einvoice-validatorDocs

EN 16931 · Peppol BIS Billing 3.0 · XRechnung · Factur-X

einvoice-validator

Validation of European e-invoices against the official published validation artefacts, in pure Rust: no JVM, no C library, no FFI. A library and a command-line tool that run the official stylesheets unchanged, with exact decimal arithmetic, and give the same report as Saxon-HE, rule by rule.

What it is

The business rules of EN 16931 and of the specifications built on it (Peppol BIS Billing 3.0, XRechnung, Factur-X, the French e-invoicing rules) are published as Schematron, which validators run compiled to XSLT 2.0 stylesheets. einvoice-validator is an XSLT 2.0 and XPath 2.0 engine, written in Rust, that runs those stylesheets as they are published, with XML Schema validation in front of them, behind a library and a command-line tool. It reads both syntaxes of EN 16931: UBL 2.1 and UN/CEFACT CII D16B, as XML files or embedded in a Factur-X, ZUGFeRD or Order-X PDF file.

Use it

Install the command-line tool from crates.io, with Rust 1.99 or later (rustup):

cargo install --locked einvoice-cli                  # installs einvoice-validate

or from a clone of the repository, where the toolchain (Rust 1.99.1) is pinned in rust-toolchain.toml and installed by rustup on first use (Build and install from source):

git clone https://github.com/einvoice-validator/einvoice-validator.git
cd einvoice-validator
cargo install --locked --path crates/einvoice-cli    # installs einvoice-validate

Two rule sets are built in: cen-ubl, CEN EN 16931 UBL 1.3.17 with the UBL 2.1 schemas, and cen-cii, CEN EN 16931 CII 1.3.17 with the UN/CEFACT CII D16B schemas. Without --rules or --bundle, einvoice-validate picks the rule set of each document from its root element: cen-ubl for a UBL Invoice or CreditNote, cen-cii for a CII CrossIndustryInvoice, cen-ubl for anything else. The other rule sets are fetched on demand (below).

