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        "bafy2bzacearjal5rsmzloz3ny7aoju2rgw66wgxdrydgg27thcsazbmf5qihq" @ "v15.0.0-rc1" for "butterflynet",
89        "bafy2bzaceda5lc7qrwp2hdm6s6erppwuydsfqrhbgld7juixalk342inqimbo" @ "v16.0.1" for "butterflynet",
90        "bafy2bzacedzjwguwuihh4tptzfkkwaj3naamrnklbaixn2wfzqh67twwp56pi" @ "v17.0.0" 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        "bafy2bzaceb6j6666h36xnhksu3ww4kxb6e25niayfgkdnifaqi6m6ooc66i6i" @ "v9.0.3" for "mainnet",
101        "bafy2bzacecsuyf7mmvrhkx2evng5gnz5canlnz2fdlzu2lvcgptiq2pzuovos" @ "v10.0.0" for "mainnet",
102        "bafy2bzacecnhaiwcrpyjvzl4uv4q3jzoif26okl3m66q3cijp3dfwlcxwztwo" @ "v11.0.0" for "mainnet",
103        "bafy2bzaceapkgfggvxyllnmuogtwasmsv5qi2qzhc2aybockd6kag2g5lzaio" @ "v12.0.0" for "mainnet",
104        "bafy2bzacecdhvfmtirtojwhw2tyciu4jkbpsbk5g53oe24br27oy62sn4dc4e" @ "v13.0.0" for "mainnet",
105        "bafy2bzacecbueuzsropvqawsri27owo7isa5gp2qtluhrfsto2qg7wpgxnkba" @ "v14.0.0" for "mainnet",
106        "bafy2bzaceakwje2hyinucrhgtsfo44p54iw4g6otbv5ghov65vajhxgntr53u" @ "v15.0.0" for "mainnet",
107        "bafy2bzacecnepvsh4lw6pwljobvwm6zwu6mbwveatp7llhpuguvjhjiqz7o46" @ "v16.0.1" for "mainnet",
108        "bafy2bzaceai74ppsvuxs3nvpzzeuptdr3wl7vmdpbphvtz4qt5hfq2qdfvz3e" @ "v17.0.0" for "mainnet",
109    ])
110});
111
112#[serde_as]
113#[derive(Serialize, Deserialize, Debug, PartialEq)]
114pub struct ActorBundleMetadata {
115    pub network: NetworkChain,
116    pub version: String,
117    #[serde_as(as = "DisplayFromStr")]
118    pub bundle_cid: Cid,
119    pub manifest: BuiltinActorManifest,
120}
121
122impl ActorBundleMetadata {
123    pub fn actor_major_version(&self) -> anyhow::Result<u64> {
124        self.version
125            .trim_start_matches('v')
126            .split('.')
127            .next()
128            .ok_or_else(|| anyhow::anyhow!("invalid version"))
129            .and_then(|s| s.parse().map_err(|_| anyhow::anyhow!("invalid version")))
130    }
131}
132
133type ActorBundleMetadataMap = HashMap<(NetworkChain, String), ActorBundleMetadata>;
134
135pub static ACTOR_BUNDLES_METADATA: LazyLock<ActorBundleMetadataMap> = LazyLock::new(|| {
136    let json: &str = include_str!("../../build/manifest.json");
137    let metadata_vec: Vec<ActorBundleMetadata> =
138        serde_json::from_str(json).expect("invalid manifest");
139    metadata_vec
140        .into_iter()
141        .map(|metadata| {
142            (
143                (metadata.network.clone(), metadata.version.clone()),
144                metadata,
145            )
146        })
147        .collect()
148});
149
150pub async fn get_actor_bundles_metadata() -> anyhow::Result<Vec<ActorBundleMetadata>> {
151    let store = MemoryBlockstore::new();
152    for network in [
153        NetworkChain::Mainnet,
154        NetworkChain::Calibnet,
155        NetworkChain::Butterflynet,
156        NetworkChain::Devnet(Default::default()),
157    ] {
158        load_actor_bundles_from_server(&store, &network, &ACTOR_BUNDLES).await?;
159    }
160
161    ACTOR_BUNDLES
162        .iter()
163        .map(|bundle| -> anyhow::Result<_> {
164            Ok(ActorBundleMetadata {
165                network: bundle.network.clone(),
166                version: bundle.version.clone(),
167                bundle_cid: bundle.manifest,
168                manifest: BuiltinActorManifest::load_manifest(&store, &bundle.manifest)?,
169            })
170        })
171        .collect()
172}
173
174pub async fn generate_actor_bundle(output: &Path) -> anyhow::Result<()> {
175    let (mut roots, blocks) = FuturesUnordered::from_iter(ACTOR_BUNDLES.iter().map(
176        |ActorBundleInfo {
177             manifest: root,
178             url,
179             alt_url,
180             network,
181             version,
182         }| async move {
183            let result = if let Ok(response) =
184                download_file_with_cache(url, &ACTOR_BUNDLE_CACHE_DIR, DownloadFileOption::NonResumable).await
185            {
186                response
187            } else {
188                warn!(
189                    "failed to download bundle {network}-{version} from primary URL, trying alternative URL"
190                );
191                download_file_with_cache(alt_url, &ACTOR_BUNDLE_CACHE_DIR, DownloadFileOption::NonResumable).await?
192            };
193
194            let bytes = std::fs::read(&result.path)?;
195            let car = CarStream::new(Cursor::new(bytes)).await?;
196            ensure!(car.header_v1.roots.len() == 1);
197            ensure!(car.header_v1.roots.first() == root);
198            anyhow::Ok((*root, car.try_collect::<Vec<_>>().await?))
199        },
200    ))
201    .try_collect::<Vec<_>>()
202    .await?
203    .into_iter()
204    .unzip::<_, _, Vec<_>, Vec<_>>();
205
206    ensure!(roots.iter().all_unique());
207
208    roots.sort(); // deterministic
209
210    let mut blocks = blocks.into_iter().flatten().collect_vec();
211    blocks.sort();
212    blocks.dedup();
213
214    for block in blocks.iter() {
215        block.validate()?;
216    }
217
218    stream::iter(blocks)
219        .map(io::Result::Ok)
220        .forward(CarWriter::new_carv1(
221            NonEmpty::new(roots).map_err(|_| anyhow::Error::msg("car roots cannot be empty"))?,
222            ZstdEncoder::with_quality(
223                File::create(&output).await?,
224                async_compression::Level::Precise(17),
225            ),
226        )?)
227        .await?;
228
229    Ok(())
230}
231
232#[cfg(test)]
233mod tests {
234    use http::StatusCode;
235    use reqwest::Response;
236    use std::time::Duration;
237
238    use crate::utils::net::global_http_client;
239
240    use super::*;
241
242    #[tokio::test]
243    async fn check_bundles_are_mirrored() {
244        // Run the test only in CI so that regular test on dev machines don't download the bundles
245        // on poor internet connections.
246        if std::env::var("CI").is_err() {
247            return;
248        }
249
250        FuturesUnordered::from_iter(ACTOR_BUNDLES.iter().map(
251            |ActorBundleInfo {
252                 manifest,
253                 url,
254                 alt_url,
255                 network: _,
256                 version: _,
257             }| async move {
258                let (primary, alt) = match (http_get(url).await, http_get(alt_url).await) {
259                    (Ok(primary), Ok(alt)) => (primary, alt),
260                    (Err(_), Err(_)) => anyhow::bail!("Both sources are down"),
261                    // If either of the sources are otherwise down, we don't want to fail the test.
262                    _ => return anyhow::Ok(()),
263                };
264
265                // Check that neither of the sources respond with 404.
266                // Such code would indicate that the bundle URLs are incorrect.
267                // In case of GH releases, it may have been yanked for some reason.
268                // In case of our own bundles, it may have been not uploaded (or deleted).
269                assert_ne!(
270                    StatusCode::NOT_FOUND,
271                    primary.status(),
272                    "Could not download {url}"
273                );
274                assert_ne!(
275                    StatusCode::NOT_FOUND,
276                    alt.status(),
277                    "Could not download {alt_url}"
278                );
279
280                // If either of the sources are otherwise down, we don't want to fail the test.
281                // This is because we don't want to fail the test if the infrastructure is down.
282                if !primary.status().is_success() || !alt.status().is_success() {
283                    return anyhow::Ok(());
284                }
285
286                // Check that the bundles are identical.
287                // This is to ensure that the bundle was not tamperered with and that the
288                // bundle was uploaded to the alternative URL correctly.
289                let (primary, alt) = match (primary.bytes().await, alt.bytes().await) {
290                    (Ok(primary), Ok(alt)) => (primary, alt),
291                    (Err(_), Err(_)) => anyhow::bail!("Both sources are down"),
292                    // If either of the sources are otherwise down, we don't want to fail the test.
293                    _ => return anyhow::Ok(()),
294                };
295
296                let car_primary = CarStream::new(Cursor::new(primary)).await?;
297                let car_secondary = CarStream::new(Cursor::new(alt)).await?;
298
299                assert_eq!(
300                    car_primary.header_v1.roots, car_secondary.header_v1.roots,
301                    "Roots for {url} and {alt_url} do not match"
302                );
303                assert_eq!(
304                    car_primary.header_v1.roots.first(),
305                    manifest,
306                    "Manifest for {url} and {alt_url} does not match"
307                );
308
309                Ok(())
310            },
311        ))
312        .try_collect::<Vec<_>>()
313        .await
314        .unwrap();
315    }
316
317    pub async fn http_get(url: &Url) -> anyhow::Result<Response> {
318        Ok(global_http_client()
319            .get(url.clone())
320            .timeout(Duration::from_secs(120))
321            .send()
322            .await?)
323    }
324
325    #[test]
326    fn test_actor_major_version_correct() {
327        let cases = [
328            ("8.0.0-rc.1", 8),
329            ("v9.0.3", 9),
330            ("v10.0.0-rc.1", 10),
331            ("v12.0.0", 12),
332            ("v13.0.0-rc.3", 13),
333            ("v13.0.0", 13),
334            ("v14.0.0-rc.1", 14),
335        ];
336
337        for (version, expected) in cases.iter() {
338            let metadata = ActorBundleMetadata {
339                network: NetworkChain::Mainnet,
340                version: version.to_string(),
341                bundle_cid: Default::default(),
342                manifest: Default::default(),
343            };
344
345            assert_eq!(metadata.actor_major_version().unwrap(), *expected);
346        }
347    }
348
349    #[test]
350    fn test_actor_major_version_invalid() {
351        let cases = ["cthulhu", "vscode", ".02", "-42"];
352
353        for version in cases.iter() {
354            let metadata = ActorBundleMetadata {
355                network: NetworkChain::Mainnet,
356                version: version.to_string(),
357                bundle_cid: Default::default(),
358                manifest: Default::default(),
359            };
360
361            assert!(metadata.actor_major_version().is_err());
362        }
363    }
364}