From 95f239d20dfb58a28fbc8b3309e9df8cde86c16c Mon Sep 17 00:00:00 2001 From: Mike Lodder Date: Wed, 14 Oct 2026 15:45:04 -0600 Subject: [PATCH] feat: no default just traits Signed-off-by: Mike Lodder --- CHANGELOG.md | 49 ++++++++ Cargo.toml | 126 +++++++++++++------ README.md | 133 +++++++++++++------- SECURITY.md | 8 +- src/attrid.rs | 46 ++++++- src/lib.rs | 122 ++++++------------ src/ms.rs | 238 +++++++++++------------------------- src/serde/de.rs | 51 +++----- src/serde/mod.rs | 60 ++++++--- src/serde/ser.rs | 2 +- src/views.rs | 50 ++------ src/views/bls12381.rs | 46 +++++-- src/views/builder.rs | 19 +-- src/views/dispatch.rs | 16 ++- src/views/lamport.rs | 3 +- src/views/lamport_merkle.rs | 3 +- src/views/threshold_meta.rs | 125 ++++++++++++++++--- tests/security_tests.rs | 3 +- 18 files changed, 631 insertions(+), 469 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e18ff21..de27228 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,55 @@ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [2.0.0] - 2026-10-14 + +### Added + +- The `bls12-381` feature. It gates the `views::bls12381` module, the BLS12-381 view dispatch, the BLS ssh signature conversions in `Builder::new_from_ssh_signature`, and the `Builder::new_from_bls_*` constructors, and it pulls in `blsful`. +- The `chacha20` feature. It gates `encrypt_threshold_meta`, `decrypt_threshold_meta`, and `generate_meta_key`, and pulls in `chacha20poly1305`, `getrandom`, and `zeroize`. +- With `default-features = false` the crate depends on no signature or AEAD crate. It provides the `Multisig` type, its attributes, the view traits, `ViewBuilder`, the threshold metadata types, and the data-only views (Ed25519, secp256k1, NIST P, RSA, SLH-DSA, ML-DSA, FN-DSA, MAYO, and the hybrids). +- Tests for the partial-disclosure round trip and for the disclosure modes without `chacha20`. +- `FromStr` for `AttrId` and `SchemeTypeId`. The existing `TryFrom<&str>` impls now delegate to it, so `"sig-data".parse::()` works and the old calls are unchanged. This clears the `clippy::try_from_instead_of_from_str` errors that failed `cargo clippy -- -D warnings`. +- `impl From<&Multisig> for Vec` encodes without cloning. The owned `From` delegates to it, and binary serde serialization uses it instead of cloning the multisig. + +### Changed + +- **Breaking:** the default feature set is now `bls12-381`, `chacha20`, `lamport`, `serde`, and `xmss`. A build with `default-features = false` loses the BLS constructors, BLS views, and the threshold metadata encryption functions; add the features you use. +- **Breaking:** without `bls12-381`, the BLS12-381 combined and share codecs leave `SIG_CODECS` and `SIG_SHARE_CODECS`, so the arrays shrink by two entries each. This matches how the `lamport` and `xmss` codecs already behave. +- Without `chacha20`, `stamp_disclosure_attrs` and `read_threshold_params` return `SharesError::MetaEncryption` for the partial and fully confidential disclosure modes. The confidential threshold is never written in plaintext. +- The `xmss` feature no longer pulls in a crate. The XMSS views carry signature bytes only. +- Removed redundant copies on the encode and decode paths: message and attribute bytes are written straight into the output instead of being cloned into a `Varbytes` first, decoded attributes are moved instead of cloned, the `Builder` setters no longer copy each attribute twice, and binary serde deserialization decodes from the input bytes directly. In paired benchmarks against 1.6.0 on an idle machine, `multisig_to_bytes` is about 26% faster, `Builder` construction about 20% faster, and a full roundtrip 29–38% faster; decoding is unchanged within noise. +- Re-enabled `clippy::redundant_clone`. +- Fixed four redundant intra-doc link targets so `cargo doc` builds with `RUSTDOCFLAGS="-D warnings"`. +- Moved the crate-level lint settings from `lib.rs` into the `[lints]` table in `Cargo.toml`, so they now apply to tests and benches as well as the library. Fixed the one trivial cast in `tests/security_tests.rs` that this exposed. +- **Breaking:** renamed `ThresholdDisclosure::FullConfidentialial` to `ThresholdDisclosure::FullConfidential`, fixing the typo. The encoded value (2) is unchanged, so existing shares decode as before; `as_str()` and `Display` now return `full-confidential`. +- `ThresholdMetadata` and `ThresholdMetaCipher` CBOR encoding uses `serde_cbor_2` instead of `ciborium`. The bytes are identical: blobs written by 1.6.0 decode unchanged, and 1.6.0 decodes blobs written by 2.0.0. + +### Removed + +- **Breaking:** `Builder::new_from_bls_signature` and `Builder::new_from_bls_signature_share`, deprecated since 1.0.7. They inferred G1 or G2 from the byte length. Use `new_from_bls_signature_with_codec` and `new_from_bls_signature_share_with_codec`, which take the codec as their first argument. +- **Breaking:** the `Views` trait and `impl Views for Multisig`, deprecated since 1.5.0. Use `ViewBuilder` instead: `ms.attr_view()` becomes `ViewBuilder::new(&ms).attr().build()`, and likewise for `data`, `conv`, `threshold_attr`, `threshold`, and `disclosure`. + +### Fixed + +- Enabling `lamport` without `xmss` failed to compile, because `SIG_CODECS` had a fixed length of 60 while three entries were gated on `xmss`. The array lengths are now derived from the enabled features. + +### Dependencies + +- `blsful`, `chacha20poly1305`, `getrandom`, and `zeroize` are now optional. +- Removed the unused `elliptic-curve` and `xmss` dependencies. +- `ssh-key` now enables only `alloc`. The `ecdsa` and `ed25519` features were never used by this crate. +- Replaced `ciborium` with `serde_cbor_2`. +- Sorted the keys in every `Cargo.toml` section and dropped a stale comment about a local `multi-codec` build. + +### Documentation + +- README codec tables now use the real `Codec` variant names (`MlDsa65Msig`, `SlhDsaSha2128FMsig`, …) and multicodec names (`ml-dsa-65-msig`, `slh-dsa-sha2-128f-msig`, …). The old tables had both wrong. +- README now covers the 25 Lamport, Merkle-Lamport, and XMSS codecs, the 11 Merkle-Lamport share codecs, the `sig-index` and `depth` attributes, and Lamport and Merkle-Lamport threshold support. It previously described threshold signatures as BLS-only and counted 35 codecs; the default build has 60 signature and 13 share codecs. +- README lists the `_with_codec` BLS constructors, adds an "Upgrading from 1.x" section, and fixes the CI badge and multi-key links. +- The crate-level docs list every supported signature family instead of only Ed25519, secp256k1, and BLS12-381, and the examples build with `Codec::EddsaMsig` instead of the key codec `Codec::Ed25519Pub`. +- SECURITY.md reflects `blsful` 4.1.0 and the `[lints.rust]` `unsafe_code = "deny"` setting. + ## [1.6.0] - 2026-10-08 ### Changed diff --git a/Cargo.toml b/Cargo.toml index ded3e98..1d6e971 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,60 +1,61 @@ [package] -name = "multi-sig" -version = "1.6.0" -edition = "2024" -rust-version = "1.99" authors = ["Dave Grantham "] +categories = ["cryptography", "encoding"] description = "Multisig self-describing multicodec implementation for digital signatures" -repository = "https://github.com/cryptidtech/multi-sig.git" -readme = "README.md" -license = "Apache-2.0" +edition = "2024" keywords = ["multiformats", "multisig", "signatures", "crypto"] -categories = ["cryptography", "encoding"] +license = "Apache-2.0" +name = "multi-sig" +readme = "README.md" +repository = "https://github.com/cryptidtech/multi-sig.git" +rust-version = "1.99" +version = "2.0.0" [features] -default = ["serde", "lamport", "xmss"] +# BLS12-381 signatures, signature shares, and share combining +bls12-381 = ["dep:blsful"] +# ChaCha20-Poly1305 encryption of threshold metadata (partial and fully +# confidential disclosure modes) +chacha20 = ["dep:chacha20poly1305", "dep:getrandom", "dep:zeroize"] +default = ["bls12-381", "chacha20", "lamport", "serde", "xmss"] +# Lamport and Merkle-Lamport signature views +lamport = ["dep:blake2", "dep:blake3", "dep:lamport_signature_plus", "dep:sha2", "dep:sha3", "dep:shake"] # `serde` is now a required dependency because the core `threshold_meta` # module (always compiled) derives `Serialize`/`Deserialize` for its CBOR # blob types. The feature flag is retained for backward compatibility and # controls only the public `serde` impl module. serde = [] -lamport = ["dep:lamport_signature_plus", "dep:sha3", "dep:sha2", "dep:blake2", "dep:shake", "dep:blake3"] -xmss = ["dep:xmss"] +# XMSS signature views; they carry signature bytes only, so no XMSS crate is needed +xmss = [] -# Local multi-codec 1.4.0 until it is published (remove at release). [dependencies] -ciborium = "0.2" -chacha20poly1305 = "0.11" -elliptic-curve = "0.14" -getrandom = { version = "0.4" } # blsful configured per-target below (blst for native, rust for wasm) +blake2 = { version = "0.11.0", optional = true } +blake3 = { version = "1.8", optional = true } +chacha20poly1305 = { version = "0.11", optional = true } +getrandom = { version = "0.4", optional = true } +lamport_signature_plus = { version = "0.5.0", optional = true } multi-base = { version = "1.1", default-features = false } multi-codec = "1.6" multi-trait = { version = "1.1", default-features = false } multi-util = "1.2" serde = { version = "1.0", default-features = false, features = ["alloc", "derive"] } +serde_cbor_2 = "0.13.0" +sha2 = { version = "0.11", optional = true } +sha3 = { version = "0.12", optional = true } +shake = { version = "0.1", optional = true } ssh-encoding = "0.3" +ssh-key = { version = "0.7.0-rc.11", default-features = false, features = ["alloc"] } thiserror = { version = "2.0" } unsigned-varint = { version = "0.8", features = ["std"] } -zeroize = "1" -# Lamport support (feature-gated, default-enabled) -lamport_signature_plus = { version = "0.5.0", optional = true } -sha3 = { version = "0.12", optional = true } -sha2 = { version = "0.11", optional = true } -blake2 = { version = "0.11.0", optional = true } -shake = { version = "0.1", optional = true } -blake3 = { version = "1.8", optional = true } -# XMSS support (feature-gated, default-enabled) -xmss = { version = "0.1.0-pre.0", optional = true } +zeroize = { version = "1", optional = true } [target.'cfg(target_arch = "wasm32")'.dependencies] -blsful = { version = "4.1.0", default-features = false, features = ["rust"] } -getrandom = { version = "0.4", features = ["wasm_js"] } -ssh-key = { version = "0.7.0-rc.11", default-features = false, features = ["alloc", "ecdsa", "ed25519"] } +blsful = { version = "4.1.0", default-features = false, features = ["rust"], optional = true } +getrandom = { version = "0.4", features = ["wasm_js"], optional = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -blsful = { version = "4.1.0", default-features = false, features = ["blst"] } -ssh-key = { version = "0.7.0-rc.11", default-features = false, features = ["alloc", "ecdsa", "ed25519"] } +blsful = { version = "4.1.0", default-features = false, features = ["blst"], optional = true } [dev-dependencies] criterion = { version = "0.8", features = ["html_reports"] } @@ -65,15 +66,72 @@ serde_json = "1.0" serde_test = "1.0" [[bench]] -name = "multisig_bench" harness = false +name = "multisig_bench" path = "benches/multisig_bench.rs" +# Pedantic, nursery, and cargo lints are on. The allows suppress stylistic +# lints that would require large-scale churn for minimal security benefit. +# Each is reviewed individually. [lints.clippy] -pedantic = { level = "warn", priority = -1 } -nursery = { level = "warn", priority = -1 } +# false positives in complex match arms +branches_sharing_code = "allow" cargo = { level = "warn", priority = -1 } +# intentional in codec conversions +cast_possible_truncation = "allow" +# wrapping common terms in backticks is stylistic +doc_markdown = "allow" +# explicit lifetimes aid readability +elidable_lifetime_names = "allow" +# glob imports of enums are used judiciously +enum_glob_use = "allow" +# into_iter() is idiomatic +explicit_iter_loop = "allow" +# stylistic +if_not_else = "allow" +# module-level items are ordered logically +items_after_statements = "allow" +# many functions can't be const due to trait bounds +missing_const_for_fn = "allow" +# public APIs are documented; this is noisy on impl blocks and trait impls +missing_errors_doc = "allow" +# we avoid panics; where they exist they are documented +missing_panics_doc = "allow" +# blsful pulls in duplicate versions (tracked) multiple_crate_versions = { level = "allow", priority = 1 } +# too noisy on every function returning Result +must_use_candidate = "allow" +# false positives in test code +needless_for_each = "allow" +nursery = { level = "warn", priority = -1 } +# sometimes less readable than if-let +option_if_let_else = "allow" +# false positives for cheap constructors like BTreeMap::new +or_fun_call = "allow" +pedantic = { level = "warn", priority = -1 } +# needed for crate-internal module visibility +redundant_pub_crate = "allow" +# builder pattern returns self by design +return_self_not_must_use = "allow" +# stylistic preference +semicolon_if_nothing_returned = "allow" +# single-arm match with else is clearer in context +single_match_else = "allow" +# crate-level doc paragraph length +too_long_first_doc_paragraph = "allow" +# large match arms are inherent to this crate +too_many_lines = "allow" +# stylistic; format strings are clear as-is +uninlined_format_args = "allow" +# false positive +unnecessary_semicolon = "allow" +# causes churn in match arms on large enums +use_self = "allow" [lints.rust] +missing_docs = "warn" +trivial_casts = "deny" +trivial_numeric_casts = "deny" unsafe_code = "deny" +unused_import_braces = "deny" +unused_qualifications = "deny" diff --git a/README.md b/README.md index d4a92d3..600f824 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,28 @@ [![](https://img.shields.io/badge/made%20by-Cryptid%20Technologies-gold.svg?style=flat-square)][CRYPTID] [![](https://img.shields.io/badge/project-provenance-purple.svg?style=flat-square)][PROVENANCE] [![](https://img.shields.io/badge/project-multiformats-blue.svg?style=flat-square)][MULTIFORMATS] -![](https://github.com/cryptidtech/multisig/actions/workflows/rust.yml/badge.svg) +![](https://github.com/cryptidtech/multi-sig/actions/workflows/rust.yml/badge.svg) # Multisig -A Rust implementation of the [multiformats][MULTIFORMATS] [multisig specification][MULTISIG]. The published crate is **`multi-sig`**. Depend on it as `multi-sig = "1.0"` in `Cargo.toml`. Import it as `multi_sig` in Rust, for example `use multi_sig::Builder;`. +A Rust implementation of the [multiformats][MULTIFORMATS] [multisig specification][MULTISIG]. The published crate is **`multi-sig`**. Depend on it as `multi-sig = "2.0"` in `Cargo.toml`. Import it as `multi_sig` in Rust, for example `use multi_sig::Builder;`. ## Current Status -This crate gives self-describing digital signature containers (`Multisig`) for 35 signature codecs. The codecs span classical, post-quantum, and hybrid schemes. It supports BLS12-381 threshold signatures with share accumulation and combination. It supports SSH signature interoperability for all classical schemes plus BLS12-381 combined and share signatures. +This crate gives self-describing digital signature containers (`Multisig`) for 60 signature codecs and 13 signature-share codecs with the default features. The codecs span classical, post-quantum, hash-based, and hybrid schemes. It supports threshold signatures with share accumulation and combination for BLS12-381, Lamport, and Merkle-Lamport. It supports SSH signature interoperability for all classical schemes plus BLS12-381 combined and share signatures. **Supported signature families:** - **Classical:** Ed25519, secp256k1 (ECDSA), NIST P-256/P-384/P-521 (ECDSA), RSA-SHA256, BLS12-381 G1/G2 - **Post-quantum:** ML-DSA (65/87), FN-DSA (512/1024), MAYO (1/2/3/5), SLH-DSA (all 12 parameter sets) +- **Hash-based:** Lamport and Merkle-tree Lamport (SHA-2, SHA-3, BLAKE2, BLAKE3, SHAKE digests), XMSS-SHA2_10/16/20_256 - **Hybrid:** Ed25519+MAYO-2, Ed25519+ML-DSA-65, Ed25519+FN-DSA-512, BLS12-381-G1+ML-DSA-65, BLS12-381-G1+FN-DSA-512, BLS12-381-G1+MAYO-1, BLS12-381-G1+MAYO-2 -- **Threshold:** BLS12-381 G1/G2 combined and share signatures with threshold disclosure modes +- **Threshold:** BLS12-381 G1/G2 combined and share signatures with threshold disclosure modes, and Lamport and Merkle-Lamport signature shares **SSH interoperability:** Ed25519, secp256k1, NIST P-256/P-384/P-521, RSA-SHA256, and BLS12-381 G1/G2 (combined and share signatures) convert to and from OpenSSH format with the [`ssh-key`][SSHKEY] crate. Non-standard algorithms use [RFC 4251][RFC4251] "additional algorithms" names with the `@multisig` domain suffix, for example `secp256k1@multisig` and `bls12_381-g1-share@multisig`. +**Optional crypto:** the BLS12-381, Lamport, and XMSS views and the threshold metadata encryption each sit behind a [Cargo feature](#cargo-features). All are on by default. With `default-features = false` the crate pulls in no signature or AEAD crate. + ## Introduction This is a Rust implementation of a multicodec container format for digital signatures. The design is intentionally abstract. It supports any kind of digital signature data for any protocol. The format is a container of signature data with abstract, protocol-specific views backed by a generic, self-describing data storage format. @@ -44,6 +47,8 @@ SIGIL (0x1239) | signature_codec | Varbytes(message) | Varuint(num_attributes) | The preferred base encoding for Multisig strings is `Base16Lower` (lowercase hex). +Encode with `Vec::::from(&ms)`, which borrows the multisig instead of cloning it (the owned `From` also works), and decode with `Multisig::try_from(bytes.as_slice())`. + ## Supported Signature Formats ### Classical Signatures @@ -63,26 +68,36 @@ The preferred base encoding for Multisig strings is `Base16Lower` (lowercase hex | Codec | Multicodec name | SSH | Notes | |---|---|---|---| -| `Mldsa65Msig` | `mldsa-65-msig` | no | ML-DSA (Dilithium) security level 65; FIPS 204 | -| `Mldsa87Msig` | `mldsa-87-msig` | no | ML-DSA security level 87; FIPS 204 | +| `MlDsa65Msig` | `ml-dsa-65-msig` | no | ML-DSA-65; FIPS 204 | +| `MlDsa87Msig` | `ml-dsa-87-msig` | no | ML-DSA-87; FIPS 204 | | `FnDsa512Msig` | `fn-dsa-512-msig` | no | FN-DSA (Falcon) 512; FIPS 206 (draft) | | `FnDsa1024Msig` | `fn-dsa-1024-msig` | no | FN-DSA (Falcon) 1024; FIPS 206 (draft) | | `Mayo1Msig` | `mayo-1-msig` | no | MAYO-1 | | `Mayo2Msig` | `mayo-2-msig` | no | MAYO-2 | | `Mayo3Msig` | `mayo-3-msig` | no | MAYO-3 | | `Mayo5Msig` | `mayo-5-msig` | no | MAYO-5 | -| `SlhdsaSha2128FMsig` | `slhdsa-sha2-128f-msig` | no | SLH-DSA (SPHINCS+) SHA-2 128f; FIPS 205 | -| `SlhdsaSha2128SMsig` | `slhdsa-sha2-128s-msig` | no | SLH-DSA SHA-2 128s | -| `SlhdsaSha2192FMsig` | `slhdsa-sha2-192f-msig` | no | SLH-DSA SHA-2 192f | -| `SlhdsaSha2192SMsig` | `slhdsa-sha2-192s-msig` | no | SLH-DSA SHA-2 192s | -| `SlhdsaSha2256FMsig` | `slhdsa-sha2-256f-msig` | no | SLH-DSA SHA-2 256f | -| `SlhdsaSha2256SMsig` | `slhdsa-sha2-256s-msig` | no | SLH-DSA SHA-2 256s | -| `SlhdsaShake128FMsig` | `slhdsa-shake-128f-msig` | no | SLH-DSA SHAKE 128f | -| `SlhdsaShake128SMsig` | `slhdsa-shake-128s-msig` | no | SLH-DSA SHAKE 128s | -| `SlhdsaShake192FMsig` | `slhdsa-shake-192f-msig` | no | SLH-DSA SHAKE 192f | -| `SlhdsaShake192SMsig` | `slhdsa-shake-192s-msig` | no | SLH-DSA SHAKE 192s | -| `SlhdsaShake256FMsig` | `slhdsa-shake-256f-msig` | no | SLH-DSA SHAKE 256f | -| `SlhdsaShake256SMsig` | `slhdsa-shake-256s-msig` | no | SLH-DSA SHAKE 256s | +| `SlhDsaSha2128FMsig` | `slh-dsa-sha2-128f-msig` | no | SLH-DSA (SPHINCS+) SHA-2 128f; FIPS 205 | +| `SlhDsaSha2128SMsig` | `slh-dsa-sha2-128s-msig` | no | SLH-DSA SHA-2 128s | +| `SlhDsaSha2192FMsig` | `slh-dsa-sha2-192f-msig` | no | SLH-DSA SHA-2 192f | +| `SlhDsaSha2192SMsig` | `slh-dsa-sha2-192s-msig` | no | SLH-DSA SHA-2 192s | +| `SlhDsaSha2256FMsig` | `slh-dsa-sha2-256f-msig` | no | SLH-DSA SHA-2 256f | +| `SlhDsaSha2256SMsig` | `slh-dsa-sha2-256s-msig` | no | SLH-DSA SHA-2 256s | +| `SlhDsaShake128FMsig` | `slh-dsa-shake128f-msig` | no | SLH-DSA SHAKE 128f | +| `SlhDsaShake128SMsig` | `slh-dsa-shake128s-msig` | no | SLH-DSA SHAKE 128s | +| `SlhDsaShake192FMsig` | `slh-dsa-shake192f-msig` | no | SLH-DSA SHAKE 192f | +| `SlhDsaShake192SMsig` | `slh-dsa-shake192s-msig` | no | SLH-DSA SHAKE 192s | +| `SlhDsaShake256FMsig` | `slh-dsa-shake256f-msig` | no | SLH-DSA SHAKE 256f | +| `SlhDsaShake256SMsig` | `slh-dsa-shake256s-msig` | no | SLH-DSA SHAKE 256s | + +### Hash-Based Signatures + +None of these convert to SSH format. + +| Codecs | Multicodec names | Feature | Notes | +|---|---|---|---| +| `LamportSha3512Sig`, `LamportSha3384Sig`, `LamportSha3256Sig`, `LamportSha2512Sig`, `LamportSha2384Sig`, `LamportSha2256Sig`, `LamportBlake2B512Sig`, `LamportBlake2S256Sig`, `LamportBlake3256Sig`, `LamportShake128Sig`, `LamportShake256Sig` | `lamport-sha3-512-sig` … `lamport-shake-256-sig` | `lamport` | One-time Lamport signatures, one codec per digest; threshold shares supported | +| `LamportMerkleSha3512Sig` … `LamportMerkleShake256Sig` (same 11 digests) | `lamport-merkle-sha3-512-sig` … `lamport-merkle-shake-256-sig` | `lamport` | Merkle-tree Lamport signatures; carry the tree `depth` attribute; threshold shares supported | +| `XmssSha210256Msig`, `XmssSha216256Msig`, `XmssSha220256Msig` | `xmss-sha2-10-256-msig`, `xmss-sha2-16-256-msig`, `xmss-sha2-20-256-msig` | `xmss` | XMSS (RFC 8391); listed in `SIG_CODECS` only when `lamport` is also on; carry the `sig-index` leaf index attribute | ### Hybrid Signatures (Classical + Post-Quantum) @@ -98,13 +113,15 @@ Hybrid signatures use a nested combiner construction. The classical component si | `Bls12381G1Mayo1Msig` | `bls12381-g1-mayo1-msig` | BLS12-381 G1 + MAYO-1 | no | | `Bls12381G1Mayo2Msig` | `bls12381-g1-mayo2-msig` | BLS12-381 G1 + MAYO-2 | no | -### Threshold Signature Shares (BLS12-381) +### Threshold Signature Shares | Codec | Multicodec name | SSH algorithm | Notes | |---|---|---|---| | `Bls12381G1ShareMsig` | `bls12_381-g1-share-msig` | `bls12_381-g1-share@multisig` | A BLS G1 partial signature from a threshold share | | `Bls12381G2ShareMsig` | `bls12_381-g2-share-msig` | `bls12_381-g2-share@multisig` | A BLS G2 partial signature from a threshold share | +The 11 Merkle-Lamport share codecs (`LamportMerkleSha3512SigShare` … `LamportMerkleShake256SigShare`, multicodec names ending in `-sig-share`) carry Merkle-Lamport signature shares and need the `lamport` feature. `SIG_SHARE_CODECS` lists every share codec compiled in. + ## Attribute IDs Each Multisig carries a set of attributes identified by a `u8` code: @@ -114,13 +131,17 @@ Each Multisig carries a set of attributes identified by a `u8` code: | 0 | `sig-data` | all | The raw signature bytes | | 1 | `payload-encoding` | all (optional) | The multicodec encoding of the signed payload | | 2 | `scheme` | BLS | BLS scheme type: 0=Basic, 1=MessageAugmentation, 2=ProofOfPossession | -| 3 | `threshold` | BLS shares | The threshold `t` (plaintext, Full disclosure mode) | -| 4 | `limit` | BLS shares | The share count `n` (plaintext, Full/Partial disclosure modes) | +| 3 | `threshold` | threshold shares | The threshold `t` (plaintext, Full disclosure mode) | +| 4 | `limit` | threshold shares | The share count `n` (plaintext, Full/Partial disclosure modes) | | 5 | `share-identifier` | BLS shares | 32-byte BLS scalar identifier for this share | -| 6 | `threshold-data` | BLS combined | Serialized `ThresholdData` — the accumulated share map | -| 7 | `threshold-disclosure` | BLS (optional) | Disclosure mode: 0=Full, 1=Partial, 2=FullConfidentialial | +| 6 | `threshold-data` | threshold accumulators | The accumulated shares (BLS share map, or the Lamport share-blob list) | +| 7 | `threshold-disclosure` | BLS (optional) | Disclosure mode: 0=Full, 1=Partial, 2=FullConfidential | | 8 | `encrypted-threshold-meta` | BLS (optional) | AEAD-encrypted CBOR blob containing t and/or n | | 9 | `threshold-meta-cipher` | BLS (optional) | CBOR-encoded cipher info (codec + nonce) for decrypting #8 | +| 10 | `sig-index` | XMSS | The one-time leaf index the signature consumed (u32 big-endian) | +| 11 | `depth` | Merkle-Lamport | The Merkle tree depth (one byte); cross-checked against the signature data | + +`AttrId` parses from its name with `FromStr`, e.g. `"sig-data".parse::()`. `AttrId::try_from("sig-data")` still works. ## Views on the Multisig Data @@ -149,7 +170,7 @@ let attrs = ViewBuilder::new(&ms).attr().build().unwrap(); assert_eq!(attrs.scheme().unwrap(), 0); ``` -The six kinds are `attr`, `data`, `conv`, `threshold_attr`, `threshold`, and `disclosure`. Select each with `.attr()`, `.data()`, `.conv()`, `.threshold_attr()`, `.threshold()`, or `.disclosure()`. A view borrows its Multisig, so keep the Multisig alive while the view is in use. Built-in codecs dispatch through the crate-internal `views::dispatch` core. A built-in view is identical to the view the deprecated `Views` trait method returns for that codec. +The six kinds are `attr`, `data`, `conv`, `threshold_attr`, `threshold`, and `disclosure`. Select each with `.attr()`, `.data()`, `.conv()`, `.threshold_attr()`, `.threshold()`, or `.disclosure()`. A view borrows its Multisig, so keep the Multisig alive while the view is in use. Built-in codecs dispatch through the crate-internal `views::dispatch` core. `ViewBuilder` is `Send` + `Sync` when its registered factories are. The view trait objects it returns carry no `Send`/`Sync` supertrait, so they cannot be shared across threads at the type level. @@ -212,10 +233,9 @@ Built-in views always win: a factory registered for a codec that has a built-in | `AttrView` | `payload_encoding()`, `scheme()` | Access the payload encoding codec and signing scheme | | `DataView` | `sig_bytes()` | Access the raw signature bytes | | `ConvView` | `to_ssh_signature()` | Convert to an OpenSSH `ssh_key::Signature` | -| `ThresholdAttrView` | `threshold()`, `limit()`, `identifier()`, `threshold_data()` | Read threshold parameters (BLS only) | -| `ThresholdView` | `shares()`, `shares_with_disclosure()`, `add_share()`, `add_share_with_meta()`, `combine()`, `combine_with_meta()` | Accumulate and combine threshold signature shares (BLS only) | +| `ThresholdAttrView` | `threshold()`, `limit()`, `identifier()`, `threshold_data()` | Read threshold parameters (BLS, Lamport, Merkle-Lamport) | +| `ThresholdView` | `shares()`, `shares_with_disclosure()`, `add_share()`, `add_share_with_meta()`, `combine()`, `combine_with_meta()` | Accumulate and combine threshold signature shares (BLS, Lamport, Merkle-Lamport) | | `ThresholdDisclosureView` | `disclosure_mode()`, `read_threshold_params()`, `to_disclosure()` | Read or convert the threshold disclosure mode (all codecs) | -| `Views` (deprecated) | `attr_view()`, `data_view()`, `conv_view()`, `threshold_attr_view()`, `threshold_view()`, `disclosure_view()` | Dispatcher trait — obtain any view from a `Multisig`. **Deprecated since 1.5.0**: use `ViewBuilder` (removal planned for 2.0.0) | ### View Dispatch by Codec Family @@ -232,12 +252,15 @@ Built-in views always win: a factory registered for a codec that has a built-in | SLH-DSA (all 12) | `slh_dsa::View` | `slh_dsa::View` | `slh_dsa::View` | — | — | | Ed25519-MAYO2 | `ed25519_mayo2::View` | `ed25519_mayo2::View` | `ed25519_mayo2::View` | — | — | | Other hybrids | `ed25519_hybrid::View` | `ed25519_hybrid::View` | `ed25519_hybrid::View` | — | — | +| Lamport | `lamport::View` | `lamport::View` | `lamport::View` | `lamport::View` | `lamport::View` | +| Merkle-Lamport | `lamport_merkle::View` | `lamport_merkle::View` | `lamport_merkle::View` | `lamport_merkle::View` | `lamport_merkle::View` | +| XMSS | `xmss::View` | `xmss::View` | `xmss::View` | — | — | -Dispatch runs inside `ViewBuilder` through the crate-internal `views::dispatch` functions. The table content is unchanged from earlier releases. The `disclosure` view is codec-agnostic. It is available on all codecs. +Dispatch runs inside `ViewBuilder` through the crate-internal `views::dispatch` functions. The `disclosure` view is codec-agnostic. It is available on all codecs. ### Copy-on-Write Semantics -Operations that appear to mutate the Multisig (`add_share`, `combine`, `to_disclosure`) in fact perform a copy-on-write (CoW) operation. They return a **new** `Multisig`. The original is unchanged. This is most visible in `Builder::try_build()`: +Operations that appear to mutate the Multisig (`add_share`, `combine`, `to_disclosure`) in fact perform a copy-on-write (CoW) operation. They return a **new** `Multisig`. The original is unchanged, so a share-accumulation loop rebinds the result: ```rust let mut ms = Builder::new(Codec::Bls12381G2Msig).try_build()?; @@ -258,8 +281,8 @@ The `Builder` constructs `Multisig` objects. It is a different type from `ViewBu |---|---| | `Builder::new(codec)` | Create a builder for the given signature codec | | `Builder::new_from_ssh_signature(&sig)` | Construct from an OpenSSH `ssh_key::Signature` | -| `Builder::new_from_bls_signature(&sig)` | Construct from a `blsful::Signature` (infers G1/G2 by byte length) | -| `Builder::new_from_bls_signature_share(t, n, &share)` | Construct from a `blsful::SignatureShare` | +| `Builder::new_from_bls_signature_with_codec(codec, &sig)` | Construct from a `blsful::Signature` with an explicit G1/G2 codec (`bls12-381` feature) | +| `Builder::new_from_bls_signature_share_with_codec(codec, t, n, &share)` | Construct from a `blsful::SignatureShare` with an explicit codec (`bls12-381` feature) | | `.with_message_bytes(&msg)` | Set the message payload (makes a combined signature) | | `.with_signature_bytes(&data)` | Set the raw signature bytes (`AttrId::SigData`) | | `.with_payload_encoding(codec)` | Set the payload encoding codec | @@ -332,7 +355,7 @@ For verification, `VerifyView::verify(sig, msg)`: ## Threshold Signatures (BLS12-381) -BLS12-381 is the only signature family that supports threshold signatures in this crate. A threshold BLS signature is produced by multiple parties. Each party signs with their key share. The partial signatures are then combined into a single combined signature. The combined signature verifies against the group public key. +BLS12-381, Lamport, and Merkle-Lamport support threshold signatures in this crate. Lamport shares are opaque blobs that embed their own GF(256) identifier, so the accumulator is a list of share blobs and `combine` hands them to `lamport_signature_plus`. The rest of this section covers BLS12-381, which interpolates over scalar share identifiers. A threshold BLS signature is produced by multiple parties. Each party signs with their key share. The partial signatures are then combined into a single combined signature. The combined signature verifies against the group public key. ### BLS Signature Schemes @@ -344,6 +367,8 @@ BLS12-381 supports three signature schemes, stored as `AttrId::Scheme`: | `MessageAugmentation` | 1 | Prepends a domain tag to the message before signing. | | `ProofOfPossession` | 2 | Requires a separate PoP signature over the public key. This is the **default** and the strongest rogue-key defence. | +`SchemeTypeId` parses from `"basic"`, `"message-augmentation"`, or `"proof-of-possession"` with `FromStr`. + ### How Threshold Signatures Work 1. A BLS secret key is split into `n` shares with threshold `t` using the `Multi-Key` crate's `ThresholdView::split(t, n)` or `split_with_disclosure(t, n, mode, meta_key)`. @@ -393,9 +418,9 @@ By default, threshold `t` and share count `n` are stored as **plaintext** attrib |---|---|---|---|---| | `Full` (default, 0) | plaintext attribute | plaintext attribute | everyone | everyone | | `Partial` (1) | encrypted (AEAD) | plaintext attribute | key-holder only | everyone (auditable) | -| `FullConfidentialial` (2) | encrypted (AEAD) | encrypted (AEAD) | key-holder only | key-holder only | +| `FullConfidential` (2) | encrypted (AEAD) | encrypted (AEAD) | key-holder only | key-holder only | -The encrypted values are sealed with **ChaCha20-Poly1305 AEAD**. They are stored as a CBOR-encoded `ThresholdMetadata` blob in `AttrId::EncryptedThresholdMeta`. The cipher parameters (codec and nonce) are recorded in `AttrId::ThresholdMetaCipher` so the blob is self-describing for decryption. A separate **meta key** (a 32-byte symmetric `Multikey` with `Codec::Chacha20Poly1305`) is required to encrypt and decrypt the metadata. +The encrypted values are sealed with **ChaCha20-Poly1305 AEAD**. They are stored as a CBOR-encoded `ThresholdMetadata` blob in `AttrId::EncryptedThresholdMeta`. The cipher parameters (codec and nonce) are recorded in `AttrId::ThresholdMetaCipher` so the blob is self-describing for decryption. A separate **meta key** (a 32-byte symmetric `Multikey` with `Codec::Chacha20Poly1305`) is required to encrypt and decrypt the metadata. The encrypted modes need the `chacha20` feature; without it they return `SharesError::MetaEncryption`. ### When to Use Each Mode @@ -403,11 +428,11 @@ The encrypted values are sealed with **ChaCha20-Poly1305 AEAD**. They are stored - **`Partial`** — Use when the total number of participants `n` should be auditable (for example, for governance transparency) but the threshold `t` should be hidden from share holders and observers. Hiding `t` means an adversary who compromises some shares does not know how many more they need to reconstruct. The `meta_key` is required to read `t`. The value `n` is freely readable. -- **`FullConfidentialial`** — Use when both `t` and `n` must be kept secret. An observer who sees a share cannot determine the group size or how many shares are needed. This is the strongest confidentiality mode. The `meta_key` is required to read both `t` and `n`. +- **`FullConfidential`** — Use when both `t` and `n` must be kept secret. An observer who sees a share cannot determine the group size or how many shares are needed. This is the strongest confidentiality mode. The `meta_key` is required to read both `t` and `n`. ### Trade-offs -| Consideration | Full | Partial | FullConfidentialial | +| Consideration | Full | Partial | FullConfidential | |---|---|---|---| | Backward compatible | yes | yes (attribute defaults to Full if absent) | yes | | Observer learns `t` | yes | no | no | @@ -417,7 +442,7 @@ The encrypted values are sealed with **ChaCha20-Poly1305 AEAD**. They are stored | Risk if `meta_key` lost | n/a | `t` irrecoverable | `t` and `n` irrecoverable | | Performance overhead | none | negligible (AEAD on ~10 bytes) | negligible | -**Key management risk.** Losing the `meta_key` makes `t` (Partial) or both `t` and `n` (FullConfidentialial) irrecoverable. This prevents share combination. The `meta_key` should be stored or backed up with the existing at-rest encryption mechanisms. You can always convert back to `Full` mode (with the `meta_key`) before you lose it. +**Key management risk.** Losing the `meta_key` makes `t` (Partial) or both `t` and `n` (FullConfidential) irrecoverable. This prevents share combination. The `meta_key` should be stored or backed up with the existing at-rest encryption mechanisms. You can always convert back to `Full` mode (with the `meta_key`) before you lose it. ### Creating Shares with a Disclosure Mode @@ -434,7 +459,7 @@ let meta_mk = Builder::new(Codec::Chacha20Poly1305) .try_build()?; let shares = ViewBuilder::new(&mk).threshold().build()?.split_with_disclosure(3, 5, - ThresholdDisclosure::FullConfidentialial, Some(&meta_mk))?; + ThresholdDisclosure::FullConfidential, Some(&meta_mk))?; ``` **2. Builder construction:** @@ -453,7 +478,7 @@ let share = Builder::new(Codec::Bls12381G2ShareMsig) let encrypted = ViewBuilder::new(&share) .disclosure() .build()? - .to_disclosure(ThresholdDisclosure::FullConfidentialial, Some(&meta_mk), None)?; + .to_disclosure(ThresholdDisclosure::FullConfidential, Some(&meta_mk), None)?; ``` ### Reading Threshold Parameters from Encrypted Shares @@ -487,13 +512,13 @@ let partial = ViewBuilder::new(&full) .build()? .to_disclosure(ThresholdDisclosure::Partial, Some(&meta_mk), None)?; -// Partial -> FullConfidentialial +// Partial -> FullConfidential let confidential = ViewBuilder::new(&partial) .disclosure() .build()? - .to_disclosure(ThresholdDisclosure::FullConfidentialial, Some(&meta_mk), Some(&meta_mk))?; + .to_disclosure(ThresholdDisclosure::FullConfidential, Some(&meta_mk), Some(&meta_mk))?; -// FullConfidentialial -> Full +// FullConfidential -> Full let full_again = ViewBuilder::new(&confidential) .disclosure() .build()? @@ -522,10 +547,32 @@ A multicodec signature format called Varsig (`0x34`) already exists. It has seri ## Cargo Features +Each crypto dependency sits behind its own feature. With `default-features = false` the crate provides only the `Multisig` type, its attributes, the view traits, and the `ViewBuilder`, with no cryptographic crates. + | Feature | Default | Description | |---|---|---| +| `bls12-381` | yes | BLS12-381 signature and share views, share combining, and the `Builder::new_from_bls_*` constructors (`blsful`) | +| `chacha20` | yes | ChaCha20-Poly1305 encryption of threshold metadata (`encrypt_threshold_meta`, `decrypt_threshold_meta`, `generate_meta_key`); without it the partial and fully confidential disclosure modes return `SharesError::MetaEncryption` | +| `lamport` | yes | Lamport and Merkle-Lamport signature views (`lamport_signature_plus` and its hash crates) | +| `xmss` | yes | XMSS signature views | | `serde` | yes | Serde serialization for `Multisig` and `AttrId` | +A codec appears in `SIG_CODECS` and `SIG_SHARE_CODECS` only when its views are compiled in. + +## Upgrading from 1.x + +2.0 moves the crypto dependencies behind features. The default build keeps every view, so `multi-sig = "2.0"` behaves as 1.x did. + +- If you used `default-features = false` only to drop serde, add back what you use: `bls12-381` for the BLS views and `Builder::new_from_bls_*`, `chacha20` for `encrypt_threshold_meta`, `decrypt_threshold_meta`, and `generate_meta_key`. +- Without `chacha20`, the `Partial` and `FullConfidential` disclosure modes return `SharesError::MetaEncryption` instead of writing the threshold in plaintext. +- Without `bls12-381`, the BLS12-381 G1 and G2 combined codecs leave `SIG_CODECS` and the two BLS share codecs leave `SIG_SHARE_CODECS`, so each array is two entries shorter. This matches how the `lamport` and `xmss` codecs already behaved. +- `Builder::new_from_bls_signature` and `Builder::new_from_bls_signature_share` are gone. Use `new_from_bls_signature_with_codec(codec, &sig)` and `new_from_bls_signature_share_with_codec(codec, t, n, &share)`. +- `ThresholdDisclosure::FullConfidentialial` is renamed `FullConfidential`. The wire value (2) is unchanged; its display string is now `full-confidential`. +- The deprecated `Views` trait is gone. Replace `ms.attr_view()` with `ViewBuilder::new(&ms).attr().build()`, and likewise for the other five view kinds. +- Encode by reference with `Vec::::from(&ms)` to avoid cloning. + +See [CHANGELOG.md](CHANGELOG.md) for the full list. + ## Links - [Cryptid Technologies][CRYPTID] @@ -542,4 +589,4 @@ A multicodec signature format called Varsig (`0x34`) already exists. It has seri [MULTISIG]: https://github.com/cryptidtech/provenance-specifications/blob/main/specifications/multisig.md [SSHKEY]: https://crates.io/crates/ssh-key [RFC4251]: https://www.rfc-editor.org/rfc/rfc4251.html#page-11 -[MULTIKEY]: https://github.com/cryptidtech/multi-key.git \ No newline at end of file +[MULTIKEY]: https://github.com/cryptidtech/multi-key \ No newline at end of file diff --git a/SECURITY.md b/SECURITY.md index 50289c4..910363a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -6,7 +6,7 @@ The `multi-sig` crate gives self-describing digital signatures. It follows the m ## std-only Status -This crate is std-only. It depends on `std::collections::BTreeMap`, `std::fmt`, and `unsigned-varint` with the `std` feature. The crypto dependency stack (`blsful`, `ssh-key`, `chacha20poly1305`) also requires std. A `no_std` conversion is not planned for this crate. +This crate is std-only. It depends on `std::collections::BTreeMap`, `std::fmt`, and `unsigned-varint` with the `std` feature. The crypto dependency stack (`ssh-key`, plus `blsful` with the `bls12-381` feature and `chacha20poly1305` with the `chacha20` feature) also requires std. A `no_std` conversion is not planned for this crate. ## Release-Candidate Dependencies @@ -14,7 +14,7 @@ This crate depends on the following release-candidate (RC) crate: - `ssh-key = "0.7.0-rc.11"` — SSH key and signature encoding -The `blsful` dependency is now on a stable release (`4.0.0`). The `vsss-rs` crate is a transitive dependency via `blsful`. It resolved to the stable release `6.0.1` in this version. +The optional `blsful` dependency (`bls12-381` feature) is on a stable release (`4.1.0`). The `vsss-rs` crate is a transitive dependency via `blsful`. It resolved to the stable release `6.0.1` in this version. The `ssh-key` crate is on an RC version. No stable release exists at the time of writing. The crate keeps it on RC for three reasons: @@ -37,11 +37,11 @@ Exceeding any cap returns a clean `Err` (`Error::TooManyAttributes`, `Error::Inp ## BLS12-381 Codec Inference -The deprecated `Builder::new_from_bls_signature` and `Builder::new_from_bls_signature_share` constructors infer the BLS12-381 codec (G1 vs G2) from the compressed-point byte length (48 bytes to G1, 96 bytes to G2). This is a heuristic, not cryptographic binding. Prefer `new_from_bls_signature_with_codec` and `new_from_bls_signature_share_with_codec`. They take an explicit codec parameter. +`Builder::new_from_bls_signature_with_codec` and `Builder::new_from_bls_signature_share_with_codec` take the BLS12-381 codec (G1 or G2) from the caller. The constructors that inferred it from the compressed-point byte length were removed in 2.0.0, because a length heuristic cannot bind the codec to the curve. ## Memory Safety -- No unsafe code. `#![deny(unsafe_code)]` is enforced at compile time. +- No unsafe code. `unsafe_code = "deny"` in the `[lints.rust]` table of `Cargo.toml` enforces it at compile time for every target. - Input validation. All decode paths validate lengths, attribute counts, and codec identifiers. ## Reporting Vulnerabilities diff --git a/src/attrid.rs b/src/attrid.rs index 513d4c7..5d45acc 100644 --- a/src/attrid.rs +++ b/src/attrid.rs @@ -23,7 +23,7 @@ pub enum AttrId { ShareIdentifier, /// codec-specific threshold signature data ThresholdData, - /// Threshold disclosure mode (varuint u8): 0=Full, 1=Partial, 2=FullConfidentialial. + /// Threshold disclosure mode (varuint u8): 0=Full, 1=Partial, 2=FullConfidential. ThresholdDisclosure, /// AEAD-encrypted threshold metadata CBOR blob. EncryptedThresholdMeta, @@ -114,10 +114,10 @@ impl<'a> TryDecodeFrom<'a> for AttrId { } } -impl TryFrom<&str> for AttrId { - type Error = Error; +impl std::str::FromStr for AttrId { + type Err = Error; - fn try_from(s: &str) -> Result { + fn from_str(s: &str) -> Result { match s.to_ascii_lowercase().as_str() { "sig-data" => Ok(Self::SigData), "payload-encoding" => Ok(Self::PayloadEncoding), @@ -136,8 +136,46 @@ impl TryFrom<&str> for AttrId { } } +impl TryFrom<&str> for AttrId { + type Error = Error; + + fn try_from(s: &str) -> Result { + s.parse() + } +} + impl fmt::Display for AttrId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.as_str()) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// every attribute name parses back to its id through `FromStr` and the + /// delegating `TryFrom<&str>`, case-insensitively + #[test] + fn test_from_str_round_trip() { + let ids: Vec = (0..=u8::MAX) + .filter_map(|code| AttrId::try_from(code).ok()) + .collect(); + assert!(!ids.is_empty()); + for id in ids { + assert!(id.as_str().parse::().unwrap() == id, "{id}"); + assert!(AttrId::try_from(id.as_str()).unwrap() == id, "{id}"); + let upper = id.as_str().to_ascii_uppercase(); + assert!(upper.parse::().unwrap() == id, "{id}"); + } + } + + /// an unknown attribute name is rejected + #[test] + fn test_from_str_unknown() { + assert!(matches!( + "no-such-attribute".parse::(), + Err(Error::Attributes(AttributesError::InvalidAttributeName(_))) + )); + } +} diff --git a/src/lib.rs b/src/lib.rs index ce2c168..549f7d2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,15 +5,22 @@ //! //! ## Overview //! -//! This crate provides multisig functionality for creating and managing self-describing -//! digital signatures with support for multiple signature schemes including Ed25519, -//! Secp256k1, and BLS12-381. +//! This crate provides multisig functionality for creating and managing +//! self-describing digital signatures. A [`Multisig`] holds the signature +//! codec, an optional in-band message, and a set of attributes; views give +//! typed, per-scheme access to them. Signing and verifying live in the +//! companion `multi-key` crate. //! //! ## Supported Signature Schemes //! -//! - **Ed25519** - Fast, secure elliptic curve signatures -//! - **Secp256k1** - Bitcoin/Ethereum curve signatures -//! - **BLS12-381** - Pairing-based signatures with aggregation support +//! - **Classical:** Ed25519, secp256k1, NIST P-256/P-384/P-521, RSA-SHA256, +//! BLS12-381 G1/G2 +//! - **Post-quantum:** ML-DSA, FN-DSA, MAYO, SLH-DSA +//! - **Hash-based:** Lamport, Merkle-tree Lamport, XMSS +//! - **Hybrid:** Ed25519 or BLS12-381 G1 combined with a post-quantum scheme +//! - **Threshold:** BLS12-381, Lamport, and Merkle-Lamport signature shares +//! +//! [`SIG_CODECS`] and [`SIG_SHARE_CODECS`] list the codecs compiled in. //! //! ## Quick Start //! @@ -23,9 +30,9 @@ //! use multi_sig::Builder; //! use multi_codec::Codec; //! -//! // Create a signature with Ed25519 -//! let sig_data = vec![0u8; 64]; // Ed25519 signature (64 bytes) -//! let multisig = Builder::new(Codec::Ed25519Pub) +//! // Wrap a 64-byte Ed25519 signature +//! let sig_data = vec![0u8; 64]; +//! let multisig = Builder::new(Codec::EddsaMsig) //! .with_signature_bytes(&sig_data) //! .try_build() //! .unwrap(); @@ -38,13 +45,13 @@ //! use multi_codec::Codec; //! //! let sig_data = vec![0u8; 64]; -//! let ms1 = Builder::new(Codec::Ed25519Pub) +//! let ms1 = Builder::new(Codec::EddsaMsig) //! .with_signature_bytes(&sig_data) //! .try_build() //! .unwrap(); //! -//! // Encode to bytes -//! let bytes: Vec = ms1.clone().into(); +//! // Encode to bytes; encoding by reference does not clone the multisig +//! let bytes: Vec = (&ms1).into(); //! //! // Decode from bytes //! let ms2 = Multisig::try_from(bytes.as_ref()).unwrap(); @@ -78,6 +85,18 @@ //! //! ## Features //! +//! Each crypto dependency sits behind its own feature, all enabled by +//! default. With `default-features = false` the crate provides only the +//! [`Multisig`] type, its attributes, the view traits, and the +//! [`ViewBuilder`], with no cryptographic crates. +//! +//! - **`bls12-381`** (default): BLS12-381 signature and share views, share +//! combining, and the `Builder::new_from_bls_*` constructors (`blsful`) +//! - **`chacha20`** (default): ChaCha20-Poly1305 encryption of threshold +//! metadata for the partial and fully confidential disclosure modes; +//! without it those modes return `SharesError::MetaEncryption` +//! - **`lamport`** (default): Lamport and Merkle-Lamport signature views +//! - **`xmss`** (default): XMSS signature views //! - **`serde`** (default): Enables serde serialization support //! //! ## Thread Safety @@ -86,74 +105,6 @@ //! registered factories are. The returned view trait objects carry no //! `Send`/`Sync` supertrait. -#![warn(missing_docs)] -#![deny( - unsafe_code, - trivial_casts, - trivial_numeric_casts, - unused_import_braces, - unused_qualifications -)] -// Pedantic/nursery lints are enabled at the workspace level via -// `[lints.clippy]` in Cargo.toml. The following allows suppress stylistic -// lints that would require large-scale churn for minimal security benefit. -// Each is reviewed individually. -#![allow( - // doc-markdown wrapping common terms in backticks is stylistic - clippy::doc_markdown, - // elidable_lifetime_names: explicit lifetimes aid readability - clippy::elidable_lifetime_names, - // missing_errors_doc: public APIs are documented; this is noisy on impl - // blocks and trait impls - clippy::missing_errors_doc, - // missing_panics_doc: we avoid panics; where they exist they are documented - clippy::missing_panics_doc, - // must_use_candidate: too noisy on every function returning Result - clippy::must_use_candidate, - // return_self_not_must_use: builder pattern returns self by design - clippy::return_self_not_must_use, - // use_self: causes churn in match arms on large enums - clippy::use_self, - // semicolon_if_nothing_returned: stylistic preference - clippy::semicolon_if_nothing_returned, - // or_fun_call: false positives for cheap constructors like BTreeMap::new - clippy::or_fun_call, - // missing_const_for_fn: many functions can't be const due to trait bounds - clippy::missing_const_for_fn, - // multiple_crate_versions: blsful pulls in duplicate versions (tracked) - clippy::multiple_crate_versions, - // too_many_lines: large match arms are inherent to this crate - clippy::too_many_lines, - // option_if_let_else: sometimes less readable than if-let - clippy::option_if_let_else, - // needless_for_each: false positives in test code - clippy::needless_for_each, - // single_match_else: single-arm match with else is clearer in context - clippy::single_match_else, - // uninlined_format_args: stylistic; format strings are clear as-is - clippy::uninlined_format_args, - // cast_possible_truncation: intentional in codec conversions - clippy::cast_possible_truncation, - // redundant_pub_crate: needed for crate-internal module visibility - clippy::redundant_pub_crate, - // redundant_clone: false positives where clone is needed for ownership - clippy::redundant_clone, - // items_after_statements: module-level items are ordered logically - clippy::items_after_statements, - // if_not_else: stylistic - clippy::if_not_else, - // explicit_iter_loop: into_iter() is idiomatic - clippy::explicit_iter_loop, - // enum_glob_use: glob imports of enums are used judiciously - clippy::enum_glob_use, - // branches_sharing_code: false positives in complex match arms - clippy::branches_sharing_code, - // too_long_first_doc_paragraph: crate-level doc paragraph length - clippy::too_long_first_doc_paragraph, - // unnecessary_semicolon: false positive - clippy::unnecessary_semicolon, -)] - /// Errors produced by this library pub mod error; pub use error::Error; @@ -178,8 +129,10 @@ pub mod views; pub use views::{ AttrView, ConvView, DataView, MAX_THRESHOLD_PARTICIPANTS, ThresholdAttrView, ThresholdDisclosure, ThresholdDisclosureView, ThresholdMetaCipher, ThresholdMetadata, - ThresholdView, decrypt_threshold_meta, encrypt_threshold_meta, generate_meta_key, + ThresholdView, }; +#[cfg(feature = "chacha20")] +pub use views::{decrypt_threshold_meta, encrypt_threshold_meta, generate_meta_key}; /// Builder-pattern view creation pub use views::builder::{ @@ -188,11 +141,6 @@ pub use views::builder::{ Unselected, ViewBuilder, ViewKind, }; -// The `Views` trait is deprecated; this re-export keeps source compatibility -// for the 1.x line. -#[allow(deprecated)] -pub use views::Views; - /// Merkle-tree Lamport signature view #[cfg(feature = "lamport")] pub use views::lamport_merkle; @@ -207,7 +155,7 @@ pub mod serde; /// use multi_sig::prelude::*; /// /// let sig_data = vec![0u8; 64]; -/// let ms = Builder::new(Codec::Ed25519Pub) +/// let ms = Builder::new(Codec::EddsaMsig) /// .with_signature_bytes(&sig_data) /// .try_build() /// .unwrap(); diff --git a/src/ms.rs b/src/ms.rs index e9f9760..ae5bf69 100644 --- a/src/ms.rs +++ b/src/ms.rs @@ -1,15 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 +#[cfg(feature = "bls12-381")] +use crate::views::bls12381::{self, SchemeTypeId}; use crate::{ - AttrId, AttrView, ConvView, DataView, Error, ThresholdAttrView, ThresholdView, - views::{ - ThresholdDisclosure, ThresholdDisclosureView, - bls12381::{self, SchemeTypeId}, - dispatch, secp256k1, threshold_meta, - }, + AttrId, Error, + views::{ThresholdDisclosure, dispatch, secp256k1, threshold_meta}, }; -// `Views` is deprecated; this import supports the deprecated delegating impl. -#[allow(deprecated)] -use crate::Views; +#[cfg(feature = "bls12-381")] use blsful::{ Signature, SignatureShare, inner_types::{GroupEncoding, PrimeField}, @@ -17,14 +13,24 @@ use blsful::{ }; use multi_base::Base; use multi_codec::Codec; -use multi_trait::{Null, TryDecodeFrom}; +use multi_trait::{EncodeInto, Null, TryDecodeFrom}; use multi_util::{BaseEncoded, CodecInfo, EncodingInfo, Varbytes, Varuint}; use std::{collections::BTreeMap, fmt}; +/// the number of BLS12-381 codecs in each of [`SIG_CODECS`] (G1, G2) and +/// [`SIG_SHARE_CODECS`] (G1 share, G2 share) +const BLS_CODEC_COUNT: usize = if cfg!(feature = "bls12-381") { 2 } else { 0 }; + +/// the number of XMSS codecs in [`SIG_CODECS`] +#[cfg(feature = "lamport")] +const XMSS_CODEC_COUNT: usize = if cfg!(feature = "xmss") { 3 } else { 0 }; + /// the list of signature codecs currently supported #[cfg(feature = "lamport")] -pub const SIG_CODECS: [Codec; 60] = [ +pub const SIG_CODECS: [Codec; 55 + BLS_CODEC_COUNT + XMSS_CODEC_COUNT] = [ + #[cfg(feature = "bls12-381")] Codec::Bls12381G1Msig, + #[cfg(feature = "bls12-381")] Codec::Bls12381G2Msig, Codec::EddsaMsig, Codec::Es256KMsig, @@ -102,8 +108,10 @@ pub const SIG_CODECS: [Codec; 60] = [ /// the list of signature codecs currently supported #[cfg(not(feature = "lamport"))] -pub const SIG_CODECS: [Codec; 35] = [ +pub const SIG_CODECS: [Codec; 33 + BLS_CODEC_COUNT] = [ + #[cfg(feature = "bls12-381")] Codec::Bls12381G1Msig, + #[cfg(feature = "bls12-381")] Codec::Bls12381G2Msig, Codec::EddsaMsig, Codec::Es256KMsig, @@ -142,8 +150,10 @@ pub const SIG_CODECS: [Codec; 35] = [ /// the list of signature share codecs supported #[cfg(feature = "lamport")] -pub const SIG_SHARE_CODECS: [Codec; 13] = [ +pub const SIG_SHARE_CODECS: [Codec; 11 + BLS_CODEC_COUNT] = [ + #[cfg(feature = "bls12-381")] Codec::Bls12381G1ShareMsig, + #[cfg(feature = "bls12-381")] Codec::Bls12381G2ShareMsig, Codec::LamportMerkleSha3512SigShare, Codec::LamportMerkleSha3384SigShare, @@ -160,8 +170,10 @@ pub const SIG_SHARE_CODECS: [Codec; 13] = [ /// the list of signature share codecs supported #[cfg(not(feature = "lamport"))] -pub const SIG_SHARE_CODECS: [Codec; 2] = [ +pub const SIG_SHARE_CODECS: [Codec; BLS_CODEC_COUNT] = [ + #[cfg(feature = "bls12-381")] Codec::Bls12381G1ShareMsig, + #[cfg(feature = "bls12-381")] Codec::Bls12381G2ShareMsig, //, //Codec::LamportShareMsig, ]; @@ -229,24 +241,40 @@ impl EncodingInfo for Multisig { impl From for Vec { fn from(val: Multisig) -> Self { - let mut v = Vec::default(); + Self::from(&val) + } +} + +/// Encode a borrowed multisig without cloning its message or attributes +impl From<&Multisig> for Vec { + fn from(val: &Multisig) -> Self { + // the payloads plus a generous allowance for the varint prefixes + let payload: usize = val.attributes.values().map(|a| a.len() + 12).sum(); + let mut v = Self::with_capacity(32 + val.message.len() + payload); // add in the sigil v.append(&mut SIGIL.into()); // add in the signature codec v.append(&mut val.codec.into()); // add in the message - v.append(&mut Varbytes::new(val.message.clone()).into()); + encode_varbytes_into(&mut v, &val.message); // add in the number of attributes v.append(&mut Varuint(val.attributes.len()).into()); // add in the attributes val.attributes.iter().for_each(|(id, attr)| { v.append(&mut (*id).into()); - v.append(&mut Varbytes::new(attr.clone()).into()); + encode_varbytes_into(&mut v, attr); }); v } } +/// Append `data` in the `Varbytes` wire form (varint length, then the +/// bytes) without first copying it into a `Varbytes` +pub(crate) fn encode_varbytes_into(out: &mut Vec, data: &[u8]) { + out.extend_from_slice(&data.len().encode_into()); + out.extend_from_slice(data); +} + impl<'a> TryFrom<&'a [u8]> for Multisig { type Error = Error; @@ -292,7 +320,7 @@ impl<'a> TryDecodeFrom<'a> for Multisig { // Per-attribute size is already capped by Varbytes' // MAX_DECODED_SIZE (16 MiB). The total decoded-size cap // below provides a second layer of protection. - if attributes.insert(id, (*attr).clone()).is_some() { + if attributes.insert(id, attr.to_inner()).is_some() { return Err(Error::DuplicateAttribute(id.code())); } // Enforce total decoded size cap @@ -371,36 +399,6 @@ impl fmt::Debug for Multisig { } } -// The trait is deprecated; implementing it warrants this allowance. -#[allow(deprecated)] -impl Views for Multisig { - /// Provide a read-only view to access the signature attributes - fn attr_view<'a>(&'a self) -> Result, Error> { - dispatch::dispatch_attr_view(self) - } - /// Provide a read-only view to access signature data - fn data_view<'a>(&'a self) -> Result, Error> { - dispatch::dispatch_data_view(self) - } - /// Provide a view for converting to other signature formats - fn conv_view<'a>(&'a self) -> Result, Error> { - dispatch::dispatch_conv_view(self) - } - /// Provide a read-only view to access the threshold signature attributes - fn threshold_attr_view<'a>(&'a self) -> Result, Error> { - dispatch::dispatch_threshold_attr_view(self) - } - /// Provide the view for adding a share to a multisig - fn threshold_view<'a>(&'a self) -> Result, Error> { - dispatch::dispatch_threshold_view(self) - } - - /// Provide an interface for threshold disclosure mode operations - fn disclosure_view<'a>(&'a self) -> Result, Error> { - dispatch::dispatch_disclosure_view(self) - } -} - /// Builder for Multisigs #[derive(Clone, Default)] pub struct Builder { @@ -442,6 +440,7 @@ impl Builder { ..Default::default() }) } + #[cfg(feature = "bls12-381")] bls12381::ALGORITHM_NAME_G1 => { let sig_combined = bls12381::SigCombined::try_from(sig.as_bytes())?; attributes.insert(AttrId::Scheme, sig_combined.0.into()); @@ -452,6 +451,7 @@ impl Builder { ..Default::default() }) } + #[cfg(feature = "bls12-381")] bls12381::ALGORITHM_NAME_G2 => { let sig_combined = bls12381::SigCombined::try_from(sig.as_bytes())?; attributes.insert(AttrId::Scheme, sig_combined.0.into()); @@ -462,6 +462,7 @@ impl Builder { ..Default::default() }) } + #[cfg(feature = "bls12-381")] bls12381::ALGORITHM_NAME_G1_SHARE => { let sig_share = bls12381::SigShare::try_from(sig.as_bytes())?; attributes.insert(AttrId::ShareIdentifier, sig_share.0.0.to_be_bytes().into()); @@ -475,6 +476,7 @@ impl Builder { ..Default::default() }) } + #[cfg(feature = "bls12-381")] bls12381::ALGORITHM_NAME_G2_SHARE => { let sig_share = bls12381::SigShare::try_from(sig.as_bytes())?; attributes.insert(AttrId::ShareIdentifier, sig_share.0.0.to_be_bytes().into()); @@ -494,62 +496,17 @@ impl Builder { } } - /// create a new builder from a Bls Signature - /// - /// # Known limitation (length-based codec inference) - /// - /// The BLS12-381 codec (`Bls12381G1Msig` vs `Bls12381G2Msig`) is selected - /// from the compressed-point byte length: 48 bytes -> G1, 96 bytes -> G2. - /// This is a heuristic rather than cryptographic binding — a 48-byte G2 - /// signature or a 96-byte G1 signature (both invalid for BLS12-381 but - /// constructable by an attacker controlling the input) would be - /// misclassified. Downstream code that trusts this codec tag for curve - /// selection must re-validate the signature against the intended curve - /// rather than relying on the codec alone. - /// - /// Prefer [`Self::new_from_bls_signature_with_codec`] when the curve is - /// known at the call site. - #[deprecated( - since = "1.0.7", - note = "length-based codec inference is ambiguous; use new_from_bls_signature_with_codec" - )] - pub fn new_from_bls_signature(sig: &Signature) -> Result - where - C: blsful::BlsSignatureImpl, - { - let scheme_type_id = SchemeTypeId::from(sig); - let sig_bytes: Vec = sig.as_raw_value().to_bytes().as_ref().to_vec(); - let codec = match sig_bytes.len() { - 48 => Codec::Bls12381G1Msig, // G1Projective::to_compressed() - 96 => Codec::Bls12381G2Msig, // G2Projective::to_compressed() - _ => { - return Err(Error::UnsupportedAlgorithm( - "invalid Bls signature size".to_string(), - )); - } - }; - let mut attributes = BTreeMap::new(); - attributes.insert(AttrId::SigData, sig_bytes); - attributes.insert(AttrId::Scheme, scheme_type_id.into()); - Ok(Self { - codec, - attributes: Some(attributes), - ..Default::default() - }) - } - /// Create a new builder from a BLS signature with an explicit codec. /// - /// This constructor avoids the length-based codec inference heuristic - /// used by [`Self::new_from_bls_signature`] by requiring the caller to - /// specify the BLS12-381 codec (`Bls12381G1Msig` or `Bls12381G2Msig`) - /// directly. Prefer this constructor when the curve is known at the call - /// site. + /// The caller names the BLS12-381 codec (`Bls12381G1Msig` or + /// `Bls12381G2Msig`) instead of having it inferred from the signature's + /// byte length, which cannot bind the codec to the curve. /// /// # Errors /// /// Returns [`Error::UnsupportedAlgorithm`] if `codec` is not a BLS12-381 /// signature codec. + #[cfg(feature = "bls12-381")] pub fn new_from_bls_signature_with_codec( codec: Codec, sig: &Signature, @@ -577,68 +534,17 @@ impl Builder { }) } - /// create a new builder from a Bls SignatureShare - /// - /// # Known limitation (length-based codec inference) - /// - /// The share codec (`Bls12381G1ShareMsig` vs `Bls12381G2ShareMsig`) is - /// selected from the compressed-point byte length: 48 bytes -> G1, - /// 96 bytes -> G2. As with [`Self::new_from_bls_signature`], this is a - /// heuristic, not cryptographic binding; downstream consumers must - /// re-validate against the intended curve rather than trusting the - /// codec tag alone. - /// - /// Prefer [`Self::new_from_bls_signature_share_with_codec`] when the - /// curve is known at the call site. - #[deprecated( - since = "1.0.7", - note = "length-based codec inference is ambiguous; use new_from_bls_signature_share_with_codec" - )] - pub fn new_from_bls_signature_share( - threshold: usize, - limit: usize, - sigshare: &SignatureShare, - ) -> Result - where - C: blsful::BlsSignatureImpl, - { - let scheme_type_id = SchemeTypeId::from(sigshare); - let sigshare = sigshare.as_raw_value(); - let identifier = sigshare.identifier().0.to_repr().as_ref().to_vec(); - let value = sigshare.value().0.to_bytes().as_ref().to_vec(); - let codec = match value.len() { - 48 => Codec::Bls12381G1ShareMsig, // large pubkeys, small signatures - 96 => Codec::Bls12381G2ShareMsig, // small pubkeys, large signatures - _ => { - return Err(Error::UnsupportedAlgorithm( - "invalid Bls signature size".to_string(), - )); - } - }; - let mut attributes = BTreeMap::new(); - attributes.insert(AttrId::SigData, value); - attributes.insert(AttrId::Threshold, Varuint(threshold).into()); - attributes.insert(AttrId::Limit, Varuint(limit).into()); - attributes.insert(AttrId::ShareIdentifier, identifier); - attributes.insert(AttrId::Scheme, scheme_type_id.into()); - Ok(Self { - codec, - attributes: Some(attributes), - ..Default::default() - }) - } - /// Create a new builder from a BLS signature share with an explicit codec. /// - /// This constructor avoids the length-based codec inference heuristic - /// used by [`Self::new_from_bls_signature_share`] by requiring the caller - /// to specify the BLS12-381 share codec - /// (`Bls12381G1ShareMsig` or `Bls12381G2ShareMsig`) directly. + /// The caller names the BLS12-381 share codec (`Bls12381G1ShareMsig` or + /// `Bls12381G2ShareMsig`) instead of having it inferred from the share's + /// byte length. /// /// # Errors /// /// Returns [`Error::UnsupportedAlgorithm`] if `codec` is not a BLS12-381 /// signature share codec. + #[cfg(feature = "bls12-381")] pub fn new_from_bls_signature_share_with_codec( codec: Codec, threshold: usize, @@ -686,61 +592,61 @@ impl Builder { self } - fn with_attribute(mut self, attr: AttrId, data: &Vec) -> Self { + fn with_attribute(mut self, attr: AttrId, data: Vec) -> Self { let mut attributes = self.attributes.unwrap_or_default(); - attributes.insert(attr, data.to_owned()); + attributes.insert(attr, data); self.attributes = Some(attributes); self } /// set the payload encoding codec pub fn with_payload_encoding(self, codec: Codec) -> Self { - self.with_attribute(AttrId::PayloadEncoding, &codec.into()) + self.with_attribute(AttrId::PayloadEncoding, codec.into()) } /// set the signing scheme pub fn with_scheme(self, scheme: u8) -> Self { - self.with_attribute(AttrId::Scheme, &Varuint(scheme).into()) + self.with_attribute(AttrId::Scheme, Varuint(scheme).into()) } /// add a signature payload pub fn with_signature_bytes(self, data: &impl AsRef<[u8]>) -> Self { - self.with_attribute(AttrId::SigData, &data.as_ref().to_vec()) + self.with_attribute(AttrId::SigData, data.as_ref().to_vec()) } /// add the threshold signature threshold pub fn with_threshold(self, threshold: usize) -> Self { - self.with_attribute(AttrId::Threshold, &Varuint(threshold).into()) + self.with_attribute(AttrId::Threshold, Varuint(threshold).into()) } /// add the threshold signature limit pub fn with_limit(self, limit: usize) -> Self { - self.with_attribute(AttrId::Limit, &Varuint(limit).into()) + self.with_attribute(AttrId::Limit, Varuint(limit).into()) } /// add the threshold signature identifier pub fn with_identifier(self, identifier: &impl AsRef<[u8]>) -> Self { - self.with_attribute(AttrId::ShareIdentifier, &identifier.as_ref().to_vec()) + self.with_attribute(AttrId::ShareIdentifier, identifier.as_ref().to_vec()) } /// add the threshold data pub fn with_threshold_data(self, tdata: &impl AsRef<[u8]>) -> Self { - self.with_attribute(AttrId::ThresholdData, &tdata.as_ref().to_vec()) + self.with_attribute(AttrId::ThresholdData, tdata.as_ref().to_vec()) } /// Set the XMSS leaf index for a stateful signature. pub fn with_sig_index(self, index: u32) -> Self { - self.with_attribute(AttrId::SigIndex, &index.to_be_bytes().to_vec()) + self.with_attribute(AttrId::SigIndex, index.to_be_bytes().to_vec()) } /// Set the merkle-tree depth (one raw byte, 1..=3). pub fn with_depth(self, depth: u8) -> Self { - self.with_attribute(AttrId::Depth, &vec![depth]) + self.with_attribute(AttrId::Depth, vec![depth]) } /// Set the disclosure mode for a threshold sig share being built. /// - /// In Full mode, t and n are plaintext. In Partial/FullConfidentialial, + /// In Full mode, t and n are plaintext. In Partial/FullConfidential, /// `meta_key` is required. pub fn with_disclosure( self, @@ -882,6 +788,7 @@ mod tests { assert_eq!(ms, Multisig::try_from(v.as_slice()).unwrap()); } + #[cfg(feature = "bls12-381")] #[test] fn test_bls_signature() { let sk = blsful::Bls12381G2::new_secret_key(); @@ -901,6 +808,7 @@ mod tests { assert_eq!(ms, Multisig::try_from(v.as_slice()).unwrap()); } + #[cfg(feature = "bls12-381")] #[test] fn test_bls_signature_combine() { let sk = blsful::Bls12381G2::new_secret_key(); @@ -988,6 +896,7 @@ mod tests { assert_eq!(ms1, ms2); } + #[cfg(feature = "bls12-381")] #[test] fn test_bls_signature_ssh_roundtrip() { let sk = blsful::Bls12381G1::new_secret_key(); @@ -1014,6 +923,7 @@ mod tests { assert_eq!(ms1, ms2); } + #[cfg(feature = "bls12-381")] #[test] fn test_bls_signature_combine_ssh_roundtrip() { let sk = blsful::Bls12381G2::new_secret_key(); diff --git a/src/serde/de.rs b/src/serde/de.rs index d61e7e9..aa3663e 100644 --- a/src/serde/de.rs +++ b/src/serde/de.rs @@ -30,28 +30,16 @@ impl<'de> Deserialize<'de> for AttrId { where E: Error, { - AttrId::try_from(c).map_err(|e| Error::custom(e.to_string())) + AttrId::try_from(c).map_err(E::custom) } + // serde's default `visit_borrowed_str` and `visit_string` + // forward here fn visit_str(self, s: &str) -> Result where E: Error, { - AttrId::try_from(s).map_err(|e| Error::custom(e.to_string())) - } - - fn visit_borrowed_str(self, s: &'de str) -> Result - where - E: Error, - { - AttrId::try_from(s).map_err(|e| Error::custom(e.to_string())) - } - - fn visit_string(self, s: String) -> Result - where - E: Error, - { - AttrId::try_from(s.as_str()).map_err(|e| Error::custom(e.to_string())) + s.parse().map_err(E::custom) } } @@ -113,10 +101,9 @@ impl<'de> Deserialize<'de> for Multisig { } let attr: Vec<(AttrId, EncodedVarbytes)> = map.next_value()?; let mut a = Attributes::new(); - attr.iter() - .try_for_each(|(id, attr)| -> Result<(), V::Error> { - let i = *id; - let v: Vec = (**attr).clone().to_inner(); + attr.into_iter() + .try_for_each(|(i, attr)| -> Result<(), V::Error> { + let v: Vec = attr.to_inner().to_inner(); if a.insert(i, v).is_some() { return Err(Error::duplicate_field( "duplicate attribute id", @@ -143,35 +130,29 @@ impl<'de> Deserialize<'de> for Multisig { if deserializer.is_human_readable() { deserializer.deserialize_struct(ms::SIGIL.as_str(), FIELDS, MultisigVisitor) } else { - // Use `deserialize_byte_buf` with a visitor that accepts both - // borrowed and owned bytes. This works with `serde_test` - // (BorrowedBytes), `serde_cbor` (borrowed), and `ciborium` - // (owned). The previous `&'de [u8]` bound only worked with - // deserializers that support borrowing from input. + // `deserialize_byte_buf` with a visitor that accepts both borrowed + // and owned bytes works with `serde_test` (BorrowedBytes), + // `serde_cbor_2` (borrowed), and reader-based decoders (owned). + // Both paths decode straight from the input bytes. struct ByteBufVisitor; - impl<'de> Visitor<'de> for ByteBufVisitor { - type Value = Vec; + impl Visitor<'_> for ByteBufVisitor { + type Value = Multisig; fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("byte buffer") } - fn visit_borrowed_bytes(self, v: &'de [u8]) -> Result { - Ok(v.to_vec()) - } - fn visit_bytes(self, v: &[u8]) -> Result { - Ok(v.to_vec()) + Multisig::try_from(v).map_err(E::custom) } fn visit_byte_buf(self, v: Vec) -> Result { - Ok(v) + self.visit_bytes(v.as_slice()) } } - let b = deserializer.deserialize_byte_buf(ByteBufVisitor)?; - Ok(Self::try_from(b.as_slice()).map_err(|e| Error::custom(e.to_string()))?) + deserializer.deserialize_byte_buf(ByteBufVisitor) } } } diff --git a/src/serde/mod.rs b/src/serde/mod.rs index cf2ce38..80d3703 100644 --- a/src/serde/mod.rs +++ b/src/serde/mod.rs @@ -11,14 +11,6 @@ mod tests { use multi_trait::Null; use serde_test::{Configure, Token, assert_tokens}; - /// Serialize a value to CBOR bytes using `ciborium` (replaces the - /// unmaintained `serde_cbor` dev-dependency). - fn cbor_to_vec(value: &T) -> Vec { - let mut buf = Vec::new(); - ciborium::into_writer(value, &mut buf).expect("CBOR serialize"); - buf - } - #[test] fn test_ed25519_serde_compact() { let ms = Builder::new(Codec::Eddsa) @@ -101,8 +93,8 @@ mod tests { .with_signature_bytes(&[0u8; 64]) .try_build() .unwrap(); - let v = cbor_to_vec(&ms1); - let ms2: Multisig = ciborium::from_reader(v.as_slice()).unwrap(); + let v = serde_cbor_2::to_vec(&ms1).unwrap(); + let ms2: Multisig = serde_cbor_2::from_slice(&v).unwrap(); assert_eq!(ms1, ms2); } @@ -188,11 +180,12 @@ mod tests { .with_signature_bytes(&[0u8; 64]) .try_build() .unwrap(); - let v = cbor_to_vec(&ms1); - let ms2: Multisig = ciborium::from_reader(v.as_slice()).unwrap(); + let v = serde_cbor_2::to_vec(&ms1).unwrap(); + let ms2: Multisig = serde_cbor_2::from_slice(&v).unwrap(); assert_eq!(ms1, ms2); } + #[cfg(feature = "bls12-381")] #[test] fn test_bls12381g1_serde_compact() { /* @@ -268,6 +261,7 @@ mod tests { ) } + #[cfg(feature = "bls12-381")] #[test] fn test_bls12381g1_serde_json() { let ms1 = Builder::new(Codec::Bls12381G1Msig) @@ -279,17 +273,19 @@ mod tests { assert_eq!(ms1, ms2); } + #[cfg(feature = "bls12-381")] #[test] fn test_bls12381g1_serde_cbor() { let ms1 = Builder::new(Codec::Bls12381G1Msig) .with_signature_bytes(&[0u8; 64]) .try_build() .unwrap(); - let v = cbor_to_vec(&ms1); - let ms2: Multisig = ciborium::from_reader(v.as_slice()).unwrap(); + let v = serde_cbor_2::to_vec(&ms1).unwrap(); + let ms2: Multisig = serde_cbor_2::from_slice(&v).unwrap(); assert_eq!(ms1, ms2); } + #[cfg(feature = "bls12-381")] #[test] fn test_bls12381g1_share_serde_compact() { let ms = Builder::new(Codec::Bls12381G1Msig) @@ -412,8 +408,8 @@ mod tests { .unwrap() .to_inner(); - let v = cbor_to_vec(&ms1); - let ms2: Multisig = ciborium::from_reader(v.as_slice()).unwrap(); + let v = serde_cbor_2::to_vec(&ms1).unwrap(); + let ms2: Multisig = serde_cbor_2::from_slice(&v).unwrap(); assert_eq!(ms1, ms2); } @@ -450,4 +446,36 @@ mod tests { let ms: EncodedMultisig = Multisig::null().into(); assert_tokens(&ms.readable(), &[Token::BorrowedStr("fb924000000")]); } + + /// `AttrId` deserializes from every string token (serde forwards + /// borrowed and owned strings to `visit_str`) and from its `u8` code + #[test] + fn test_attrid_deserialize_all_token_forms() { + use crate::AttrId; + use serde::{ + Deserialize, + de::IntoDeserializer, + de::value::{BorrowedStrDeserializer, Error, StrDeserializer, StringDeserializer}, + }; + let from_str = AttrId::deserialize(StrDeserializer::::new("sig-data")); + assert!(from_str.ok() == Some(AttrId::SigData)); + let from_borrowed = AttrId::deserialize(BorrowedStrDeserializer::::new("sig-data")); + assert!(from_borrowed.ok() == Some(AttrId::SigData)); + let from_string = + AttrId::deserialize(StringDeserializer::::new("sig-data".to_string())); + assert!(from_string.ok() == Some(AttrId::SigData)); + let from_u8 = AttrId::deserialize(IntoDeserializer::::into_deserializer(11u8)); + assert!(from_u8.ok() == Some(AttrId::Depth)); + } + + /// an unknown `AttrId` name or code surfaces the crate error message + #[test] + fn test_attrid_deserialize_errors() { + use crate::AttrId; + use serde_test::assert_de_tokens_error; + let name_err = AttrId::try_from("bogus").err().unwrap().to_string(); + assert_de_tokens_error::(&[Token::String("bogus")], &name_err); + let code_err = AttrId::try_from(255u8).err().unwrap().to_string(); + assert_de_tokens_error::(&[Token::U8(255)], &code_err); + } } diff --git a/src/serde/ser.rs b/src/serde/ser.rs index 752f366..d457786 100644 --- a/src/serde/ser.rs +++ b/src/serde/ser.rs @@ -42,7 +42,7 @@ impl ser::Serialize for Multisig { ss.serialize_field("attributes", &attributes)?; ss.end() } else { - let v: Vec = self.clone().into(); + let v: Vec = self.into(); serializer.serialize_bytes(v.as_slice()) } } diff --git a/src/views.rs b/src/views.rs index ba65f66..a7fdaf0 100644 --- a/src/views.rs +++ b/src/views.rs @@ -1,19 +1,17 @@ // SPDX-License-Identifier: Apache-2.0 -//! Views over a [`Multisig`](crate::Multisig): abstract, algorithm-specific -//! interfaces over the attributes of a signature. The per-codec modules -//! implement the six view traits. The -//! [`threshold_meta`](crate::views::threshold_meta) module holds the -//! disclosure modes and the encrypted threshold metadata helpers. +//! Views over a [`Multisig`]: abstract, algorithm-specific interfaces over +//! the attributes of a signature. The per-codec modules implement the six +//! view traits. The [`threshold_meta`] module holds the disclosure modes and +//! the encrypted threshold metadata helpers. //! -//! Construct views with -//! [`ViewBuilder`](crate::views::builder::ViewBuilder): a fluent kind -//! selector plus optional local-codec factories for custom signature -//! schemes. The deprecated [`Views`] trait delegates to the same internal -//! dispatch core the builder uses. +//! Construct views with [`ViewBuilder`](crate::views::builder::ViewBuilder): +//! a fluent kind selector plus optional local-codec factories for custom +//! signature schemes. use crate::{Error, Multisig}; use multi_codec::Codec; /// BLS12 381 G1/G2 signature implementation +#[cfg(feature = "bls12-381")] pub mod bls12381; /// Builder-pattern construction of the view types pub mod builder; @@ -49,9 +47,10 @@ pub mod slh_dsa; pub mod threshold_meta; pub use threshold_meta::{ DisclosureView, MAX_THRESHOLD_PARTICIPANTS, ThresholdDisclosure, ThresholdMetaCipher, - ThresholdMetadata, decrypt_threshold_meta, disclosure_mode, encrypt_threshold_meta, - generate_meta_key, read_threshold_params, stamp_disclosure_attrs, + ThresholdMetadata, disclosure_mode, read_threshold_params, stamp_disclosure_attrs, }; +#[cfg(feature = "chacha20")] +pub use threshold_meta::{decrypt_threshold_meta, encrypt_threshold_meta, generate_meta_key}; /// XMSS-SHA2_10/16/20_256 stateful hash-based signature implementation; RFC 8391 #[cfg(feature = "xmss")] pub mod xmss; @@ -133,30 +132,3 @@ pub trait ThresholdDisclosureView { current_meta_key: Option<&[u8]>, ) -> Result; } - -/// trait for getting the other views -/// -/// Deprecated: construct views with [`ViewBuilder`](builder::ViewBuilder) -/// instead. This trait and its impl for `Multisig` remain as a -/// source-compatible delegating shim. -/// -/// Note: `multi_key::Views` is a different, unrelated trait; this -/// deprecation does not affect it. -#[deprecated( - since = "1.5.0", - note = "use ViewBuilder; this trait will be removed in 2.0.0. multi_key::Views is a different, unrelated trait" -)] -pub trait Views { - /// Provide a read-only view to access the signature attributes - fn attr_view<'a>(&'a self) -> Result, Error>; - /// Provide a read-only view to access signature data - fn data_view<'a>(&'a self) -> Result, Error>; - /// Provide a view for converting to other signature formats - fn conv_view<'a>(&'a self) -> Result, Error>; - /// Provide a read-only view to access the threshold signature attributes - fn threshold_attr_view<'a>(&'a self) -> Result, Error>; - /// Provide the view for adding a share to a multisig - fn threshold_view<'a>(&'a self) -> Result, Error>; - /// Provide an interface for threshold disclosure mode operations - fn disclosure_view<'a>(&'a self) -> Result, Error>; -} diff --git a/src/views/bls12381.rs b/src/views/bls12381.rs index 430d1b2..3c38c3b 100644 --- a/src/views/bls12381.rs +++ b/src/views/bls12381.rs @@ -1,4 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 +use crate::ms::encode_varbytes_into; use crate::{ AttrId, AttrView, Builder, ConvView, DataView, Error, Multisig, ThresholdAttrView, ThresholdView, @@ -148,10 +149,10 @@ impl<'a> TryDecodeFrom<'a> for SchemeTypeId { } } -impl TryFrom<&str> for SchemeTypeId { - type Error = Error; +impl std::str::FromStr for SchemeTypeId { + type Err = Error; - fn try_from(s: &str) -> Result { + fn from_str(s: &str) -> Result { match s.to_ascii_lowercase().as_str() { "basic" => Ok(Self::Basic), "message-augmentation" => Ok(Self::MessageAugmentation), @@ -161,6 +162,14 @@ impl TryFrom<&str> for SchemeTypeId { } } +impl TryFrom<&str> for SchemeTypeId { + type Error = Error; + + fn try_from(s: &str) -> Result { + s.parse() + } +} + impl fmt::Display for SchemeTypeId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.as_str()) @@ -182,7 +191,7 @@ impl From for Vec { // add in the signature type id v.append(&mut val.0.into()); // add in the signature bytes - v.append(&mut Varbytes::new(val.1.clone()).into()); + encode_varbytes_into(&mut v, &val.1); v } } @@ -235,7 +244,7 @@ impl From for Vec { // add in the share type id v.append(&mut val.3.into()); // add in the share data - v.append(&mut Varbytes::new(val.4.clone()).into()); + encode_varbytes_into(&mut v, &val.4); v } } @@ -301,8 +310,8 @@ impl From for Vec { // add in the number of sig shares v.append(&mut Varuint(val.0.len()).into()); // add in the sig shares - val.0.iter().for_each(|(_, share)| { - v.append(&mut share.clone().into()); + val.0.into_values().for_each(|share| { + v.append(&mut share.into()); }); v } @@ -1022,3 +1031,26 @@ impl<'a> ThresholdView for View<'a> { } } } + +#[cfg(test)] +mod scheme_type_id_tests { + use super::*; + + /// every scheme name parses back to its id through `FromStr` and the + /// delegating `TryFrom<&str>`, and an unknown name is rejected + #[test] + fn test_from_str_round_trip() { + for id in [ + SchemeTypeId::Basic, + SchemeTypeId::MessageAugmentation, + SchemeTypeId::ProofOfPossession, + ] { + assert!(id.as_str().parse::().unwrap() == id, "{id}"); + assert!(SchemeTypeId::try_from(id.as_str()).unwrap() == id, "{id}"); + } + assert!(matches!( + "no-such-scheme".parse::(), + Err(Error::Shares(SharesError::InvalidShareTypeName(_))) + )); + } +} diff --git a/src/views/builder.rs b/src/views/builder.rs index 18d2ecc..0805f2a 100644 --- a/src/views/builder.rs +++ b/src/views/builder.rs @@ -1,11 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 //! Builder-pattern construction of the read-only [`Multisig`] view types. //! -//! [`ViewBuilder`](crate::views::builder::ViewBuilder) replaces direct trait-method view access with a fluent +//! [`ViewBuilder`] replaces direct trait-method view access with a fluent //! shape. It serves two purposes: //! -//! 1. Standard codecs reach their built-in views through the same dispatch -//! core that backs the `Views` extension trait. +//! 1. Standard codecs reach their built-in views through the crate's +//! dispatch core. //! 2. Signature schemes that the crate does not standardize yet carry a codec //! outside [`SIG_CODECS`](crate::SIG_CODECS) and reach their views through //! caller-supplied local-codec factories (issue #3). @@ -54,7 +54,7 @@ //! # Dispatch order //! //! `build` consults the built-in codec dispatch first. Only when it reports -//! [`AttributesError::UnsupportedCodec`](crate::error::AttributesError::UnsupportedCodec) +//! [`AttributesError::UnsupportedCodec`] //! for the codec carried by the `Multisig` is a registered local factory //! consulted. A factory registered for any other codec is ignored and the //! original error propagates. A built-in view is therefore never overridden @@ -124,11 +124,11 @@ //! # Cross-crate alignment //! //! `multi_key::ViewBuilder` carries the same fluent-selector shape for the -//! companion `multi-key` crate; `multi_key::Views` is a separate, unrelated -//! trait. This module also records the documented deviation from the issue -//! #3 callback sketch: this crate has six view traits and no single `View` -//! trait, so the type-safe realization of the callback capability is a -//! per-kind fluent selector plus a per-kind typed factory. +//! companion `multi-key` crate. This module also records the documented +//! deviation from the issue #3 callback sketch: this crate has six view +//! traits and no single `View` trait, so the type-safe realization of the +//! callback capability is a per-kind fluent selector plus a per-kind typed +//! factory. use crate::{ AttrView, ConvView, DataView, Error, Multisig, ThresholdAttrView, ThresholdDisclosureView, @@ -631,6 +631,7 @@ mod tests { } } + #[cfg(feature = "bls12-381")] #[test] fn test_representative_kinds_build() { let ms = Builder::new(Codec::EddsaMsig) diff --git a/src/views/dispatch.rs b/src/views/dispatch.rs index 9eba5d4..22affab 100644 --- a/src/views/dispatch.rs +++ b/src/views/dispatch.rs @@ -6,6 +6,8 @@ //! its built-in view and reports `AttributesError::UnsupportedCodec` with that //! codec on fallthrough. +#[cfg(feature = "bls12-381")] +use crate::views::bls12381; #[cfg(feature = "xmss")] use crate::views::xmss; #[cfg(feature = "lamport")] @@ -15,8 +17,8 @@ use crate::{ ThresholdView, error::AttributesError, views::{ - DisclosureView, bls12381, ed25519, ed25519_hybrid, ed25519_mayo2, fn_dsa, mayo, ml_dsa, - nist_p, rsa, secp256k1, slh_dsa, + DisclosureView, ed25519, ed25519_hybrid, ed25519_mayo2, fn_dsa, mayo, ml_dsa, nist_p, rsa, + secp256k1, slh_dsa, }, }; use multi_codec::Codec; @@ -27,6 +29,7 @@ use multi_codec::Codec; /// `ms` when no built-in view supports the codec. pub(crate) fn dispatch_attr_view(ms: &Multisig) -> Result, Error> { match ms.codec { + #[cfg(feature = "bls12-381")] Codec::Bls12381G1Msig | Codec::Bls12381G2Msig | Codec::Bls12381G1ShareMsig @@ -121,6 +124,7 @@ pub(crate) fn dispatch_attr_view(ms: &Multisig) -> Result /// `ms` when no built-in view supports the codec. pub(crate) fn dispatch_data_view(ms: &Multisig) -> Result, Error> { match ms.codec { + #[cfg(feature = "bls12-381")] Codec::Bls12381G1Msig | Codec::Bls12381G2Msig | Codec::Bls12381G1ShareMsig @@ -215,6 +219,7 @@ pub(crate) fn dispatch_data_view(ms: &Multisig) -> Result /// `ms` when no built-in view supports the codec. pub(crate) fn dispatch_conv_view(ms: &Multisig) -> Result, Error> { match ms.codec { + #[cfg(feature = "bls12-381")] Codec::Bls12381G1Msig | Codec::Bls12381G2Msig | Codec::Bls12381G1ShareMsig @@ -312,6 +317,7 @@ pub(crate) fn dispatch_threshold_attr_view( ms: &Multisig, ) -> Result, Error> { match ms.codec { + #[cfg(feature = "bls12-381")] Codec::Bls12381G1Msig | Codec::Bls12381G2Msig | Codec::Bls12381G1ShareMsig @@ -373,6 +379,7 @@ pub(crate) fn dispatch_threshold_attr_view( /// `AttributesError::UnsupportedCodec` with the codec carried by `ms`. pub(crate) fn dispatch_threshold_view(ms: &Multisig) -> Result, Error> { match ms.codec { + #[cfg(feature = "bls12-381")] Codec::Bls12381G1Msig | Codec::Bls12381G2Msig => { Ok(Box::new(bls12381::View::try_from(ms)?)) } @@ -428,9 +435,8 @@ pub(crate) fn dispatch_threshold_view(ms: &Multisig) -> Result::combine`. +use crate::ms::encode_varbytes_into; use crate::{ AttrId, AttrView, Builder, ConvView, DataView, Error, Multisig, ThresholdAttrView, ThresholdView, @@ -121,7 +122,7 @@ fn combine_blobs(codec: Codec, blobs: &[Vec]) -> Result, Error> { fn encode_shares(blobs: &[Vec]) -> Vec { let mut out: Vec = Varuint(blobs.len()).into(); for blob in blobs { - out.append(&mut Varbytes::new(blob.clone()).into()); + encode_varbytes_into(&mut out, blob); } out } diff --git a/src/views/lamport_merkle.rs b/src/views/lamport_merkle.rs index a6441ac..fff604f 100644 --- a/src/views/lamport_merkle.rs +++ b/src/views/lamport_merkle.rs @@ -12,6 +12,7 @@ //! `depth` attribute (one raw byte), cross-checked against the depth byte at //! offset 0 of each `MtSignatureShare` blob. +use crate::ms::encode_varbytes_into; use crate::{ AttrId, AttrView, Builder, ConvView, DataView, Error, Multisig, ThresholdAttrView, ThresholdView, @@ -141,7 +142,7 @@ fn combine_blobs(codec: Codec, blobs: &[Vec]) -> Result<(Vec, u8), Error fn encode_shares(blobs: &[Vec]) -> Vec { let mut out: Vec = Varuint(blobs.len()).into(); for blob in blobs { - out.append(&mut Varbytes::new(blob.clone()).into()); + encode_varbytes_into(&mut out, blob); } out } diff --git a/src/views/threshold_meta.rs b/src/views/threshold_meta.rs index 8ce6b12..3f7f2ba 100644 --- a/src/views/threshold_meta.rs +++ b/src/views/threshold_meta.rs @@ -14,9 +14,10 @@ //! //! - **[`ThresholdDisclosure::Full`]** — t and n are plaintext attributes (default). //! - **[`ThresholdDisclosure::Partial`]** — n is plaintext, t is encrypted. -//! - **[`ThresholdDisclosure::FullConfidentialial`]** — both t and n are encrypted. +//! - **[`ThresholdDisclosure::FullConfidential`]** — both t and n are encrypted. use crate::{AttrId, Error, Multisig}; +#[cfg(feature = "chacha20")] use chacha20poly1305::{ ChaCha20Poly1305, Nonce, aead::{Aead, KeyInit, Payload}, @@ -25,6 +26,7 @@ use multi_codec::Codec; use multi_trait::{EncodeInto, TryDecodeFrom}; use multi_util::Varuint; use serde::{Deserialize, Serialize}; +#[cfg(feature = "chacha20")] use zeroize::Zeroizing; /// Maximum number of threshold participants (t or n) accepted when decoding @@ -44,7 +46,7 @@ pub enum ThresholdDisclosure { /// n is plaintext, t is encrypted (auditable n, hidden t). Partial = 1, /// Both t and n are encrypted. - FullConfidentialial = 2, + FullConfidential = 2, } impl ThresholdDisclosure { @@ -54,7 +56,7 @@ impl ThresholdDisclosure { match self { Self::Full => "full", Self::Partial => "partial", - Self::FullConfidentialial => "full-confidentialial", + Self::FullConfidential => "full-confidential", } } } @@ -78,7 +80,7 @@ impl TryFrom for ThresholdDisclosure { match code { 0 => Ok(Self::Full), 1 => Ok(Self::Partial), - 2 => Ok(Self::FullConfidentialial), + 2 => Ok(Self::FullConfidential), _ => Err(Error::Shares(crate::error::SharesError::MetaEncryption( format!("invalid disclosure mode: {code}"), ))), @@ -152,18 +154,16 @@ impl ThresholdMetadata { /// Encode to CBOR bytes. pub fn to_cbor_bytes(&self) -> Result, Error> { - let mut buf = Vec::new(); - ciborium::into_writer(self, &mut buf).map_err(|e| { + serde_cbor_2::to_vec(self).map_err(|e| { Error::Shares(crate::error::SharesError::MetaEncryption(format!( "CBOR encode: {e}" ))) - })?; - Ok(buf) + }) } /// Decode from CBOR bytes. pub fn from_cbor_bytes(bytes: &[u8]) -> Result { - ciborium::from_reader(bytes).map_err(|e| { + serde_cbor_2::from_slice(bytes).map_err(|e| { Error::Shares(crate::error::SharesError::MetaEncryption(format!( "CBOR decode: {e}" ))) @@ -201,18 +201,16 @@ impl ThresholdMetaCipher { /// Encode to CBOR bytes. pub fn to_cbor_bytes(&self) -> Result, Error> { - let mut buf = Vec::new(); - ciborium::into_writer(self, &mut buf).map_err(|e| { + serde_cbor_2::to_vec(self).map_err(|e| { Error::Shares(crate::error::SharesError::MetaEncryption(format!( "CBOR encode cipher: {e}" ))) - })?; - Ok(buf) + }) } /// Decode from CBOR bytes. pub fn from_cbor_bytes(bytes: &[u8]) -> Result { - ciborium::from_reader(bytes).map_err(|e| { + serde_cbor_2::from_slice(bytes).map_err(|e| { Error::Shares(crate::error::SharesError::MetaEncryption(format!( "CBOR decode cipher: {e}" ))) @@ -224,6 +222,7 @@ impl ThresholdMetaCipher { /// /// `key` must be 32 bytes. A random nonce is generated and returned in the /// [`ThresholdMetaCipher`]. +#[cfg(feature = "chacha20")] #[allow(deprecated)] pub fn encrypt_threshold_meta( meta: &ThresholdMetadata, @@ -269,6 +268,7 @@ pub fn encrypt_threshold_meta( } /// Decrypt threshold metadata using ChaCha20-Poly1305 AEAD. +#[cfg(feature = "chacha20")] #[allow(deprecated)] pub fn decrypt_threshold_meta( encrypted: &[u8], @@ -313,12 +313,39 @@ pub fn decrypt_threshold_meta( } /// Generate a random 32-byte ChaCha20-Poly1305 key. +#[cfg(feature = "chacha20")] pub fn generate_meta_key() -> Zeroizing> { let mut key = Zeroizing::new(vec![0u8; 32]); getrandom::fill(key.as_mut_slice()).expect("getrandom failure during meta key generation"); key } +/// Fallback without the `chacha20` feature: no AEAD is compiled in, so the +/// partial and fully confidential disclosure modes fail instead of writing +/// threshold metadata. +#[cfg(not(feature = "chacha20"))] +fn encrypt_threshold_meta( + _meta: &ThresholdMetadata, + _key: &[u8], +) -> Result<(Vec, ThresholdMetaCipher), Error> { + Err(Error::Shares(crate::error::SharesError::MetaEncryption( + "threshold metadata encryption needs the `chacha20` feature".to_string(), + ))) +} + +/// Fallback without the `chacha20` feature: no AEAD is compiled in, so +/// encrypted threshold metadata cannot be read. +#[cfg(not(feature = "chacha20"))] +fn decrypt_threshold_meta( + _encrypted: &[u8], + _cipher_info: &ThresholdMetaCipher, + _key: &[u8], +) -> Result { + Err(Error::Shares(crate::error::SharesError::MetaEncryption( + "threshold metadata decryption needs the `chacha20` feature".to_string(), + ))) +} + /// Read the disclosure mode from a Multisig. Returns Full if no attribute is present. pub fn disclosure_mode(ms: &Multisig) -> Result { match ms.attributes.get(&AttrId::ThresholdDisclosure) { @@ -335,7 +362,7 @@ pub fn disclosure_mode(ms: &Multisig) -> Result { /// Read t and n from a Multisig, decrypting if necessary. /// /// `meta_key` is the raw 32-byte symmetric key (extracted from a `Multikey` by -/// the caller); it is required for Partial/FullConfidentialial modes. +/// the caller); it is required for Partial/FullConfidential modes. pub fn read_threshold_params( ms: &Multisig, meta_key: Option<&[u8]>, @@ -395,7 +422,7 @@ pub fn read_threshold_params( ))? as usize; Ok((t, n)) } - ThresholdDisclosure::FullConfidentialial => { + ThresholdDisclosure::FullConfidential => { let encrypted = ms.attributes.get(&AttrId::EncryptedThresholdMeta).ok_or( crate::error::SharesError::MetaEncryption( "missing EncryptedThresholdMeta".to_string(), @@ -432,7 +459,7 @@ pub fn read_threshold_params( /// Stamp disclosure attributes onto a Multisig's attribute map. /// /// `meta_key` is the raw 32-byte symmetric key (extracted from a `Multikey` by -/// the caller); required for Partial/FullConfidentialial modes. +/// the caller); required for Partial/FullConfidential modes. pub fn stamp_disclosure_attrs( attributes: &mut std::collections::BTreeMap>, mode: ThresholdDisclosure, @@ -474,7 +501,7 @@ pub fn stamp_disclosure_attrs( ); attributes.insert(AttrId::ThresholdDisclosure, mode.encode_into()); } - ThresholdDisclosure::FullConfidentialial => { + ThresholdDisclosure::FullConfidential => { let meta_key = meta_key.ok_or(SharesError::MissingMetaKey)?; let meta = ThresholdMetadata::new(threshold as u16, limit as u16); @@ -526,3 +553,65 @@ impl<'a> crate::views::ThresholdDisclosureView for DisclosureView<'a> { Ok(new_ms) } } + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + + /// a partial-disclosure stamp encrypts t, keeps n plaintext, and reads + /// back with the same key + #[cfg(feature = "chacha20")] + #[test] + fn test_partial_disclosure_round_trip() { + let key = generate_meta_key(); + let mut attributes = BTreeMap::new(); + stamp_disclosure_attrs( + &mut attributes, + ThresholdDisclosure::Partial, + 3, + 5, + Some(key.as_slice()), + ) + .unwrap(); + assert!(!attributes.contains_key(&AttrId::Threshold)); + assert!(attributes.contains_key(&AttrId::EncryptedThresholdMeta)); + + let ms = Multisig { + codec: Codec::Bls12381G1ShareMsig, + attributes, + ..Default::default() + }; + assert_eq!( + read_threshold_params(&ms, Some(key.as_slice())).unwrap(), + (3, 5) + ); + } + + /// without the `chacha20` feature the encrypted disclosure modes fail and + /// never write the confidential threshold in plaintext + #[cfg(not(feature = "chacha20"))] + #[test] + fn test_encrypted_disclosure_needs_chacha20() { + let key = [7u8; 32]; + for mode in [ + ThresholdDisclosure::Partial, + ThresholdDisclosure::FullConfidential, + ] { + let mut attributes = BTreeMap::new(); + let result = stamp_disclosure_attrs(&mut attributes, mode, 3, 5, Some(&key)); + assert!( + matches!( + result, + Err(Error::Shares(crate::error::SharesError::MetaEncryption(_))) + ), + "{mode}: {result:?}" + ); + assert!(!attributes.contains_key(&AttrId::Threshold), "{mode}"); + assert!( + !attributes.contains_key(&AttrId::EncryptedThresholdMeta), + "{mode}" + ); + } + } +} diff --git a/tests/security_tests.rs b/tests/security_tests.rs index 0135208..10db09c 100644 --- a/tests/security_tests.rs +++ b/tests/security_tests.rs @@ -41,7 +41,8 @@ fn test_truncated_data() { /// Test empty bytes #[test] fn test_empty_bytes() { - let result = Multisig::try_from(&[] as &[u8]); + let empty: &[u8] = &[]; + let result = Multisig::try_from(empty); assert!(result.is_err()); }