Skip to main content

forest/networks/
actors_bundle.rs

1// Copyright 2019-2026 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4use std::io::{self, Cursor};
5use std::path::Path;
6use std::sync::LazyLock;
7
8use ahash::HashMap;
9use anyhow::ensure;
10use async_compression::tokio::write::ZstdEncoder;
11use cid::Cid;
12use futures::stream::FuturesUnordered;
13use futures::{StreamExt, TryStreamExt, stream};
14use fvm_ipld_blockstore::MemoryBlockstore;
15use itertools::Itertools;
16use nunny::Vec as NonEmpty;
17use reqwest::Url;
18use serde::{Deserialize, Serialize};
19use serde_with::{DisplayFromStr, serde_as};
20use tokio::fs::File;
21use tracing::warn;
22
23use crate::daemon::bundle::{ACTOR_BUNDLE_CACHE_DIR, load_actor_bundles_from_server};
24use crate::shim::machine::BuiltinActorManifest;
25use crate::utils::db::car_stream::{CarStream, CarWriter};
26use crate::utils::net::{DownloadFileOption, download_file_with_cache};
27
28use std::str::FromStr;
29
30use super::NetworkChain;
31
32#[derive(Debug)]
33pub struct ActorBundleInfo {
34    pub manifest: Cid,
35    pub url: Url,
36    /// Alternative URL to download the bundle from if the primary URL fails.
37    /// Note that we host the bundles and so we need to update the bucket
38    /// ourselves when a new bundle is released.
39    pub alt_url: Url,
40    pub network: NetworkChain,
41    pub version: String,
42}
43
44macro_rules! actor_bundle_info {
45    ($($cid:literal @ $version:literal for $network:literal),* $(,)?) => {
46        [
47            $(
48                ActorBundleInfo {
49                    manifest: $cid.parse().unwrap(),
50                    url: concat!(
51                            "https://github.com/filecoin-project/builtin-actors/releases/download/",
52                            $version,
53                            "/builtin-actors-",
54                            $network,
55                            ".car"
56                        ).parse().unwrap(),
57                    alt_url: concat!(
58                          "https://filecoin-actors.chainsafe.dev/",
59                          $version,
60                            "/builtin-actors-",
61                            $network,
62                            ".car"
63                        ).parse().unwrap(),
64                    network: NetworkChain::from_str($network).unwrap(),
65                    version: $version.to_string(),
66                },
67            )*
68        ]
69    }
70}
71
72pub static ACTOR_BUNDLES: LazyLock<Box<[ActorBundleInfo]>> = LazyLock::new(|| {
73    Box::new(actor_bundle_info![
74        "bafy2bzacedrdn6z3z7xz7lx4wll3tlgktirhllzqxb766dxpaqp3ukxsjfsba" @ "8.0.0-rc.1" for "calibrationnet",
75        "bafy2bzacedbedgynklc4dgpyxippkxmba2mgtw7ecntoneclsvvl4klqwuyyy" @ "v9.0.3" for "calibrationnet",
76        "bafy2bzaced25ta3j6ygs34roprilbtb3f6mxifyfnm7z7ndquaruxzdq3y7lo" @ "v10.0.0-rc.1" for "calibrationnet",
77        "bafy2bzacedhuowetjy2h4cxnijz2l64h4mzpk5m256oywp4evarpono3cjhco" @ "v11.0.0-rc2" for "calibrationnet",
78        "bafy2bzacedrunxfqta5skb7q7x32lnp4efz2oq7fn226ffm7fu5iqs62jkmvs" @ "v12.0.0-rc.1" for "calibrationnet",
79        "bafy2bzacebl4w5ptfvuw6746w7ev562idkbf5ppq72e6zub22435ws2rukzru" @ "v12.0.0-rc.2" for "calibrationnet",
80        "bafy2bzacednzb3pkrfnbfhmoqtb3bc6dgvxszpqklf3qcc7qzcage4ewzxsca" @ "v12.0.0" for "calibrationnet",
81        "bafy2bzacea4firkyvt2zzdwqjrws5pyeluaesh6uaid246tommayr4337xpmi" @ "v13.0.0-rc.3" for "calibrationnet",
82        "bafy2bzacect4ktyujrwp6mjlsitnpvuw2pbuppz6w52sfljyo4agjevzm75qs" @ "v13.0.0" for "calibrationnet",
83        "bafy2bzacebq3hncszqpojglh2dkwekybq4zn6qpc4gceqbx36wndps5qehtau" @ "v14.0.0-rc.1" for "calibrationnet",
84        "bafy2bzaceax5zkysst7vtyup4whdxwzlpnaya3qp34rnoi6gyt4pongps7obw" @ "v15.0.0" for "calibrationnet",
85        "bafy2bzacebc7zpsrihpyd2jdcvmegbbk6yhzkifre3hxtoul5wdxxklbwitry" @ "v16.0.0-rc3" for "calibrationnet",
86        "bafy2bzacecqtwq6hjhj2zy5gwjp76a4tpcg2lt7dps5ycenvynk2ijqqyo65e" @ "v16.0.1" for "calibrationnet",
87        "bafy2bzacecn64rlb52rjsvgopnidz6w42z3zobmjxqek5s4xqjh3ly47rcurg" @ "v17.0.0" for "calibrationnet",
88        "bafy2bzacebkfatnbe6w4rj7lf6gkjh7mywlrpdh2dj6hu2dl4rmtwksszm2hs" @ "v18.0.0" for "calibrationnet",
89        "bafy2bzacedzjwguwuihh4tptzfkkwaj3naamrnklbaixn2wfzqh67twwp56pi" @ "v17.0.0" for "butterflynet",
90        "bafy2bzacec3ikcjko4zok3qoe7nxnqilx2mj65tp25kkkbf7bwkejflfrdpwo" @ "v18.0.0-rc1" for "butterflynet",
91        "bafy2bzacedozk3jh2j4nobqotkbofodq4chbrabioxbfrygpldgoxs3zwgggk" @ "v9.0.3" for "devnet",
92        "bafy2bzacebzz376j5kizfck56366kdz5aut6ktqrvqbi3efa2d4l2o2m653ts" @ "v10.0.0" for "devnet",
93        "bafy2bzaceay35go4xbjb45km6o46e5bib3bi46panhovcbedrynzwmm3drr4i" @ "v11.0.0" for "devnet",
94        "bafy2bzaceasjdukhhyjbegpli247vbf5h64f7uvxhhebdihuqsj2mwisdwa6o" @ "v12.0.0" for "devnet",
95        "bafy2bzacecn7uxgehrqbcs462ktl2h23u23cmduy2etqj6xrd6tkkja56fna4" @ "v13.0.0" for "devnet",
96        "bafy2bzacebwn7ymtozv5yz3x5hnxl4bds2grlgsk5kncyxjak3hqyhslb534m" @ "v14.0.0-rc.1" for "devnet",
97        "bafy2bzacedlusqjwf7chvl2ve2fum5noyqrtjzcrzkhpbzpkg7puiru7dj4ug" @ "v15.0.0-rc1" for "devnet",
98        "bafy2bzaceclp3wfrwdjgh6c3gee5smwj3zmmrhb4fdbc4yfchfaia6rlljx5o" @ "v16.0.1" for "devnet",
99        "bafy2bzaceasvgkke3j4cs3xsxnjswpcdmokkvkiehzxzcgfox3ozlehimbuqk" @ "v17.0.0" for "devnet",
100        "bafy2bzaced35gjxagazf2fne5dakbok5abmivsh7cq7huwfuptebgwjmcpcf6" @ "v18.0.0" for "devnet",
101        "bafy2bzaceb6j6666h36xnhksu3ww4kxb6e25niayfgkdnifaqi6m6ooc66i6i" @ "v9.0.3" for "mainnet",
102        "bafy2bzacecsuyf7mmvrhkx2evng5gnz5canlnz2fdlzu2lvcgptiq2pzuovos" @ "v10.0.0" for "mainnet",
103        "bafy2bzacecnhaiwcrpyjvzl4uv4q3jzoif26okl3m66q3cijp3dfwlcxwztwo" @ "v11.0.0" for "mainnet",
104        "bafy2bzaceapkgfggvxyllnmuogtwasmsv5qi2qzhc2aybockd6kag2g5lzaio" @ "v12.0.0" for "mainnet",
105        "bafy2bzacecdhvfmtirtojwhw2tyciu4jkbpsbk5g53oe24br27oy62sn4dc4e" @ "v13.0.0" for "mainnet",
106        "bafy2bzacecbueuzsropvqawsri27owo7isa5gp2qtluhrfsto2qg7wpgxnkba" @ "v14.0.0" for "mainnet",
107        "bafy2bzaceakwje2hyinucrhgtsfo44p54iw4g6otbv5ghov65vajhxgntr53u" @ "v15.0.0" for "mainnet",
108        "bafy2bzacecnepvsh4lw6pwljobvwm6zwu6mbwveatp7llhpuguvjhjiqz7o46" @ "v16.0.1" for "mainnet",
109        "bafy2bzaceai74ppsvuxs3nvpzzeuptdr3wl7vmdpbphvtz4qt5hfq2qdfvz3e" @ "v17.0.0" for "mainnet",
110    ])
111});
112
113#[serde_as]
114#[derive(Serialize, Deserialize, Debug, PartialEq)]
115pub struct ActorBundleMetadata {
116    pub network: NetworkChain,
117    pub version: String,
118    #[serde_as(as = "DisplayFromStr")]
119    pub bundle_cid: Cid,
120    pub manifest: BuiltinActorManifest,
121}
122
123impl ActorBundleMetadata {
124    pub fn actor_major_version(&self) -> anyhow::Result<u64> {
125        self.version
126            .trim_start_matches('v')
127            .split('.')
128            .next()
129            .ok_or_else(|| anyhow::anyhow!("invalid version"))
130            .and_then(|s| s.parse().map_err(|_| anyhow::anyhow!("invalid version")))
131    }
132}
133
134type ActorBundleMetadataMap = HashMap<(NetworkChain, String), ActorBundleMetadata>;
135
136pub static ACTOR_BUNDLES_METADATA: LazyLock<ActorBundleMetadataMap> = LazyLock::new(|| {
137    let json: &str = include_str!("../../build/manifest.json");
138    let metadata_vec: Vec<ActorBundleMetadata> =
139        serde_json::from_str(json).expect("invalid manifest");
140    metadata_vec
141        .into_iter()
142        .map(|metadata| {
143            (
144                (metadata.network.clone(), metadata.version.clone()),
145                metadata,
146            )
147        })
148        .collect()
149});
150
151pub async fn get_actor_bundles_metadata() -> anyhow::Result<Vec<ActorBundleMetadata>> {
152    let store = MemoryBlockstore::new();
153    for network in [
154        NetworkChain::Mainnet,
155        NetworkChain::Calibnet,
156        NetworkChain::Butterflynet,
157        NetworkChain::Devnet(Default::default()),
158    ] {
159        load_actor_bundles_from_server(&store, &network, &ACTOR_BUNDLES).await?;
160    }
161
162    ACTOR_BUNDLES
163        .iter()
164        .map(|bundle| -> anyhow::Result<_> {
165            Ok(ActorBundleMetadata {
166                network: bundle.network.clone(),
167                version: bundle.version.clone(),
168                bundle_cid: bundle.manifest,
169                manifest: BuiltinActorManifest::load_manifest(&store, &bundle.manifest)?,
170            })
171        })
172        .collect()
173}
174
175pub async fn generate_actor_bundle(output: &Path) -> anyhow::Result<()> {
176    let (mut roots, blocks) = FuturesUnordered::from_iter(ACTOR_BUNDLES.iter().map(
177        |ActorBundleInfo {
178             manifest: root,
179             url,
180             alt_url,
181             network,
182             version,
183         }| async move {
184            let result = if let Ok(response) =
185                download_file_with_cache(url, &ACTOR_BUNDLE_CACHE_DIR, DownloadFileOption::NonResumable).await
186            {
187                response
188            } else {
189                warn!(
190                    "failed to download bundle {network}-{version} from primary URL, trying alternative URL"
191                );
192                download_file_with_cache(alt_url, &ACTOR_BUNDLE_CACHE_DIR, DownloadFileOption::NonResumable).await?
193            };
194
195            let bytes = std::fs::read(&result.path)?;
196            let car = CarStream::new(Cursor::new(bytes)).await?;
197            ensure!(car.header_v1.roots.len() == 1);
198            ensure!(car.header_v1.roots.first() == root);
199            anyhow::Ok((*root, car.try_collect::<Vec<_>>().await?))
200        },
201    ))
202    .try_collect::<Vec<_>>()
203    .await?
204    .into_iter()
205    .unzip::<_, _, Vec<_>, Vec<_>>();
206
207    ensure!(roots.iter().all_unique());
208
209    roots.sort(); // deterministic
210
211    let mut blocks = blocks.into_iter().flatten().collect_vec();
212    blocks.sort();
213    blocks.dedup();
214
215    for block in blocks.iter() {
216        block.validate()?;
217    }
218
219    stream::iter(blocks)
220        .map(io::Result::Ok)
221        .forward(CarWriter::new_carv1(
222            NonEmpty::new(roots).map_err(|_| anyhow::Error::msg("car roots cannot be empty"))?,
223            ZstdEncoder::with_quality(
224                File::create(&output).await?,
225                async_compression::Level::Precise(17),
226            ),
227        )?)
228        .await?;
229
230    Ok(())
231}
232
233#[cfg(test)]
234mod tests {
235    use http::StatusCode;
236    use reqwest::Response;
237    use std::time::Duration;
238
239    use crate::utils::net::global_http_client;
240
241    use super::*;
242
243    #[tokio::test]
244    async fn check_bundles_are_mirrored() {
245        // Run the test only in CI so that regular test on dev machines don't download the bundles
246        // on poor internet connections.
247        if std::env::var("CI").is_err() {
248            return;
249        }
250
251        FuturesUnordered::from_iter(ACTOR_BUNDLES.iter().map(
252            |ActorBundleInfo {
253                 manifest,
254                 url,
255                 alt_url,
256                 network: _,
257                 version: _,
258             }| async move {
259                let (primary, alt) = match (http_get(url).await, http_get(alt_url).await) {
260                    (Ok(primary), Ok(alt)) => (primary, alt),
261                    (Err(_), Err(_)) => anyhow::bail!("Both sources are down"),
262                    // If either of the sources are otherwise down, we don't want to fail the test.
263                    _ => return anyhow::Ok(()),
264                };
265
266                // Check that neither of the sources respond with 404.
267                // Such code would indicate that the bundle URLs are incorrect.
268                // In case of GH releases, it may have been yanked for some reason.
269                // In case of our own bundles, it may have been not uploaded (or deleted).
270                assert_ne!(
271                    StatusCode::NOT_FOUND,
272                    primary.status(),
273                    "Could not download {url}"
274                );
275                assert_ne!(
276                    StatusCode::NOT_FOUND,
277                    alt.status(),
278                    "Could not download {alt_url}"
279                );
280
281                // If either of the sources are otherwise down, we don't want to fail the test.
282                // This is because we don't want to fail the test if the infrastructure is down.
283                if !primary.status().is_success() || !alt.status().is_success() {
284                    return anyhow::Ok(());
285                }
286
287                // Check that the bundles are identical.
288                // This is to ensure that the bundle was not tamperered with and that the
289                // bundle was uploaded to the alternative URL correctly.
290                let (primary, alt) = match (primary.bytes().await, alt.bytes().await) {
291                    (Ok(primary), Ok(alt)) => (primary, alt),
292                    (Err(_), Err(_)) => anyhow::bail!("Both sources are down"),
293                    // If either of the sources are otherwise down, we don't want to fail the test.
294                    _ => return anyhow::Ok(()),
295                };
296
297                let (car_primary, car_secondary) = tokio::try_join!(
298                    CarStream::new(Cursor::new(primary)),
299                    CarStream::new(Cursor::new(alt)),
300                )?;
301
302                assert_eq!(
303                    car_primary.header_v1.roots, car_secondary.header_v1.roots,
304                    "Roots for {url} and {alt_url} do not match"
305                );
306                assert_eq!(
307                    car_primary.header_v1.roots.first(),
308                    manifest,
309                    "Manifest for {url} and {alt_url} does not match"
310                );
311
312                Ok(())
313            },
314        ))
315        .try_collect::<Vec<_>>()
316        .await
317        .unwrap();
318    }
319
320    pub async fn http_get(url: &Url) -> anyhow::Result<Response> {
321        Ok(global_http_client()
322            .get(url.clone())
323            .timeout(Duration::from_secs(120))
324            .send()
325            .await?)
326    }
327
328    #[test]
329    fn test_actor_major_version_correct() {
330        let cases = [
331            ("8.0.0-rc.1", 8),
332            ("v9.0.3", 9),
333            ("v10.0.0-rc.1", 10),
334            ("v12.0.0", 12),
335            ("v13.0.0-rc.3", 13),
336            ("v13.0.0", 13),
337            ("v14.0.0-rc.1", 14),
338        ];
339
340        for (version, expected) in cases.iter() {
341            let metadata = ActorBundleMetadata {
342                network: NetworkChain::Mainnet,
343                version: version.to_string(),
344                bundle_cid: Default::default(),
345                manifest: Default::default(),
346            };
347
348            assert_eq!(metadata.actor_major_version().unwrap(), *expected);
349        }
350    }
351
352    #[test]
353    fn test_actor_major_version_invalid() {
354        let cases = ["cthulhu", "vscode", ".02", "-42"];
355
356        for version in cases.iter() {
357            let metadata = ActorBundleMetadata {
358                network: NetworkChain::Mainnet,
359                version: version.to_string(),
360                bundle_cid: Default::default(),
361                manifest: Default::default(),
362            };
363
364            assert!(metadata.actor_major_version().is_err());
365        }
366    }
367}