halfin 0.4.0

A {regtest} bitcoin node runner 🏃‍♂️
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
// SPDX-License-Identifier: MIT OR Apache-2.0

fn main() {
    // Skip downloading when docs.rs is building documentation
    if std::env::var("DOCS_RS").is_ok() {
        return;
    }

    // Skip if the `bitcoind_31_0` feature is not enabled.
    if cfg!(feature = "bitcoind_31_0") {
        // Check if `bitcoind` is cached, and download it if not.
        bitcoind::download();
    }
    // Skip if the `utreeoxd_0_5_2` feature is not enabled.
    if cfg!(feature = "utreexod_0_5_2") {
        // Check if `utreexod` is cached, and download it if not.
        utreexod::download();
    }
    // Skip if the `electrs_0_11_1` feature is not enabled.
    if cfg!(feature = "electrs_0_11_1") {
        // Check if `electrs` is cached, and download it if not.
        electrs::download();
    }
}

/// Downloads and verifies the `bitcoind` binary based on the enabled version feature.
///
/// Binaries are verified agains the corresponding SHA256SUM under `sha256/bitcoind`.
///
/// If the binary was previously dowloaded and exists under `target/bin/bitcoin`, it won't download again.
mod bitcoind {
    use std::env;
    use std::ffi::OsStr;
    use std::fs;
    use std::fs::File;
    use std::io;
    use std::io::BufRead;
    use std::io::BufReader;
    use std::io::Cursor;
    use std::path::PathBuf;

    use std::str::FromStr;

    use bitcoin_hashes::sha256;
    use flate2::read::GzDecoder;
    use tar::Archive;

    include!("src/bitcoind/versions.rs");

