canton_lf/decode.rs
1//! Decode a package's Daml-LF bytes into the LF 2 AST ([`Package`]), and resolve
2//! its interned package metadata — the name and version that drive SCU.
3//!
4//! LF 2.x stores every name and literal in the package's `interned_strings` /
5//! `interned_dotted_names` tables and references them by `i32` index, so the raw
6//! prost AST is index-heavy; [`interned_str`] resolves those indices.
7
8use prost::Message;
9
10use crate::dar::{Dar, DarError};
11use crate::pb::daml_lf_2::Package;
12use crate::pb::daml_lf_dev::{Archive, ArchivePayload, HashFunction, archive_payload};
13use sha2::{Digest as _, Sha256};
14
15/// An error decoding Daml-LF package bytes.
16#[derive(Debug, thiserror::Error)]
17#[non_exhaustive]
18pub enum DecodeError {
19 /// Reading the DAR container failed.
20 #[error(transparent)]
21 Dar(#[from] DarError),
22 /// The protobuf bytes were malformed.
23 #[error("malformed Daml-LF archive: {0}")]
24 Proto(#[from] prost::DecodeError),
25 /// The package is not Daml-LF 2.x (this decoder only supports LF 2.x).
26 #[error("unsupported Daml-LF version (only LF 2.x is supported)")]
27 UnsupportedVersion,
28 /// The archive's payload does not hash to the package id it declares.
29 /// Refused: that id is the package's identity — it is what generated
30 /// bindings embed as `PACKAGE_ID` and what cross-package references resolve
31 /// through — so accepting a mismatch means addressing a package by a name
32 /// its contents do not answer to.
33 #[error("archive payload does not match its declared package id {declared}")]
34 PackageIdMismatch {
35 /// The id the archive claims.
36 declared: String,
37 /// The SHA-256 of the payload actually present.
38 computed: String,
39 },
40 /// The archive declares a hash function this build does not implement.
41 #[error("unsupported archive hash function {0} (only SHA-256 is defined)")]
42 UnsupportedHashFunction(i32),
43 /// The package is LF 2.x, but a **minor** this decoder was not built
44 /// against. Refused rather than decoded: prost drops fields it does not
45 /// know, so a newer minor would otherwise yield silently incomplete
46 /// bindings — a template missing a field decodes, compiles, and then fails
47 /// on the wire.
48 #[error(
49 "Daml-LF 2.{minor} is not a version this build was compiled against \
50 (it reads {supported}); the LF protos are pinned to a Canton release, \
51 so use a DAR built for that release or upgrade the SDK"
52 )]
53 UnsupportedMinor {
54 /// The minor version the archive declares.
55 minor: String,
56 /// The versions this build accepts, comma-separated and fully spelled
57 /// (`"2.1, 2.2"`). Spelled in full rather than as bare minors because
58 /// the message renders it verbatim: a `2.` prefix in the template
59 /// would attach to the first entry only.
60 supported: String,
61 },
62 /// A decode failure attributed to a specific package in the DAR.
63 #[error("package `{name}`: {source}")]
64 InPackage {
65 /// The archive path of the `.dalf` that failed to decode.
66 name: String,
67 /// The underlying failure.
68 source: Box<DecodeError>,
69 },
70}
71
72/// Decode the DAR's **main** package into the Daml-LF 2 AST, together with its
73/// **package id** (the `Archive` hash — the input to SCU/PackageMap and to
74/// qualifying cross-package references).
75///
76/// # Errors
77/// Returns [`DecodeError`] if the container or protobuf bytes are malformed, or
78/// the package is not Daml-LF 2.x.
79pub fn decode_main_package(dar: &Dar) -> Result<(Package, String), DecodeError> {
80 decode_package(dar.main_package_bytes()?)
81}
82
83/// Decode a single package's `.dalf` bytes (an `Archive`) into the LF 2 AST and
84/// its package id (the archive hash).
85///
86/// # Errors
87/// See [`decode_main_package`].
88pub fn decode_package(archive_bytes: &[u8]) -> Result<(Package, String), DecodeError> {
89 let archive = Archive::decode(archive_bytes)?;
90 let package_id = verified_package_id(&archive)?;
91 let payload = ArchivePayload::decode(archive.payload.as_slice())?;
92 // Major first: a minor only means something once the major is LF 2. An LF 1
93 // archive — which is every DAR a Daml 2.x SDK built — carries minors like
94 // "15", and judging it by the minor gate would tell the reader that
95 // "Daml-LF 2.15" is unsupported and to upgrade the SDK. No version of this
96 // decoder will ever read it; the major is the thing to say.
97 let Some(archive_payload::Sum::DamlLf2(package)) = payload.sum else {
98 return Err(DecodeError::UnsupportedVersion);
99 };
100 check_minor(&payload.minor)?;
101 Ok((package, package_id))
102}
103
104/// The package id of an archive, checked against its contents rather than
105/// taken on trust.
106///
107/// The id is the SHA-256 of the payload, and it is load-bearing: generated
108/// bindings embed it as `Contract::PACKAGE_ID`, and every cross-package
109/// reference in the DAR resolves through it. A DAR whose declared id does not
110/// match its bytes — corrupted in transit, or assembled by hand — would
111/// otherwise produce bindings that name a package by an id its contents do not
112/// answer to, and nothing downstream would notice.
113fn verified_package_id(archive: &Archive) -> Result<String, DecodeError> {
114 // The enum has exactly one member today; anything else is a scheme this
115 // build cannot check, and an unchecked hash is the thing being fixed here.
116 if archive.hash_function != HashFunction::Sha256 as i32 {
117 return Err(DecodeError::UnsupportedHashFunction(archive.hash_function));
118 }
119
120 let computed = hex(&Sha256::digest(&archive.payload));
121 if computed == archive.hash {
122 Ok(computed)
123 } else {
124 Err(DecodeError::PackageIdMismatch {
125 declared: archive.hash.clone(),
126 computed,
127 })
128 }
129}
130
131/// Lower-case hex, the spelling Daml-LF uses for a package id.
132fn hex(bytes: &[u8]) -> String {
133 bytes
134 .iter()
135 .fold(String::with_capacity(bytes.len() * 2), |mut out, byte| {
136 use std::fmt::Write as _;
137 // Infallible: writing to a String cannot fail.
138 let _ = write!(out, "{byte:02x}");
139 out
140 })
141}
142
143/// The Daml-LF 2.x minor versions this build decodes.
144///
145/// The list is evidence, not aspiration: a survey of every DAR available here —
146/// 18 of them, 648 packages across the Splice amulet/wallet/token-standard and
147/// quickstart-licensing sets — finds 617 packages at `2.1` and 31 at `2.2`, and
148/// both spellings appear inside DARs this repo generates bindings from. Both
149/// decode correctly against the vendored schema, which the conformance oracle
150/// checks against the official JVM `daml-lf-archive` reader.
151///
152/// Adding a minor is a deliberate act with a procedure: re-vendor the protos if
153/// the new minor changes them, then re-run the oracle. Guessing instead means
154/// prost silently drops fields belonging to a schema it does not know, and the
155/// bindings come out quietly incomplete.
156const SUPPORTED_LF2_MINORS: &[&str] = &["1", "2"];
157
158/// Refuse a minor we were not built against.
159///
160/// `"dev"` is refused with everything else on purpose — it is the unstable
161/// spelling, and the whole point of this gate is that an unknown schema must
162/// not decode silently.
163fn check_minor(minor: &str) -> Result<(), DecodeError> {
164 if SUPPORTED_LF2_MINORS.contains(&minor) {
165 return Ok(());
166 }
167 Err(DecodeError::UnsupportedMinor {
168 minor: minor.to_string(),
169 supported: SUPPORTED_LF2_MINORS
170 .iter()
171 .map(|minor| format!("2.{minor}"))
172 .collect::<Vec<_>>()
173 .join(", "),
174 })
175}
176
177/// Decode **every** package in a DAR, each paired with its package id (archive
178/// hash) — the PackageMap for resolving cross-package references.
179///
180/// # Errors
181/// Returns [`DecodeError`] if any package's bytes are malformed or not LF 2.x.
182pub fn decode_all(dar: &Dar) -> Result<Vec<(String, Package)>, DecodeError> {
183 dar.package_entries()
184 .map(|(name, bytes)| {
185 let (package, id) = decode_package(bytes).map_err(|error| DecodeError::InPackage {
186 name: name.to_string(),
187 source: Box::new(error),
188 })?;
189 Ok((id, package))
190 })
191 .collect()
192}
193
194/// Resolve a `package_import_id` — an index into the package's explicit import
195/// table (`package_imports.imported_packages`) — to the target package's id
196/// hash. Newer LF (2.dev / SDK 3.5+) references imported packages this way
197/// instead of by an interned id string.
198#[must_use]
199pub fn imported_package_id(package: &Package, index: i32) -> Option<&str> {
200 let imports = package.package_imports.as_ref()?;
201 let i = usize::try_from(index).ok()?;
202 imports.imported_packages.get(i).map(String::as_str)
203}
204
205/// Resolve an interned string by its `i32` index into a package's
206/// `interned_strings` table.
207#[must_use]
208pub fn interned_str(package: &Package, index: i32) -> Option<&str> {
209 usize::try_from(index)
210 .ok()
211 .and_then(|i| package.interned_strings.get(i))
212 .map(String::as_str)
213}
214
215/// Resolve an interned dotted name (a module or type name) to its `.`-joined
216/// form, e.g. `"Licensing.AppInstall"`.
217#[must_use]
218pub fn interned_dotted_name(package: &Package, index: i32) -> Option<String> {
219 let dotted = usize::try_from(index)
220 .ok()
221 .and_then(|i| package.interned_dotted_names.get(i))?;
222 let segments = dotted
223 .segments_interned_str
224 .iter()
225 .map(|&segment| interned_str(package, segment))
226 .collect::<Option<Vec<_>>>()?;
227 Some(segments.join("."))
228}
229
230/// Resolve an interned type by its `i32` index into a package's `interned_types`
231/// table (LF 2.x stores types once and references them by index).
232#[must_use]
233pub fn interned_type(package: &Package, index: i32) -> Option<&crate::pb::daml_lf_2::Type> {
234 usize::try_from(index)
235 .ok()
236 .and_then(|i| package.interned_types.get(i))
237}
238
239/// The package name from its metadata (`PackageMetadata.name_interned_str`).
240#[must_use]
241pub fn package_name(package: &Package) -> Option<&str> {
242 let index = package.metadata.as_ref()?.name_interned_str;
243 interned_str(package, index)
244}
245
246/// The package version from its metadata (`PackageMetadata.version_interned_str`).
247#[must_use]
248pub fn package_version(package: &Package) -> Option<&str> {
249 let index = package.metadata.as_ref()?.version_interned_str;
250 interned_str(package, index)
251}
252
253#[cfg(test)]
254#[allow(clippy::unwrap_used, clippy::expect_used)]
255mod hash_tests {
256 use super::*;
257
258 /// An archive whose declared id is the real SHA-256 of its payload.
259 fn honest_archive() -> Archive {
260 let payload = ArchivePayload {
261 minor: "1".to_string(),
262 sum: Some(archive_payload::Sum::DamlLf2(Package::default())),
263 }
264 .encode_to_vec();
265 let hash = hex(&Sha256::digest(&payload));
266 Archive {
267 hash_function: HashFunction::Sha256 as i32,
268 payload,
269 hash,
270 }
271 }
272
273 #[test]
274 fn an_archive_that_hashes_to_its_id_decodes_and_returns_that_id() {
275 let archive = honest_archive();
276 let expected = archive.hash.clone();
277 let (_package, id) = decode_package(&archive.encode_to_vec()).expect("honest archive");
278 assert_eq!(id, expected);
279 assert_eq!(id.len(), 64, "a SHA-256 in hex");
280 }
281
282 /// The id is the package's identity: generated bindings embed it as
283 /// `PACKAGE_ID` and cross-package references resolve through it. Taking a
284 /// mismatched one on trust means addressing a package by a name its
285 /// contents do not answer to.
286 #[test]
287 fn a_payload_that_does_not_match_its_declared_id_is_refused() {
288 let mut archive = honest_archive();
289 archive.hash = "0".repeat(64);
290 let err = decode_package(&archive.encode_to_vec()).expect_err("must not decode");
291 assert!(
292 matches!(err, DecodeError::PackageIdMismatch { .. }),
293 "{err}"
294 );
295 // Both sides belong in the message: without them a reader cannot tell a
296 // corrupted download from a hand-assembled DAR.
297 let message = err.to_string();
298 assert!(message.contains(&"0".repeat(64)), "{message}");
299
300 // The same when the payload is what changed, which is the realistic
301 // shape of the failure.
302 let mut tampered = honest_archive();
303 tampered.payload.extend_from_slice(b"extra");
304 assert!(matches!(
305 decode_package(&tampered.encode_to_vec()),
306 Err(DecodeError::PackageIdMismatch { .. })
307 ));
308 }
309
310 #[test]
311 fn an_unknown_hash_function_is_refused_rather_than_assumed_to_be_sha256() {
312 let mut archive = honest_archive();
313 archive.hash_function = 7;
314 let err = decode_package(&archive.encode_to_vec()).expect_err("must not decode");
315 assert!(
316 matches!(err, DecodeError::UnsupportedHashFunction(7)),
317 "{err}"
318 );
319 }
320}
321
322#[cfg(test)]
323#[allow(clippy::unwrap_used, clippy::expect_used)]
324mod minor_tests {
325 use super::*;
326
327 /// Build a **well-formed** `Archive` declaring `minor`: the id is the real
328 /// SHA-256 of the payload, so these tests exercise the minor gate rather
329 /// than tripping the hash gate that runs before it.
330 fn archive_with_minor(minor: &str) -> Vec<u8> {
331 let payload = ArchivePayload {
332 minor: minor.to_string(),
333 sum: Some(archive_payload::Sum::DamlLf2(Package::default())),
334 }
335 .encode_to_vec();
336 let hash = hex(&Sha256::digest(&payload));
337 Archive {
338 hash_function: HashFunction::Sha256 as i32,
339 payload,
340 hash,
341 }
342 .encode_to_vec()
343 }
344
345 /// An LF **1.x** archive is the likeliest wrong input there is — every DAR
346 /// built by a Daml 2.x SDK is one — so it has to be told the truth: this
347 /// decoder handles LF 2 only. Diagnosing it by minor instead would print
348 /// "unsupported Daml-LF minor 2.15 … upgrade the SDK", sending the reader
349 /// to rebuild a DAR whose major version will never be right.
350 #[test]
351 fn an_lf1_archive_is_diagnosed_by_its_major_not_its_minor() {
352 let payload = ArchivePayload {
353 // LF 1.15 was the last LF 1 minor, so this is a real DAR's shape.
354 minor: "15".to_string(),
355 sum: Some(archive_payload::Sum::DamlLf1(vec![1, 2, 3])),
356 }
357 .encode_to_vec();
358 let hash = hex(&Sha256::digest(&payload));
359 let bytes = Archive {
360 hash_function: HashFunction::Sha256 as i32,
361 payload,
362 hash,
363 }
364 .encode_to_vec();
365
366 let err = decode_package(&bytes).expect_err("LF 1 is not decodable here");
367 let message = err.to_string();
368 assert!(
369 matches!(err, DecodeError::UnsupportedVersion),
370 "should name the major version: {message}"
371 );
372 assert!(
373 !message.contains("2.15"),
374 "must not report an LF 1 minor as an LF 2 one: {message}"
375 );
376 }
377
378 #[test]
379 fn the_minor_this_build_targets_decodes() {
380 for minor in SUPPORTED_LF2_MINORS {
381 let bytes = archive_with_minor(minor);
382 assert!(
383 decode_package(&bytes).is_ok(),
384 "minor {minor} should decode"
385 );
386 }
387 }
388
389 /// A newer minor must fail loudly. prost silently drops fields from a
390 /// schema it does not know, so decoding one would hand the user bindings
391 /// that compile and are missing template fields — the failure would surface
392 /// on the wire, far from its cause.
393 #[test]
394 fn an_unknown_minor_is_refused_rather_than_silently_decoded() {
395 for minor in ["3", "17", "dev", ""] {
396 let bytes = archive_with_minor(minor);
397 let err = decode_package(&bytes).expect_err("minor {minor} must be refused");
398 let message = err.to_string();
399 assert!(
400 matches!(err, DecodeError::UnsupportedMinor { .. }),
401 "minor {minor}: {message}"
402 );
403 // The message has to name what was found and what is accepted,
404 // or the reader cannot tell whether to rebuild the DAR or the SDK.
405 assert!(message.contains(&format!("2.{minor}")), "{message}");
406 // *Every* accepted version, spelled in full. Asserting only the
407 // first let "(2.1, 2)" — a `2.` prefix that reached one entry of
408 // the list — pass for as long as the list had one entry.
409 for supported in SUPPORTED_LF2_MINORS {
410 assert!(
411 message.contains(&format!("2.{supported}")),
412 "should name 2.{supported} as supported: {message}"
413 );
414 }
415 }
416 }
417}
418
419#[cfg(test)]
420#[allow(clippy::unwrap_used, clippy::expect_used)]
421mod tests {
422 use super::*;
423
424 #[test]
425 fn decodes_a_real_dar_main_package() {
426 let Ok(path) = std::env::var("CANTON_TEST_DAR") else {
427 eprintln!("skipping LF-decode test: set CANTON_TEST_DAR=/path/to/x.dar");
428 return;
429 };
430
431 let dar = Dar::open(&path).expect("open DAR");
432 let (package, package_id) = decode_main_package(&dar).expect("decode LF 2.x package");
433 assert!(
434 !package_id.is_empty(),
435 "package id (archive hash) should be set"
436 );
437
438 assert!(!package.modules.is_empty(), "package should have modules");
439 assert!(
440 !package.interned_strings.is_empty(),
441 "LF 2.x packages intern their strings"
442 );
443 // The SCU inputs — name + version — resolve from the interning table.
444 let name = package_name(&package);
445 let version = package_version(&package);
446 assert!(name.is_some(), "package metadata should carry a name");
447
448 println!(
449 "decoded {} v{} — {} modules, {} interned strings, {} interned types",
450 name.unwrap_or("?"),
451 version.unwrap_or("?"),
452 package.modules.len(),
453 package.interned_strings.len(),
454 package.interned_types.len(),
455 );
456 }
457}