einvoice-validate invoice.xml                        # cen-ubl or cen-cii, from the root element of the document
einvoice-validate factur-x.pdf                       # a Factur-X / ZUGFeRD / Order-X PDF: the invoice XML it embeds
einvoice-validate --rules cen-cii invoice.xml        # a built-in rule set by name: cen-ubl or cen-cii
einvoice-validate --rules xrechnung invoice.xml      # a rule set fetched on demand (rules fetch xrechnung first)
einvoice-validate --format json --jobs 4 invoices/*.xml > report.json
einvoice-validate --format svrl - < invoice.xml      # the SVRL report, as the stylesheet wrote it
einvoice-validate --bundle DIR invoice.xml           # a rule-set bundle: DIR/bundle.toml and its stylesheets
einvoice-validate --fail-closed invoice.xml          # a finding of no known severity is fatal
einvoice-validate --max-depth 1000 deep.xml          # accept elements nested up to 1000 deep (default 256)
einvoice-validate --licences                         # the licences of everything the binary embeds, in full

A UBL invoice, a CII invoice and the same CII invoice with its sum of line net amounts one cent too high, in one run:

$ einvoice-validate ubl-invoice.xml cii-invoice.xml cii-broken.xml
ubl-invoice.xml: valid
cii-invoice.xml: valid
cii-broken.xml: invalid: 2 fatal
  fatal    BR-CO-10: [BR-CO-10]-Sum of Invoice line net amount (BT-106) = Σ Invoice line net amount (BT-131).
           at /*:CrossIndustryInvoice[namespace-uri()='urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100'][1]/*:SupplyChainTradeTransaction[namespace-uri()='urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100'][1]/*:ApplicableHeaderTradeSettlement[namespace-uri()='urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100'][1]/*:SpecifiedTradeSettlementHeaderMonetarySummation[namespace-uri()='urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100'][1]
  fatal    BR-CO-13: [BR-CO-13]-Invoice total amount without VAT (BT-109) = Σ Invoice line net amount (BT-131) - Sum of allowances on document level (BT-107) + Sum of charges on document level (BT-108).
           at /*:CrossIndustryInvoice[namespace-uri()='urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100'][1]/...
3 documents: 2 valid, 1 invalid, 0 not validated

In the JSON report, each document names the rule set it was validated with (documents[].rule_set). A UBL document with schema errors:

$ einvoice-validate invoice.xml broken.xml
invoice.xml: valid
broken.xml: invalid: 1 schema error, 11 fatal
  schema   2:1: missing-element: element ubl:Invoice: content incomplete; expected: ext:UBLExtensions, cbc:UBLVersionID, cbc:CustomizationID, cbc:ProfileID, cbc:ProfileExecutionID, cbc:ID
  ...
  fatal    BR-02: [BR-02]-An Invoice shall have an Invoice number (BT-1).
           at /*:Invoice[namespace-uri()='urn:oasis:names:specification:ubl:schema:xsd:Invoice-2'][1]
  ...
2 documents: 1 valid, 1 invalid, 0 not validated

Exit status, the highest that applies: 0 every document is valid (no schema error, no fatal finding); 1 a document is invalid (schema errors, fatal findings, not well-formed XML, or, for XRechnung, no matching scenario); 2 usage error, or a file or bundle that cannot be read or is not valid (a PDF file without one embedded invoice included); 3 a construct the engine does not support (an encrypted PDF file included), a document beyond a limit, a stylesheet error on a document, or an internal error. Output as text (for people), json (a versioned format, for scripts) or svrl; with --jobs N, N threads share one loaded rule set and the output keeps the order of the command line. Options and the JSON format: crates/einvoice-cli/README.md.

PDF files

A file or standard input that starts with %PDF- is read as a Factur-X, ZUGFeRD or Order-X PDF/A-3 file, by the crate einvoice-pdf, in pure Rust: the embedded invoice XML is extracted byte for byte and validated with the rule set of its root element (or the one named), and the output adds what the PDF states about it: the embedded file, its /AFRelationship, the PDF/A identification and the Factur-X / ZUGFeRD properties of its XMP metadata. The reader takes only the part of PDF on the path to embedded files and bounds every resource against hostile input; an encrypted file or a PDF feature outside that part is refused (exit status 3). In the library: the feature pdf, on by default, and pdf::extract.

Deeply nested documents

A document with an element nested deeper than 256 levels (the document element is at depth 1; libxml2's default limit) is refused before it is validated, with the line and column of that element: an error of kind unsupported and exit status 3 in einvoice-validate, Error::Limit in the library. --max-depth N (at most 100000) and ValidateOptions::max_depth set another maximum. The other limits are listed under Security.

$ einvoice-validate deep.xml
deep.xml: error (unsupported): limit exceeded: document, 2:838: element nested deeper than the maximum depth of 256

Rule sets fetched on demand

Peppol BIS Billing 3.0, XRechnung, Factur-X and the French e-invoicing rules may not be redistributed, so they are not part of the crates. einvoice-validate downloads them from their publishers only when asked (rules fetch NAME, a family, an alias or --all; or --fetch in a validation run), at pinned URLs, checks every file against its pinned digest, assembles their bundles in a local cache (EINVOICE_VALIDATOR_CACHE, by default the platform cache directory) and then works offline. rules list shows the rule sets, their sources and what is cached.

einvoice-validate rules fetch xrechnung              # once, from KoSIT's package registry
einvoice-validate --rules xrechnung invoice.xml      # xrechnung-ubl or xrechnung-cii, from the document's syntax
einvoice-validate rules fetch peppol                 # the Peppol Schematron, compiled here, in Rust
einvoice-validate --rules peppol invoice.xml
einvoice-validate --rules factur-x-en16931 --fetch invoice.pdf   # fetch in this run if missing
einvoice-validate rules list                         # every rule set, its source, cached or not
einvoice-validate rules path factur-x-en16931        # the bundle directory, for --bundle

Library

A Validator is built once from a rule set (schemas loaded, stylesheets prepared), is Send + Sync, and validates any number of documents. Add it from crates.io (API documentation on docs.rs):

[dependencies]
einvoice-validator = "0.4"
use einvoice_validator::{Validator, Verdict};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Built once: the UBL 2.1 schemas loaded, the CEN stylesheet prepared.
    // A Validator is Send + Sync: share it between threads.
    let validator = Validator::cen_ubl()?;
    let report = validator.validate(&std::fs::read("invoice.xml")?)?;
    for error in &report.schema_errors {
        println!("schema {}:{}: {}", error.line, error.column, error.message);
    }
    for finding in report.findings() {
        let id = finding.id.as_deref().unwrap_or("-");
        println!("{:?} {id}: {} (at {})", finding.severity, finding.text, finding.location);
    }
    println!("{}", if report.verdict() == Verdict::Valid { "valid" } else { "invalid" });
    Ok(())
}

Validator::cen_cii() is the CII rule set, and Syntax::detect tells from a document's root element which of the two built-in rule sets is its own:

use einvoice_validator::{Syntax, Validator, Verdict};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let document = std::fs::read("invoice.xml")?;
    // From the root element: cen-ubl for a UBL Invoice or CreditNote,
    // cen-cii for a CII CrossIndustryInvoice.
    let rule_set = Syntax::detect(&document).map_or("cen-ubl", Syntax::builtin_rule_set);
    let validator = Validator::builtin(rule_set)?;
    let report = validator.validate(&document)?;
    let verdict = if report.verdict() == Verdict::Valid { "valid" } else { "invalid" };
    println!("{rule_set}: {verdict}");
    Ok(())
}

Validator::from_bundle_dir loads a bundle directory, and with the feature fetch, Validator::from_cache a rule set fetched on demand (RuleSetCache, fetched_rule_sets). A Validator is Clone, sharing the loaded rule set. The Report also gives the raw and canonical SVRL, the number of fired rules of each stylesheet, the scenario a document matched and the rule-set version; validate_owned takes the document as an owned buffer and avoids a copy of its text.

Why run the official stylesheets

The validation artefacts are the reference definition of the rules. Running them unchanged means a new release of the rules is new data to vendor and test, not code to rewrite, and a result can always be traced back to the published rule that produced it.

How it works

Validation pipeline An invoice in UBL 2.1 or CII D16B XML, from a file or a PDF, is checked as XML and against the XML Schema of its syntax; then the official XSLT stylesheets of the rule set are executed by the Rust engine, which writes an SVRL report. Invoice UBL 2.1 or CII D16B, XML <xsd> Schema check UBL 2.1 or CII D16B XML Schema, in Rust <xsl> Official XSLT executed unchanged by the Rust engine SVRL report fired rules, failed asserts, reports Validation pipeline An invoice in UBL 2.1 or CII D16B XML, from a file or a PDF, is checked as XML and against the XML Schema of its syntax; then the official XSLT stylesheets of the rule set are executed by the Rust engine, which writes an SVRL report. Invoice UBL 2.1 or CII D16B, XML <xsd> Schema check UBL 2.1 or CII D16B XML Schema, in Rust <xsl> Official XSLT executed unchanged by the Rust engine SVRL report fired rules, failed asserts, reports
The pipeline, behind the library einvoice-validator and the command-line tool einvoice-validate: the document (or the invoice XML a PDF file embeds) is checked as XML, then against the XML schema of the rule set, UBL 2.1 or UN/CEFACT CII D16B, then each stylesheet of the rule set runs on it (for XRechnung, those of the scenario the document matches). The rule set is chosen from the root element unless one is named: CEN UBL for a UBL invoice or credit note, CEN CII for a CII invoice. SVRL (Schematron Validation Report Language) is the report format the official stylesheets write.
StageWhatStatus
ReadA streaming XML 1.0 parser with namespaces that builds no tree, checked against roxmltree and Saxon-HE: the XML check and the schema validation in one pass, then the stylesheets' input tree (einvoice-xml, #18); the invoice XML of a Factur-X, ZUGFeRD or Order-X PDF file (einvoice-pdf)done
Schema checkXML Schema validation in Rust against the official OASIS UBL 2.1 and UN/CEFACT CII D16B schemas, which are embedded, limited to the XSD features they use; compared with xmllint (einvoice-xsd, #6, #32)done
LoadThe stylesheet is parsed, its XPath expressions and patterns with it; constructs outside the subset are refused, and so are expressions and instructions nested beyond a limit (einvoice-xslt, einvoice-xpath)done
ValuesXPath 2.0 atomic values: exact decimals, big integers (einvoice-bigint, safe Rust, no assembly), doubles, dates, casts, comparisons, regular expressions, as Saxon-HE 12.10 behaves (einvoice-xdm)done
EvaluateXPath 2.0 evaluator over the invoice, with the static types Saxon-HE infers for variables and function results (#21); unknown functions and variables are refused when an expression is compiled; the current date and time come from a clock the caller can give (einvoice-xpath-eval, #1)done
Execute and reportXSLT executor: template rules, modes, priorities, imports, xsl:next-match, functions, parameters, the stylesheets of the ISO Schematron skeleton and of SchXslt; SVRL output, kept compactly and read as it is written. The stylesheet is prepared once and run on any number of documents; template and function invocations are bounded in nesting and in stack (einvoice-xslt-exec, #2, #29)done
SchematronSchematron compiled to XSLT as ph-schematron 10.3.1 compiles it, byte for byte, by running the ISO Schematron skeleton on the engine: how the Peppol rule set is built without Java (einvoice-schematron)done
Library and toolRule-set bundles (a bundle.toml manifest with the SHA-256 of each stylesheet and of each file it reads, severities, KoSIT scenarios), the built-in rule sets cen-ubl and cen-cii, rule sets fetched on demand, the Validator and its Report, Syntax detection from the root element (einvoice-validator); the einvoice-validate command-line tool with text, JSON and SVRL output, the rule set picked per document, and documented exit codes (einvoice-cli, #10, #35)done
WebAssembly and npmThe library on wasm32-unknown-unknown, the date and time given by the caller. The npm package einvoice-validator (JavaScript and TypeScript bindings for Node.js 22, browsers and bundlers, with cen-ubl and cen-cii) is built and tested: the Saxon-HE findings on every case of the CEN UBL and CII corpora under Node.js and in headless Chrome and Firefox. Build it from the repository with crates/einvoice-wasm/npm.sh; it is not published on npm.built, not published
Release0.4.0: the thirteen published crates of the workspace on crates.io, each with its licence texts, and a signed tag with its GitHub release; earlier releases 0.3.0, 0.2.0 and 0.1.0done

Rule sets

Two rule sets are built in. The others may not be redistributed: einvoice-validate rules fetch NAME downloads them from their publishers, at pinned URLs, checks every file against its pinned digest and assembles (for Peppol, compiles) their bundles on your machine. For each, a test corpus of official documents and mutation cases of our own carries the report Saxon-HE 12.10 gives with each stylesheet; the corpora of the fetched rule sets are built locally, like the rule sets.

Rule setReleaseHow to get itChecked against Saxon-HE
CEN EN 16931, UBL syntax1.3.17built in cen-ubl: the compiled XSLT published by CEN, vendored unmodified, after the UBL 2.1 schema1179 cases (examples, test files, VEFA unit tests) and 508 mutation cases: every report identical (#3)
CEN EN 16931, UN/CEFACT CII D16B syntax1.3.17built in cen-cii: the compiled XSLT published by CEN, vendored unmodified, after the UN/CEFACT CII D16B schema (#32)24 cases and 808 mutation cases: every report identical (#12)
Peppol BIS Billing 3.0, UBL syntax3.0.22fetched rules fetch peppol: the Schematron of the pinned release, compiled in pure Rust, without Java, as ph-schematron 10.3.1 compiles it, both stylesheets (the Peppol rules and the CEN rules the release embeds) byte for byte, their SHA-256 pinned707 cases and 509 mutation cases, with each of the two stylesheets: every report identical (#5)
Factur-X / ZUGFeRD, CII syntax, five profilesFactur-X 1.09.2 (ZUGFeRD 2.5.2)fetched rules fetch factur-x: the stylesheets and code lists of the five profiles as the Mustang validator 2.26.0 ships them (Maven Central); a failed assert without a flag is fatal, as Mustang reads it. On main: the XML schema of the profile first, as Mustang runs it42 cases and 808 mutation cases, with each of the five stylesheets: every report identical (#26)
XRechnung, UBL and CII syntaxes3.0.2fetched rules fetch xrechnung: the KoSIT validator configuration (the CEN and XRechnung rules), run as the KoSIT validator runs it: its scenarios, their levels and their XML schema1196 UBL and 686 CII cases (the test suite and the expanded unit tests of the XRechnung Schematron) and 508 + 808 mutation cases, with both stylesheets of each syntax: every report identical (#27)
French e-invoicing rules (XP Z12-012): CII, UBL, EXTENDED-CTC-FR, Factur-X, life-cycle statuses (CDAR), e-reportingFNFE-MPE package 1.4.0.04fetched rules fetch fr-ctc: fourteen bundles from the package published by FNFE-MPE; UBL 2.1 first for UBL. On main: UN/CEFACT CII D22B, CDAR D22B or the Factur-X schema first, as the package documents it53 CII, 75 UBL and 70 CDAR cases and 808 + 508 mutation cases, with each stylesheet that runs on them: every report identical (e-reporting has no test corpus) (#28)
UBL 2.1 XML Schema (Invoice, CreditNote)2.1built in the OASIS schemas, vendored unmodified and embedded (the two ETSI XAdES schemas excepted: signature content is validated laxly)Compared with xmllint (libxml2): every corpus document agrees; every other difference is listed with its cause (#6)
UN/CEFACT CII D16B XML Schema (CrossIndustryInvoice)D16Bbuilt in UNECE's files, uncoupled code lists, vendored unmodified and embeddedCompared with xmllint on the CEN CII corpus: every case agrees, the 4 mutation cases that differ are listed with their cause; the same on the CII corpora of XRechnung, Factur-X and the French rules (#32)

On every document of these corpora, each rule set reads the Saxon-HE reports as its reference validator does; the XML schema step of the Factur-X and French bundles included, since 0.4.0 (#37). Need another official rule set? Open an issue.

Performance

einvoice-validate against Saxon-HE 12.10 running the same official stylesheets on the same documents: the whole corpus of each rule set (every document, mutation cases included), one process per job, process start and rule-set load included. There are 23 jobs, one per rule set exactly as einvoice-validate --rules NAME runs it (#41): the rule set read from the cache rules fetch fills, the XML schema step, the XRechnung scenarios, the stylesheets and the verdicts, which must be the reference verdicts on every document and every run. Median of 5 runs, measured with cargo xtask bench at commit f07b7a8 (in 0.4.0), on a 20-core desktop machine (load average 1.3 before the run, 6.5 after, the run's own processes included); the full tables, the method and every run are in docs/benchmarks.md.

Rule setDocuments1 thread: einvoice-validateSaxon-HESpeed-upSpeed-up, JVM start excluded8 threads: einvoice-validateSaxon-HESpeed-upPeak memory, 1 thread (ratio)
CEN EN 16931 UBL 1.3.1716871.32 s2.29 s1.7×1.6×0.225 s1.12 s5.0×34.7 MiB / 853 MiB (25×)
CEN EN 16931 CII 1.3.178320.579 s1.66 s2.9×2.6×0.106 s0.971 s9.2×22.6 MiB / 855 MiB (38×)
Peppol BIS Billing 3.0.22 (UBL)12161.44 s3.55 s2.5×2.2×0.251 s1.95 s7.8×35.6 MiB / 888 MiB (25×)
Factur-X 1.09.2 MINIMUM8500.301 s1.69 s5.6×5.1×0.049 s1.02 s21×8.65 MiB / 807 MiB (93×)
Factur-X 1.09.2 BASIC WL8501.17 s3.60 s3.1×2.9×0.178 s1.46 s8.2×15.7 MiB / 903 MiB (58×)
Factur-X 1.09.2 BASIC8501.67 s4.91 s2.9×2.9×0.247 s1.76 s7.1×20.2 MiB / 1110 MiB (55×)
Factur-X 1.09.2 EN169318501.74 s5.31 s3.1×3.0×0.265 s1.79 s6.7×23.2 MiB / 898 MiB (39×)
Factur-X 1.09.2 EXTENDED8502.24 s6.82 s3.0×3.0×0.361 s2.16 s6.0×44.9 MiB / 1033 MiB (23×)
XRechnung 3.0.2 UBL17042.75 s5.79 s2.1×1.3×0.415 s2.50 s6.0×36.7 MiB / 874 MiB (24×)
XRechnung 3.0.2 CII14942.36 s4.90 s2.1×1.6×0.351 s2.35 s6.7×25.2 MiB / 869 MiB (34×)
French rules 1.4.0.04, EN 16931 CII8611.90 s4.92 s2.6×2.4×0.293 s2.31 s7.9×23.2 MiB / 1083 MiB (47×)
French rules 1.4.0.04, EN 16931 CII (WARNING version)8611.91 s4.83 s2.5×2.3×0.291 s2.35 s8.1×23.1 MiB / 1071 MiB (46×)
French rules 1.4.0.04, EXTENDED-CTC-FR CII8611.97 s4.95 s2.5×2.3×0.305 s2.40 s7.9×26.4 MiB / 1074 MiB (41×)
French rules 1.4.0.04, EXTENDED-CTC-FR CII (WARNING version)8611.99 s5.00 s2.5×2.3×0.304 s2.38 s7.8×25.9 MiB / 1094 MiB (42×)
French rules 1.4.0.04, Factur-X BASIC WL8612.50 s6.82 s2.7×2.6×0.357 s2.68 s7.5×20.0 MiB / 1078 MiB (54×)
French rules 1.4.0.04, Factur-X EN169318613.11 s8.84 s2.8×2.7×0.466 s3.44 s7.4×24.4 MiB / 1082 MiB (44×)
French rules 1.4.0.04, Factur-X EXTENDED8613.41 s9.75 s2.9×2.7×0.518 s3.30 s6.4×43.7 MiB / 1093 MiB (25×)
French rules 1.4.0.04, EN 16931 UBL5832.73 s5.55 s2.0×1.9×0.434 s2.55 s5.9×35.1 MiB / 1008 MiB (29×)
French rules 1.4.0.04, EN 16931 UBL (WARNING version)5832.73 s5.57 s2.0×1.9×0.433 s2.61 s6.0×35.5 MiB / 1003 MiB (28×)
French rules 1.4.0.04, EXTENDED-CTC-FR UBL5832.69 s5.69 s2.1×2.0×0.433 s2.55 s5.9×36.6 MiB / 1098 MiB (30×)
French rules 1.4.0.04, EXTENDED-CTC-FR UBL (WARNING version)5832.66 s5.58 s2.1×1.9×0.434 s2.59 s6.0×36.7 MiB / 1087 MiB (30×)
French rules 1.4.0.04, life-cycle statuses (CDAR)700.036 s0.599 s17×13×0.012 s0.577 s46×11.3 MiB / 312 MiB (28×)
French rules 1.4.0.04, life-cycle statuses (CDAR, WARNING version)700.036 s0.621 s17×13×0.013 s0.568 s43×11.2 MiB / 313 MiB (28×)
All 23 jobs1968243.2 s109 s2.5×2.3×6.74 s47.4 s7.0×23× to 93× lower

Security

Documents, PDF files and rule-set bundles may come from anyone; each is bounded so that a hostile one ends with an error, not a crash or an unbounded allocation.

Report a vulnerability through the repository's security policy.

Pure Rust

Quality

Licences