    /// Return the platform-specific tarball filename for this version of `bitcoind`.
    ///
    /// Panics if the current OS/architecture combination is not supported.
    fn get_download_filename() -> String {
        if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
            return format!("bitcoin-{}-arm64-apple-darwin.tar.gz", BITCOIND_VERSION);
        }
        if cfg!(all(target_os = "macos", target_arch = "x86_64")) {
            return format!("bitcoin-{}-x86_64-apple-darwin.tar.gz", BITCOIND_VERSION);
        }
        if cfg!(all(target_os = "linux", target_arch = "x86_64")) {
            return format!("bitcoin-{}-x86_64-linux-gnu.tar.gz", BITCOIND_VERSION);
        }
        if cfg!(all(target_os = "linux", target_arch = "aarch64")) {
            return format!("bitcoin-{}-aarch64-linux-gnu.tar.gz", BITCOIND_VERSION);
        }
        if cfg!(all(target_os = "windows", target_arch = "x86_64")) {
            return format!("bitcoin-{}-win64.zip", BITCOIND_VERSION);
        }
        panic!("No download file for this OS+Architecture combination");
    }

    /// Look up the expected SHA256 hash for `filename` from the bundled `SHA256SUMS` file.
    ///
    /// Panics if the filename is not found in the checksum file.
    #[allow(clippy::lines_filter_map_ok)]
    fn get_expected_sha256(bin_name: &str) -> sha256::Hash {
        let sha256sums_filename = format!(
            "sha256/bitcoind/bitcoin-core-{}-SHA256SUMS",
            BITCOIND_VERSION
        );
        let file = File::open(&sha256sums_filename)
            .map_err(|e| {
                format!(
                    "Cannot open `bitcoind` SHA256SUMS file={}: {:?}",
                    sha256sums_filename, e
                )
            })
            .unwrap();

        for line in BufReader::new(file).lines().flatten() {
            let tokens: Vec<_> = line.split("  ").collect();
            if tokens.len() == 2 && bin_name == tokens[1] {
                return sha256::Hash::from_str(tokens[0]).unwrap();
            }
        }

        // Failed to get the expected SHA256SUM for the binary. Is it present in the file?
        panic!(
            "Failed to find SHA256SUM for binary={} at file={}",
            bin_name, sha256sums_filename
        );
    }

    /// Download, verify, and extract the `bitcoind` binary into
    /// `<OUT_DIR>/bin/bitcoin-<VERSION>/bitcoind`, or
    /// `<HALFIN_BIN_DIR>/bitcoin-<VERSION>/bitcoind` if the
    /// `HALFIN_BIN_DIR` environment variable is set.
    ///
    /// Skips the download if the binary is already cached from a previous build.
    pub(crate) fn download() {
        const BITCOIND_DOWNLOAD_URL: &str = "https://bin.luisschwab.net";

        let download_directory = if let Ok(path) = env::var("HALFIN_BIN_DIR") {
            PathBuf::from(path)
        } else {
            PathBuf::from(env::var("OUT_DIR").unwrap()).join("bin")
        };

        fs::create_dir_all(&download_directory)
            .map_err(|e| {
                format!(
                    "Cannot create `bitcoind` download directory at={}: {:?}",
                    download_directory.display(),
                    e
                )
            })
            .unwrap();

        let existing_filename = download_directory
            .join(format!("bitcoin-{}", BITCOIND_VERSION))
            .join("bitcoind");

        // Emit the binary path an an environment variable
        // so that `get_bitcoind_path` picks it up.
        println!(
            "cargo:rustc-env=HALFIN_BITCOIND_PATH={}",
            existing_filename.display()
        );

        let download_filename = get_download_filename();
        let expected_hash = get_expected_sha256(&download_filename);

        if existing_filename.exists() {
            return;
        }

        let bitcoind_tarball_bytes = {
            let download_url = format!(
                "{}/bitcoin-core-{}/{}",
                BITCOIND_DOWNLOAD_URL, BITCOIND_VERSION, download_filename
            );

            println!(
                "cargo:warning=Downloading `bitcoind` @ v{} from `{}`",
                BITCOIND_VERSION, download_url,
            );

            let response = bitreq::get(&download_url)
                .send()
                .map_err(|e| format!("Failed to GET {}: {:?}", download_url, e))
                .unwrap();

            assert_eq!(
                response.status_code, 200,
                "Failed to GET {}: {} {}",
                download_url, response.status_code, response.reason_phrase
            );

            response.as_bytes().to_vec()
        };

        let bitcoind_tarball_hash = sha256::Hash::hash(&bitcoind_tarball_bytes);
        assert_eq!(
            bitcoind_tarball_hash, expected_hash,
            "Downloaded bitcoind binary hash does not match expected hash: downloaded={} != expected={}",
            bitcoind_tarball_hash, expected_hash
        );

        let destination_directory =
            download_directory.join(format!("bitcoin-{}", BITCOIND_VERSION));
        fs::create_dir_all(&destination_directory)
            .map_err(|e| {
                format!(
                    "Cannot create destination directory={}: {}",
                    destination_directory.display(),
                    e
                )
            })
            .unwrap();

        if download_filename.ends_with(".tar.gz") {
            let gz_decoder = GzDecoder::new(&bitcoind_tarball_bytes[..]);
            let mut archive = Archive::new(gz_decoder);

            for mut entry in archive.entries().unwrap().flatten() {
                if let Ok(path) = entry.path() {
                    if path.file_name() == Some(OsStr::new("bitcoind")) {
                        let destination_path = destination_directory.join("bitcoind");
                        let mut output_file = File::create(&destination_path)
                            .map_err(|e| {
                                format!(
                                    "Cannot create `bitcoind` at destination={}: {}",
                                    destination_path.display(),
                                    e
                                )
                            })
                            .unwrap();

                        io::copy(&mut entry, &mut output_file).unwrap();

                        #[cfg(unix)]
                        {
                            use std::os::unix::fs::PermissionsExt;
                            let mut perms = output_file.metadata().unwrap().permissions();
                            perms.set_mode(0o755);
                            output_file.set_permissions(perms).unwrap();
                        }
                        break;
                    }
                }
            }
        } else if download_filename.ends_with(".zip") {
            let cursor = Cursor::new(bitcoind_tarball_bytes);
            let mut archive = zip::ZipArchive::new(cursor).unwrap();

            for i in 0..archive.len() {
                let mut file = archive.by_index(i).unwrap();
                if file
                    .enclosed_name()
                    .is_some_and(|p| p.file_name() == Some(OsStr::new("bitcoind.exe")))
                {
                    let destination_path = destination_directory.join("bitcoind.exe");
                    let mut output_file = File::create(&destination_path)
                        .map_err(|e| {
                            format!(
                                "Cannot create `bitcoind.exe` at destination={}: {}",
                                destination_path.display(),
                                e
                            )
                        })
                        .unwrap();

                    io::copy(&mut file, &mut output_file).unwrap();
                    break;
                }
            }
        }

        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        {
            use std::process::Command;

            let signing_status = Command::new("codesign")
                .arg("-v")
                .arg(&existing_filename)
                .status()
                .map_err(|e| format!("Failed to run `codesign -v` on `bitcoind`: {}", e))
                .unwrap();

            if !signing_status.success() {
                Command::new("codesign")
                    .arg("-s")
                    .arg("-")
                    .arg(&existing_filename)
                    .status()
                    .map_err(|e| format!("Failed to run `codesign -s` on `bitcoind`: {}", e))
                    .unwrap();
            }
        }
    }
}

/// Downloads and verifies the `utreexod` binary based on the enabled version feature.
///
/// Binaries are verified agains the corresponding SHA256SUM under `sha256/utreexod`.
///
/// If the binary was previously dowloaded and exists under `target/bin/utreexod`, it won't download again.
mod utreexod {
    use std::env;
    use std::ffi::OsStr;
    use std::fs;
    use std::fs::File;
    use std::io;
    use std::io::BufRead;
    use std::io::BufReader;
    use std::io::Cursor;
    use std::path::PathBuf;

    use std::str::FromStr;

    use bitcoin_hashes::sha256;
    use flate2::read::GzDecoder;
    use tar::Archive;

    include!("src/utreexod/versions.rs");

    /// Return the platform-specific tarball filename for this version of `utreexod`.
    ///
    /// Panics if the current OS/architecture combination is not supported.
    fn get_download_filename() -> String {
        if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
            return "utreexod-darwin-arm64.tar.gz".to_string();
        }
        if cfg!(all(target_os = "macos", target_arch = "x86_64")) {
            return "utreexod-darwin-amd64.tar.gz".to_string();
        }
        if cfg!(all(target_os = "linux", target_arch = "x86_64")) {
            return "utreexod-linux-amd64.tar.gz".to_string();
        }
        if cfg!(all(target_os = "linux", target_arch = "aarch64")) {
            return "utreexod-linux-arm64.tar.gz".to_string();
        }
        if cfg!(all(target_os = "windows", target_arch = "x86_64")) {
            return "utreexod-windows-amd64.zip".to_string();
        }
        panic!("No download file for this OS+Architecture combination");
    }

    /// Look up the expected SHA256 hash for `filename` from the bundled `SHA256SUMS` file.
    ///
    /// Panics if the filename is not found in the checksum file.
    #[allow(clippy::lines_filter_map_ok)]
    fn get_expected_sha256(bin_name: &str) -> sha256::Hash {
        let sha256sums_filename =
            format!("sha256/utreexod/utreexod-{}-SHA256SUMS", UTREEXOD_VERSION);

        let file = File::open(&sha256sums_filename)
            .map_err(|e| {
                format!(
                    "Cannot open `utreexod` SHA256SUMS file={}: {:?}",
                    sha256sums_filename, e
                )
            })
            .unwrap();

        for line in BufReader::new(file).lines().flatten() {
            let tokens: Vec<_> = line.split("  ").collect();
            if tokens.len() == 2 && bin_name == tokens[1] {
                return sha256::Hash::from_str(tokens[0]).unwrap();
            }
        }

        // Failed to get the expected SHA256SUM for the binary. Is it present in the file?
        panic!(
            "Failed to find SHA256SUM for utreexod binary={} at path={}",
            bin_name, sha256sums_filename
        );
    }

    /// Download, verify, and extract the `utreexod` binary into
    /// `<OUT_DIR>/bin/utreexod-<VERSION>/utreexod`, or
    /// `<HALFIN_BIN_DIR>/utreexod-<VERSION>/utreexod` if the
    /// the `HALFIN_BIN_DIR` environment variable is set.
    ///
    /// Skips the download if the binary is already cached from a previous build.
    pub(crate) fn download() {
        const UTREEXOD_DOWNLOAD_URL: &str = "https://bin.luisschwab.net";

        let download_directory = if let Ok(path) = env::var("HALFIN_BIN_DIR") {
            PathBuf::from(path)
        } else {
            PathBuf::from(env::var("OUT_DIR").unwrap()).join("bin")
        };

        fs::create_dir_all(&download_directory)
            .map_err(|e| {
                format!(
                    "Cannot create `utreexod` download directory at={}: {:?}",
                    download_directory.display(),
                    e
                )
            })
            .unwrap();

        let existing_filename = download_directory
            .join(format!("utreexod-{}", UTREEXOD_VERSION))
            .join("utreexod");

        // Emit the binary path an an environment variable
        // so that `get_utreexod_path` picks it up.
        println!(
            "cargo:rustc-env=HALFIN_UTREEXOD_PATH={}",
            existing_filename.display()
        );

        let download_filename = get_download_filename();
        let expected_hash = get_expected_sha256(&download_filename);

        if existing_filename.exists() {
            return;
        }

        let utreexod_tarball_bytes = {
            let download_url = format!(
                "{}/utreexod-{}/{}",
                UTREEXOD_DOWNLOAD_URL, UTREEXOD_VERSION, download_filename
            );

            println!(
                "cargo:warning=Downloading `utreexod` @ v{} from `{}`",
                UTREEXOD_VERSION, download_url,
            );

            let response = bitreq::get(&download_url)
                .send()
                .map_err(|e| format!("Failed to GET {}: {:?}", download_url, e))
                .unwrap();

            assert_eq!(
                response.status_code, 200,
                "Failed to GET {}: {} {}",
                download_url, response.status_code, response.reason_phrase
            );

            let utreexod_tarball = response.as_bytes().to_vec();

            utreexod_tarball
        };

        let utreexod_tarball_hash = sha256::Hash::hash(&utreexod_tarball_bytes);
        assert_eq!(
            utreexod_tarball_hash, expected_hash,
            "Downloaded utreexod binary hash does not match expected hash: downloaded={} != expected={}",
            utreexod_tarball_hash, expected_hash
        );

        let destination_directory =
            download_directory.join(format!("utreexod-{}", UTREEXOD_VERSION));
        fs::create_dir_all(&destination_directory)
            .map_err(|e| {
                format!(
                    "Cannot create destination directory={}: {}",
                    destination_directory.display(),
                    e
                )
            })
            .unwrap();

        if download_filename.ends_with(".tar.gz") {
            let gz_decoder = GzDecoder::new(&utreexod_tarball_bytes[..]);
            let mut archive = Archive::new(gz_decoder);

            for mut entry in archive.entries().unwrap().flatten() {
                if let Ok(path) = entry.path() {
                    if path.file_name() == Some(OsStr::new("utreexod")) {
                        let destination_path = destination_directory.join("utreexod");
                        let mut outputfile = File::create(&destination_path)
                            .map_err(|e| {
                                format!(
                                    "Cannot create `utreexod` at destination={}: {}",
                                    destination_path.display(),
                                    e
                                )
                            })
                            .unwrap();

                        io::copy(&mut entry, &mut outputfile).unwrap();

                        #[cfg(unix)]
                        {
                            use std::os::unix::fs::PermissionsExt;
                            let mut perms = outputfile.metadata().unwrap().permissions();
                            perms.set_mode(0o755);
                            outputfile.set_permissions(perms).unwrap();
                        }
                        break;
                    }
                }
            }
        } else if download_filename.ends_with(".zip") {
            let cursor = Cursor::new(utreexod_tarball_bytes);
            let mut archive = zip::ZipArchive::new(cursor).unwrap();

            for i in 0..archive.len() {
                let mut file = archive.by_index(i).unwrap();
                if file
                    .enclosed_name()
                    .is_some_and(|p| p.file_name() == Some(OsStr::new("utreexod.exe")))
                {
                    let destination_path = destination_directory.join("utreexod.exe");
                    let mut outputfile = File::create(&destination_path)
                        .map_err(|e| {
                            format!(
                                "Cannot create `utreexod.exe` at destination={}: {}",
                                destination_path.display(),
                                e
                            )
                        })
                        .unwrap();

                    io::copy(&mut file, &mut outputfile).unwrap();
                    break;
                }
            }
        }

        // MacOS (`arm64`) requires binaries to be code-signed locally for the OS to allow it's execution.
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        {
            use std::process::Command;

            let signing_status = Command::new("codesign")
                .arg("-v")
                .arg(&existing_filename)
                .status()
                .map_err(|e| format!("Failed to run `codesign -v` on `utreexod`: {}", e))
                .unwrap();

            if !signing_status.success() {
                Command::new("codesign")
                    .arg("-s")
                    .arg("-")
                    .arg(&existing_filename)
                    .status()
                    .map_err(|e| format!("Failed to run `codesign -s` on `utreexod`: {}", e))
                    .unwrap();
            }
        }
    }
}

/// Downloads and verifies the `electrs` binary based on the enabled version feature.
mod electrs {
    use std::env;
    use std::ffi::OsStr;
    use std::fs;
    use std::fs::File;
    use std::io;
    use std::io::BufRead;
    use std::io::BufReader;
    use std::io::Cursor;
    use std::path::PathBuf;
    use std::str::FromStr;

    use bitcoin_hashes::sha256;
    use flate2::read::GzDecoder;
    use tar::Archive;

    include!("src/electrsd/versions.rs");

    const ELECTRS_DOWNLOAD_URL: &str = "https://bin.luisschwab.net";

    /// Return the platform-specific archive filename for this version of `electrs`.
    ///
    /// Panics if the current OS/architecture combination is not supported.
    fn get_download_filename() -> String {
        if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
            return "electrs-darwin-arm64.tar.gz".to_string();
        }
        if cfg!(all(target_os = "macos", target_arch = "x86_64")) {
            return "electrs-darwin-amd64.tar.gz".to_string();
        }
        if cfg!(all(target_os = "linux", target_arch = "x86_64")) {
            return "electrs-linux-amd64.tar.gz".to_string();
        }
        if cfg!(all(target_os = "linux", target_arch = "aarch64")) {
            return "electrs-linux-arm64.tar.gz".to_string();
        }
        if cfg!(all(target_os = "windows", target_arch = "x86_64")) {
            return "electrs-windows-amd64.zip".to_string();
        }
        if cfg!(all(target_os = "windows", target_arch = "aarch64")) {
            return "electrs-windows-arm64.zip".to_string();
        }
        panic!("No download file for this OS+Architecture combination");
    }

    fn remote_dist_url() -> String {
        format!("{}/electrs-{}", ELECTRS_DOWNLOAD_URL, ELECTRS_VERSION)
    }

    /// Look up the expected SHA256 hash for `filename` from the bundled `SHA256SUMS` file.
    ///
    /// Panics if the filename is not found in the checksum file.
    #[allow(clippy::lines_filter_map_ok)]
    fn get_expected_sha256(bin_name: &str) -> sha256::Hash {
        let sha256sums_filename = format!("sha256/electrsd/electrs-{}-SHA256SUMS", ELECTRS_VERSION);

        let file = File::open(&sha256sums_filename)
            .map_err(|e| {
                format!(
                    "Cannot open `electrs` SHA256SUMS file={}: {:?}",
                    sha256sums_filename, e
                )
            })
            .unwrap();

        for line in BufReader::new(file).lines().flatten() {
            let tokens: Vec<_> = line.split("  ").collect();
            if tokens.len() == 2 && bin_name == tokens[1] {
                return sha256::Hash::from_str(tokens[0]).unwrap();
            }
        }

        panic!(
            "Failed to find SHA256SUM for electrs binary={} at path={}",
            bin_name, sha256sums_filename
        );
    }

    /// Read, verify, and extract the `electrs` binary into
    /// `<OUT_DIR>/bin/electrs-<VERSION>/electrs`, or
    /// `<HALFIN_BIN_DIR>/electrs-<VERSION>/electrs` if the
    /// `HALFIN_BIN_DIR` environment variable is set.
    ///
    /// Skips extraction if the binary is already cached from a previous build.
    pub(crate) fn download() {
        let download_directory = if let Ok(path) = env::var("HALFIN_BIN_DIR") {
            PathBuf::from(path)
        } else {
            PathBuf::from(env::var("OUT_DIR").unwrap()).join("bin")
        };

        fs::create_dir_all(&download_directory)
            .map_err(|e| {
                format!(
                    "Cannot create `electrs` download directory at={}: {:?}",
                    download_directory.display(),
                    e
                )
            })
            .unwrap();

        let existing_filename = download_directory
            .join(format!("electrs-{}", ELECTRS_VERSION))
            .join("electrs");

        // Emit the binary path as an environment variable
        // so that `get_electrs_path` can pick it up.
        println!(
            "cargo:rustc-env=HALFIN_ELECTRS_PATH={}",
            existing_filename.display()
        );

        let download_filename = get_download_filename();
        let expected_hash = get_expected_sha256(&download_filename);

        #[cfg(windows)]
        let existing_file_exists = existing_filename.with_extension("exe").exists();
        #[cfg(not(windows))]
        let existing_file_exists = existing_filename.exists();

        if existing_file_exists {
            return;
        }

        let electrs_archive_bytes = {
            let remote_dist_url = remote_dist_url();
            let download_url = format!("{}/{}", remote_dist_url, download_filename);

            println!(
                "cargo:warning=Downloading `electrs` @ v{} from `{}`",
                ELECTRS_VERSION, download_url,
            );

            let response = bitreq::get(&download_url)
                .send()
                .map_err(|e| format!("Failed to GET {}: {:?}", download_url, e))
                .unwrap();

            assert_eq!(
                response.status_code, 200,
                "Failed to GET {}: {} {}",
                download_url, response.status_code, response.reason_phrase
            );

            response.as_bytes().to_vec()
        };

        let electrs_archive_hash = sha256::Hash::hash(&electrs_archive_bytes);
        assert_eq!(
            electrs_archive_hash, expected_hash,
            "electrs archive hash does not match expected hash: downloaded={} != expected={}",
            electrs_archive_hash, expected_hash
        );

        let destination_directory = download_directory.join(format!("electrs-{}", ELECTRS_VERSION));
        fs::create_dir_all(&destination_directory)
            .map_err(|e| {
                format!(
                    "Cannot create destination directory={}: {}",
                    destination_directory.display(),
                    e
                )
            })
            .unwrap();

        if download_filename.ends_with(".tar.gz") {
            let gz_decoder = GzDecoder::new(&electrs_archive_bytes[..]);
            let mut archive = Archive::new(gz_decoder);

            for mut entry in archive.entries().unwrap().flatten() {
                if let Ok(path) = entry.path() {
                    if path.file_name() == Some(OsStr::new("electrs")) {
                        let destination_path = destination_directory.join("electrs");
                        let mut output_file = File::create(&destination_path)
                            .map_err(|e| {
                                format!(
                                    "Cannot create `electrs` at destination={}: {}",
                                    destination_path.display(),
                                    e
                                )
                            })
                            .unwrap();

                        io::copy(&mut entry, &mut output_file).unwrap();

                        #[cfg(unix)]
                        {
                            use std::os::unix::fs::PermissionsExt;
                            let mut perms = output_file.metadata().unwrap().permissions();
                            perms.set_mode(0o755);
                            output_file.set_permissions(perms).unwrap();
                        }
                        break;
                    }
                }
            }
        } else if download_filename.ends_with(".zip") {
            let cursor = Cursor::new(electrs_archive_bytes);
            let mut archive = zip::ZipArchive::new(cursor).unwrap();

            for i in 0..archive.len() {
                let mut file = archive.by_index(i).unwrap();
                if file
                    .enclosed_name()
                    .is_some_and(|p| p.file_name() == Some(OsStr::new("electrs.exe")))
                {
                    let destination_path = destination_directory.join("electrs.exe");
                    let mut output_file = File::create(&destination_path)
                        .map_err(|e| {
                            format!(
                                "Cannot create `electrs.exe` at destination={}: {}",
                                destination_path.display(),
                                e
                            )
                        })
                        .unwrap();

                    io::copy(&mut file, &mut output_file).unwrap();
                    break;
                }
            }
        }
    }
}