From 59e3151812669d227f820b79eb5e58bca8af613d Mon Sep 17 00:00:00 2001 From: Dave Grantham Date: Tue, 6 Oct 2026 20:45:10 -0600 Subject: [PATCH 1/7] extract view dispatch Signed-off-by: Dave Grantham --- src/ms.rs | 403 +------------------------------------- src/views.rs | 2 + src/views/dispatch.rs | 439 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 450 insertions(+), 394 deletions(-) create mode 100644 src/views/dispatch.rs diff --git a/src/ms.rs b/src/ms.rs index 9e956dd..6dadcb9 100644 --- a/src/ms.rs +++ b/src/ms.rs @@ -1,18 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 -#[cfg(feature = "lamport")] -use crate::views::lamport; -#[cfg(feature = "lamport")] -use crate::views::lamport_merkle; -#[cfg(feature = "xmss")] -use crate::views::xmss; use crate::{ AttrId, AttrView, ConvView, DataView, Error, ThresholdAttrView, ThresholdView, Views, - error::AttributesError, views::{ - DisclosureView, ThresholdDisclosure, ThresholdDisclosureView, + ThresholdDisclosure, ThresholdDisclosureView, bls12381::{self, SchemeTypeId}, - ed25519, ed25519_hybrid, ed25519_mayo2, fn_dsa, mayo, ml_dsa, nist_p, rsa, secp256k1, - slh_dsa, threshold_meta, + dispatch, secp256k1, threshold_meta, }, }; use blsful::{ @@ -379,405 +371,28 @@ impl fmt::Debug for Multisig { impl Views for Multisig { /// Provide a read-only view to access the signature attributes fn attr_view<'a>(&'a self) -> Result, Error> { - match self.codec { - Codec::Bls12381G1Msig - | Codec::Bls12381G2Msig - | Codec::Bls12381G1ShareMsig - | Codec::Bls12381G2ShareMsig => Ok(Box::new(bls12381::View::try_from(self)?)), - Codec::EddsaMsig | Codec::XeddsaMsig => Ok(Box::new(ed25519::View::try_from(self)?)), - Codec::Es256KMsig => Ok(Box::new(secp256k1::View::try_from(self)?)), - Codec::Es256Msig | Codec::Es384Msig | Codec::Es521Msig => { - Ok(Box::new(nist_p::View::try_from(self)?)) - } - Codec::Rs256Msig => Ok(Box::new(rsa::View::try_from(self)?)), - Codec::SlhDsaSha2128FMsig - | Codec::SlhDsaSha2128SMsig - | Codec::SlhDsaSha2192FMsig - | Codec::SlhDsaSha2192SMsig - | Codec::SlhDsaSha2256FMsig - | Codec::SlhDsaSha2256SMsig - | Codec::SlhDsaShake128FMsig - | Codec::SlhDsaShake128SMsig - | Codec::SlhDsaShake192FMsig - | Codec::SlhDsaShake192SMsig - | Codec::SlhDsaShake256FMsig - | Codec::SlhDsaShake256SMsig => Ok(Box::new(slh_dsa::View::try_from(self)?)), - Codec::MlDsa65Msig | Codec::MlDsa87Msig => Ok(Box::new(ml_dsa::View::try_from(self)?)), - Codec::FnDsa512Msig | Codec::FnDsa1024Msig => { - Ok(Box::new(fn_dsa::View::try_from(self)?)) - } - Codec::Mayo1Msig | Codec::Mayo2Msig | Codec::Mayo3Msig | Codec::Mayo5Msig => { - Ok(Box::new(mayo::View::try_from(self)?)) - } - Codec::Ed25519Mayo2Msig => Ok(Box::new(ed25519_mayo2::View::try_from(self)?)), - Codec::Ed25519Mldsa65Msig - | Codec::Ed25519Fndsa512Msig - | Codec::Bls12381G1Mldsa65Msig - | Codec::Bls12381G1Fndsa512Msig - | Codec::Bls12381G1Mayo1Msig - | Codec::Bls12381G1Mayo2Msig => Ok(Box::new(ed25519_hybrid::View::try_from(self)?)), - #[cfg(feature = "lamport")] - Codec::LamportSha3256Sig - | Codec::LamportSha3384Sig - | Codec::LamportSha3512Sig - | Codec::LamportSha3256SigShare - | Codec::LamportSha3384SigShare - | Codec::LamportSha3512SigShare - | Codec::LamportSha2256Sig - | Codec::LamportSha2384Sig - | Codec::LamportSha2512Sig - | Codec::LamportSha2256SigShare - | Codec::LamportSha2384SigShare - | Codec::LamportSha2512SigShare - | Codec::LamportBlake2B512Sig - | Codec::LamportBlake2S256Sig - | Codec::LamportBlake3256Sig - | Codec::LamportBlake2B512SigShare - | Codec::LamportBlake2S256SigShare - | Codec::LamportBlake3256SigShare - | Codec::LamportShake128Sig - | Codec::LamportShake256Sig - | Codec::LamportShake128SigShare - | Codec::LamportShake256SigShare => Ok(Box::new(lamport::View::try_from(self)?)), - #[cfg(feature = "lamport")] - Codec::LamportMerkleSha3512Sig - | Codec::LamportMerkleSha3512SigShare - | Codec::LamportMerkleSha3384Sig - | Codec::LamportMerkleSha3384SigShare - | Codec::LamportMerkleSha3256Sig - | Codec::LamportMerkleSha3256SigShare - | Codec::LamportMerkleSha2512Sig - | Codec::LamportMerkleSha2512SigShare - | Codec::LamportMerkleSha2384Sig - | Codec::LamportMerkleSha2384SigShare - | Codec::LamportMerkleSha2256Sig - | Codec::LamportMerkleSha2256SigShare - | Codec::LamportMerkleBlake2B512Sig - | Codec::LamportMerkleBlake2B512SigShare - | Codec::LamportMerkleBlake2S256Sig - | Codec::LamportMerkleBlake2S256SigShare - | Codec::LamportMerkleBlake3256Sig - | Codec::LamportMerkleBlake3256SigShare - | Codec::LamportMerkleShake128Sig - | Codec::LamportMerkleShake128SigShare - | Codec::LamportMerkleShake256Sig - | Codec::LamportMerkleShake256SigShare => { - Ok(Box::new(lamport_merkle::View::try_from(self)?)) - } - #[cfg(feature = "xmss")] - Codec::XmssSha210256Msig | Codec::XmssSha216256Msig | Codec::XmssSha220256Msig => { - Ok(Box::new(xmss::View::try_from(self)?)) - } - _ => Err(AttributesError::UnsupportedCodec(self.codec).into()), - } + dispatch::dispatch_attr_view(self) } /// Provide a read-only view to access signature data fn data_view<'a>(&'a self) -> Result, Error> { - match self.codec { - Codec::Bls12381G1Msig - | Codec::Bls12381G2Msig - | Codec::Bls12381G1ShareMsig - | Codec::Bls12381G2ShareMsig => Ok(Box::new(bls12381::View::try_from(self)?)), - Codec::EddsaMsig | Codec::XeddsaMsig => Ok(Box::new(ed25519::View::try_from(self)?)), - Codec::Es256KMsig => Ok(Box::new(secp256k1::View::try_from(self)?)), - Codec::Es256Msig | Codec::Es384Msig | Codec::Es521Msig => { - Ok(Box::new(nist_p::View::try_from(self)?)) - } - Codec::Rs256Msig => Ok(Box::new(rsa::View::try_from(self)?)), - Codec::SlhDsaSha2128FMsig - | Codec::SlhDsaSha2128SMsig - | Codec::SlhDsaSha2192FMsig - | Codec::SlhDsaSha2192SMsig - | Codec::SlhDsaSha2256FMsig - | Codec::SlhDsaSha2256SMsig - | Codec::SlhDsaShake128FMsig - | Codec::SlhDsaShake128SMsig - | Codec::SlhDsaShake192FMsig - | Codec::SlhDsaShake192SMsig - | Codec::SlhDsaShake256FMsig - | Codec::SlhDsaShake256SMsig => Ok(Box::new(slh_dsa::View::try_from(self)?)), - Codec::MlDsa65Msig | Codec::MlDsa87Msig => Ok(Box::new(ml_dsa::View::try_from(self)?)), - Codec::FnDsa512Msig | Codec::FnDsa1024Msig => { - Ok(Box::new(fn_dsa::View::try_from(self)?)) - } - Codec::Mayo1Msig | Codec::Mayo2Msig | Codec::Mayo3Msig | Codec::Mayo5Msig => { - Ok(Box::new(mayo::View::try_from(self)?)) - } - Codec::Ed25519Mayo2Msig => Ok(Box::new(ed25519_mayo2::View::try_from(self)?)), - Codec::Ed25519Mldsa65Msig - | Codec::Ed25519Fndsa512Msig - | Codec::Bls12381G1Mldsa65Msig - | Codec::Bls12381G1Fndsa512Msig - | Codec::Bls12381G1Mayo1Msig - | Codec::Bls12381G1Mayo2Msig => Ok(Box::new(ed25519_hybrid::View::try_from(self)?)), - #[cfg(feature = "lamport")] - Codec::LamportSha3256Sig - | Codec::LamportSha3384Sig - | Codec::LamportSha3512Sig - | Codec::LamportSha3256SigShare - | Codec::LamportSha3384SigShare - | Codec::LamportSha3512SigShare - | Codec::LamportSha2256Sig - | Codec::LamportSha2384Sig - | Codec::LamportSha2512Sig - | Codec::LamportSha2256SigShare - | Codec::LamportSha2384SigShare - | Codec::LamportSha2512SigShare - | Codec::LamportBlake2B512Sig - | Codec::LamportBlake2S256Sig - | Codec::LamportBlake3256Sig - | Codec::LamportBlake2B512SigShare - | Codec::LamportBlake2S256SigShare - | Codec::LamportBlake3256SigShare - | Codec::LamportShake128Sig - | Codec::LamportShake256Sig - | Codec::LamportShake128SigShare - | Codec::LamportShake256SigShare => Ok(Box::new(lamport::View::try_from(self)?)), - #[cfg(feature = "lamport")] - Codec::LamportMerkleSha3512Sig - | Codec::LamportMerkleSha3512SigShare - | Codec::LamportMerkleSha3384Sig - | Codec::LamportMerkleSha3384SigShare - | Codec::LamportMerkleSha3256Sig - | Codec::LamportMerkleSha3256SigShare - | Codec::LamportMerkleSha2512Sig - | Codec::LamportMerkleSha2512SigShare - | Codec::LamportMerkleSha2384Sig - | Codec::LamportMerkleSha2384SigShare - | Codec::LamportMerkleSha2256Sig - | Codec::LamportMerkleSha2256SigShare - | Codec::LamportMerkleBlake2B512Sig - | Codec::LamportMerkleBlake2B512SigShare - | Codec::LamportMerkleBlake2S256Sig - | Codec::LamportMerkleBlake2S256SigShare - | Codec::LamportMerkleBlake3256Sig - | Codec::LamportMerkleBlake3256SigShare - | Codec::LamportMerkleShake128Sig - | Codec::LamportMerkleShake128SigShare - | Codec::LamportMerkleShake256Sig - | Codec::LamportMerkleShake256SigShare => { - Ok(Box::new(lamport_merkle::View::try_from(self)?)) - } - #[cfg(feature = "xmss")] - Codec::XmssSha210256Msig | Codec::XmssSha216256Msig | Codec::XmssSha220256Msig => { - Ok(Box::new(xmss::View::try_from(self)?)) - } - _ => Err(AttributesError::UnsupportedCodec(self.codec).into()), - } + dispatch::dispatch_data_view(self) } - /// Provide a read-only view to access signature data + /// Provide a view for converting to other signature formats fn conv_view<'a>(&'a self) -> Result, Error> { - match self.codec { - Codec::Bls12381G1Msig - | Codec::Bls12381G2Msig - | Codec::Bls12381G1ShareMsig - | Codec::Bls12381G2ShareMsig => Ok(Box::new(bls12381::View::try_from(self)?)), - Codec::EddsaMsig | Codec::XeddsaMsig => Ok(Box::new(ed25519::View::try_from(self)?)), - Codec::Es256KMsig => Ok(Box::new(secp256k1::View::try_from(self)?)), - Codec::Es256Msig | Codec::Es384Msig | Codec::Es521Msig => { - Ok(Box::new(nist_p::View::try_from(self)?)) - } - Codec::Rs256Msig => Ok(Box::new(rsa::View::try_from(self)?)), - Codec::SlhDsaSha2128FMsig - | Codec::SlhDsaSha2128SMsig - | Codec::SlhDsaSha2192FMsig - | Codec::SlhDsaSha2192SMsig - | Codec::SlhDsaSha2256FMsig - | Codec::SlhDsaSha2256SMsig - | Codec::SlhDsaShake128FMsig - | Codec::SlhDsaShake128SMsig - | Codec::SlhDsaShake192FMsig - | Codec::SlhDsaShake192SMsig - | Codec::SlhDsaShake256FMsig - | Codec::SlhDsaShake256SMsig => Ok(Box::new(slh_dsa::View::try_from(self)?)), - Codec::MlDsa65Msig | Codec::MlDsa87Msig => Ok(Box::new(ml_dsa::View::try_from(self)?)), - Codec::FnDsa512Msig | Codec::FnDsa1024Msig => { - Ok(Box::new(fn_dsa::View::try_from(self)?)) - } - Codec::Mayo1Msig | Codec::Mayo2Msig | Codec::Mayo3Msig | Codec::Mayo5Msig => { - Ok(Box::new(mayo::View::try_from(self)?)) - } - Codec::Ed25519Mayo2Msig => Ok(Box::new(ed25519_mayo2::View::try_from(self)?)), - Codec::Ed25519Mldsa65Msig - | Codec::Ed25519Fndsa512Msig - | Codec::Bls12381G1Mldsa65Msig - | Codec::Bls12381G1Fndsa512Msig - | Codec::Bls12381G1Mayo1Msig - | Codec::Bls12381G1Mayo2Msig => Ok(Box::new(ed25519_hybrid::View::try_from(self)?)), - #[cfg(feature = "lamport")] - Codec::LamportSha3256Sig - | Codec::LamportSha3384Sig - | Codec::LamportSha3512Sig - | Codec::LamportSha3256SigShare - | Codec::LamportSha3384SigShare - | Codec::LamportSha3512SigShare - | Codec::LamportSha2256Sig - | Codec::LamportSha2384Sig - | Codec::LamportSha2512Sig - | Codec::LamportSha2256SigShare - | Codec::LamportSha2384SigShare - | Codec::LamportSha2512SigShare - | Codec::LamportBlake2B512Sig - | Codec::LamportBlake2S256Sig - | Codec::LamportBlake3256Sig - | Codec::LamportBlake2B512SigShare - | Codec::LamportBlake2S256SigShare - | Codec::LamportBlake3256SigShare - | Codec::LamportShake128Sig - | Codec::LamportShake256Sig - | Codec::LamportShake128SigShare - | Codec::LamportShake256SigShare => Ok(Box::new(lamport::View::try_from(self)?)), - #[cfg(feature = "lamport")] - Codec::LamportMerkleSha3512Sig - | Codec::LamportMerkleSha3512SigShare - | Codec::LamportMerkleSha3384Sig - | Codec::LamportMerkleSha3384SigShare - | Codec::LamportMerkleSha3256Sig - | Codec::LamportMerkleSha3256SigShare - | Codec::LamportMerkleSha2512Sig - | Codec::LamportMerkleSha2512SigShare - | Codec::LamportMerkleSha2384Sig - | Codec::LamportMerkleSha2384SigShare - | Codec::LamportMerkleSha2256Sig - | Codec::LamportMerkleSha2256SigShare - | Codec::LamportMerkleBlake2B512Sig - | Codec::LamportMerkleBlake2B512SigShare - | Codec::LamportMerkleBlake2S256Sig - | Codec::LamportMerkleBlake2S256SigShare - | Codec::LamportMerkleBlake3256Sig - | Codec::LamportMerkleBlake3256SigShare - | Codec::LamportMerkleShake128Sig - | Codec::LamportMerkleShake128SigShare - | Codec::LamportMerkleShake256Sig - | Codec::LamportMerkleShake256SigShare => { - Ok(Box::new(lamport_merkle::View::try_from(self)?)) - } - #[cfg(feature = "xmss")] - Codec::XmssSha210256Msig | Codec::XmssSha216256Msig | Codec::XmssSha220256Msig => { - Ok(Box::new(xmss::View::try_from(self)?)) - } - _ => Err(AttributesError::UnsupportedCodec(self.codec).into()), - } + 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> { - match self.codec { - Codec::Bls12381G1Msig - | Codec::Bls12381G2Msig - | Codec::Bls12381G1ShareMsig - | Codec::Bls12381G2ShareMsig => Ok(Box::new(bls12381::View::try_from(self)?)), - #[cfg(feature = "lamport")] - Codec::LamportSha3256Sig - | Codec::LamportSha3256SigShare - | Codec::LamportSha3384Sig - | Codec::LamportSha3384SigShare - | Codec::LamportSha3512Sig - | Codec::LamportSha3512SigShare - | Codec::LamportSha2256Sig - | Codec::LamportSha2256SigShare - | Codec::LamportSha2384Sig - | Codec::LamportSha2384SigShare - | Codec::LamportSha2512Sig - | Codec::LamportSha2512SigShare - | Codec::LamportBlake2B512Sig - | Codec::LamportBlake2B512SigShare - | Codec::LamportBlake2S256Sig - | Codec::LamportBlake2S256SigShare - | Codec::LamportBlake3256Sig - | Codec::LamportBlake3256SigShare - | Codec::LamportShake128Sig - | Codec::LamportShake128SigShare - | Codec::LamportShake256Sig - | Codec::LamportShake256SigShare => Ok(Box::new(lamport::View::try_from(self)?)), - #[cfg(feature = "lamport")] - Codec::LamportMerkleSha3512Sig - | Codec::LamportMerkleSha3512SigShare - | Codec::LamportMerkleSha3384Sig - | Codec::LamportMerkleSha3384SigShare - | Codec::LamportMerkleSha3256Sig - | Codec::LamportMerkleSha3256SigShare - | Codec::LamportMerkleSha2512Sig - | Codec::LamportMerkleSha2512SigShare - | Codec::LamportMerkleSha2384Sig - | Codec::LamportMerkleSha2384SigShare - | Codec::LamportMerkleSha2256Sig - | Codec::LamportMerkleSha2256SigShare - | Codec::LamportMerkleBlake2B512Sig - | Codec::LamportMerkleBlake2B512SigShare - | Codec::LamportMerkleBlake2S256Sig - | Codec::LamportMerkleBlake2S256SigShare - | Codec::LamportMerkleBlake3256Sig - | Codec::LamportMerkleBlake3256SigShare - | Codec::LamportMerkleShake128Sig - | Codec::LamportMerkleShake128SigShare - | Codec::LamportMerkleShake256Sig - | Codec::LamportMerkleShake256SigShare => { - Ok(Box::new(lamport_merkle::View::try_from(self)?)) - } - _ => Err(AttributesError::UnsupportedCodec(self.codec).into()), - } + dispatch::dispatch_threshold_attr_view(self) } /// Provide the view for adding a share to a multisig fn threshold_view<'a>(&'a self) -> Result, Error> { - match self.codec { - Codec::Bls12381G1Msig | Codec::Bls12381G2Msig => { - Ok(Box::new(bls12381::View::try_from(self)?)) - } - #[cfg(feature = "lamport")] - Codec::LamportSha3256Sig - | Codec::LamportSha3256SigShare - | Codec::LamportSha3384Sig - | Codec::LamportSha3384SigShare - | Codec::LamportSha3512Sig - | Codec::LamportSha3512SigShare - | Codec::LamportSha2256Sig - | Codec::LamportSha2256SigShare - | Codec::LamportSha2384Sig - | Codec::LamportSha2384SigShare - | Codec::LamportSha2512Sig - | Codec::LamportSha2512SigShare - | Codec::LamportBlake2B512Sig - | Codec::LamportBlake2B512SigShare - | Codec::LamportBlake2S256Sig - | Codec::LamportBlake2S256SigShare - | Codec::LamportBlake3256Sig - | Codec::LamportBlake3256SigShare - | Codec::LamportShake128Sig - | Codec::LamportShake128SigShare - | Codec::LamportShake256Sig - | Codec::LamportShake256SigShare => Ok(Box::new(lamport::View::try_from(self)?)), - #[cfg(feature = "lamport")] - Codec::LamportMerkleSha3512Sig - | Codec::LamportMerkleSha3512SigShare - | Codec::LamportMerkleSha3384Sig - | Codec::LamportMerkleSha3384SigShare - | Codec::LamportMerkleSha3256Sig - | Codec::LamportMerkleSha3256SigShare - | Codec::LamportMerkleSha2512Sig - | Codec::LamportMerkleSha2512SigShare - | Codec::LamportMerkleSha2384Sig - | Codec::LamportMerkleSha2384SigShare - | Codec::LamportMerkleSha2256Sig - | Codec::LamportMerkleSha2256SigShare - | Codec::LamportMerkleBlake2B512Sig - | Codec::LamportMerkleBlake2B512SigShare - | Codec::LamportMerkleBlake2S256Sig - | Codec::LamportMerkleBlake2S256SigShare - | Codec::LamportMerkleBlake3256Sig - | Codec::LamportMerkleBlake3256SigShare - | Codec::LamportMerkleShake128Sig - | Codec::LamportMerkleShake128SigShare - | Codec::LamportMerkleShake256Sig - | Codec::LamportMerkleShake256SigShare => { - Ok(Box::new(lamport_merkle::View::try_from(self)?)) - } - _ => Err(AttributesError::UnsupportedCodec(self.codec).into()), - } + dispatch::dispatch_threshold_view(self) } /// Provide an interface for threshold disclosure mode operations fn disclosure_view<'a>(&'a self) -> Result, Error> { - Ok(Box::new(DisclosureView::new(self))) + dispatch::dispatch_disclosure_view(self) } } diff --git a/src/views.rs b/src/views.rs index 8837cc7..2c826b4 100644 --- a/src/views.rs +++ b/src/views.rs @@ -4,6 +4,8 @@ use multi_codec::Codec; /// BLS12 381 G1/G2 signature implementation pub mod bls12381; +/// Crate-internal per-codec view dispatch shared by view entry points +pub(crate) mod dispatch; /// Edwards curve 25519 signature implementation pub mod ed25519; /// Generic Ed25519 hybrid signature view (codec-agnostic holder) diff --git a/src/views/dispatch.rs b/src/views/dispatch.rs new file mode 100644 index 0000000..9eba5d4 --- /dev/null +++ b/src/views/dispatch.rs @@ -0,0 +1,439 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Crate-internal view dispatch for `Multisig`. +//! +//! Every per-codec view table lives here so that all view entry points share +//! one implementation. Each function maps the codec carried by the multisig to +//! its built-in view and reports `AttributesError::UnsupportedCodec` with that +//! codec on fallthrough. + +#[cfg(feature = "xmss")] +use crate::views::xmss; +#[cfg(feature = "lamport")] +use crate::views::{lamport, lamport_merkle}; +use crate::{ + AttrView, ConvView, DataView, Error, Multisig, ThresholdAttrView, ThresholdDisclosureView, + ThresholdView, + error::AttributesError, + views::{ + DisclosureView, bls12381, ed25519, ed25519_hybrid, ed25519_mayo2, fn_dsa, mayo, ml_dsa, + nist_p, rsa, secp256k1, slh_dsa, + }, +}; +use multi_codec::Codec; + +/// Provide a read-only view to access the signature attributes +/// +/// Falls back to `AttributesError::UnsupportedCodec` with the codec carried by +/// `ms` when no built-in view supports the codec. +pub(crate) fn dispatch_attr_view(ms: &Multisig) -> Result, Error> { + match ms.codec { + Codec::Bls12381G1Msig + | Codec::Bls12381G2Msig + | Codec::Bls12381G1ShareMsig + | Codec::Bls12381G2ShareMsig => Ok(Box::new(bls12381::View::try_from(ms)?)), + Codec::EddsaMsig | Codec::XeddsaMsig => Ok(Box::new(ed25519::View::try_from(ms)?)), + Codec::Es256KMsig => Ok(Box::new(secp256k1::View::try_from(ms)?)), + Codec::Es256Msig | Codec::Es384Msig | Codec::Es521Msig => { + Ok(Box::new(nist_p::View::try_from(ms)?)) + } + Codec::Rs256Msig => Ok(Box::new(rsa::View::try_from(ms)?)), + Codec::SlhDsaSha2128FMsig + | Codec::SlhDsaSha2128SMsig + | Codec::SlhDsaSha2192FMsig + | Codec::SlhDsaSha2192SMsig + | Codec::SlhDsaSha2256FMsig + | Codec::SlhDsaSha2256SMsig + | Codec::SlhDsaShake128FMsig + | Codec::SlhDsaShake128SMsig + | Codec::SlhDsaShake192FMsig + | Codec::SlhDsaShake192SMsig + | Codec::SlhDsaShake256FMsig + | Codec::SlhDsaShake256SMsig => Ok(Box::new(slh_dsa::View::try_from(ms)?)), + Codec::MlDsa65Msig | Codec::MlDsa87Msig => Ok(Box::new(ml_dsa::View::try_from(ms)?)), + Codec::FnDsa512Msig | Codec::FnDsa1024Msig => Ok(Box::new(fn_dsa::View::try_from(ms)?)), + Codec::Mayo1Msig | Codec::Mayo2Msig | Codec::Mayo3Msig | Codec::Mayo5Msig => { + Ok(Box::new(mayo::View::try_from(ms)?)) + } + Codec::Ed25519Mayo2Msig => Ok(Box::new(ed25519_mayo2::View::try_from(ms)?)), + Codec::Ed25519Mldsa65Msig + | Codec::Ed25519Fndsa512Msig + | Codec::Bls12381G1Mldsa65Msig + | Codec::Bls12381G1Fndsa512Msig + | Codec::Bls12381G1Mayo1Msig + | Codec::Bls12381G1Mayo2Msig => Ok(Box::new(ed25519_hybrid::View::try_from(ms)?)), + #[cfg(feature = "lamport")] + Codec::LamportSha3256Sig + | Codec::LamportSha3384Sig + | Codec::LamportSha3512Sig + | Codec::LamportSha3256SigShare + | Codec::LamportSha3384SigShare + | Codec::LamportSha3512SigShare + | Codec::LamportSha2256Sig + | Codec::LamportSha2384Sig + | Codec::LamportSha2512Sig + | Codec::LamportSha2256SigShare + | Codec::LamportSha2384SigShare + | Codec::LamportSha2512SigShare + | Codec::LamportBlake2B512Sig + | Codec::LamportBlake2S256Sig + | Codec::LamportBlake3256Sig + | Codec::LamportBlake2B512SigShare + | Codec::LamportBlake2S256SigShare + | Codec::LamportBlake3256SigShare + | Codec::LamportShake128Sig + | Codec::LamportShake256Sig + | Codec::LamportShake128SigShare + | Codec::LamportShake256SigShare => Ok(Box::new(lamport::View::try_from(ms)?)), + #[cfg(feature = "lamport")] + Codec::LamportMerkleSha3512Sig + | Codec::LamportMerkleSha3512SigShare + | Codec::LamportMerkleSha3384Sig + | Codec::LamportMerkleSha3384SigShare + | Codec::LamportMerkleSha3256Sig + | Codec::LamportMerkleSha3256SigShare + | Codec::LamportMerkleSha2512Sig + | Codec::LamportMerkleSha2512SigShare + | Codec::LamportMerkleSha2384Sig + | Codec::LamportMerkleSha2384SigShare + | Codec::LamportMerkleSha2256Sig + | Codec::LamportMerkleSha2256SigShare + | Codec::LamportMerkleBlake2B512Sig + | Codec::LamportMerkleBlake2B512SigShare + | Codec::LamportMerkleBlake2S256Sig + | Codec::LamportMerkleBlake2S256SigShare + | Codec::LamportMerkleBlake3256Sig + | Codec::LamportMerkleBlake3256SigShare + | Codec::LamportMerkleShake128Sig + | Codec::LamportMerkleShake128SigShare + | Codec::LamportMerkleShake256Sig + | Codec::LamportMerkleShake256SigShare => Ok(Box::new(lamport_merkle::View::try_from(ms)?)), + #[cfg(feature = "xmss")] + Codec::XmssSha210256Msig | Codec::XmssSha216256Msig | Codec::XmssSha220256Msig => { + Ok(Box::new(xmss::View::try_from(ms)?)) + } + _ => Err(AttributesError::UnsupportedCodec(ms.codec).into()), + } +} + +/// Provide a read-only view to access signature data +/// +/// Falls back to `AttributesError::UnsupportedCodec` with the codec carried by +/// `ms` when no built-in view supports the codec. +pub(crate) fn dispatch_data_view(ms: &Multisig) -> Result, Error> { + match ms.codec { + Codec::Bls12381G1Msig + | Codec::Bls12381G2Msig + | Codec::Bls12381G1ShareMsig + | Codec::Bls12381G2ShareMsig => Ok(Box::new(bls12381::View::try_from(ms)?)), + Codec::EddsaMsig | Codec::XeddsaMsig => Ok(Box::new(ed25519::View::try_from(ms)?)), + Codec::Es256KMsig => Ok(Box::new(secp256k1::View::try_from(ms)?)), + Codec::Es256Msig | Codec::Es384Msig | Codec::Es521Msig => { + Ok(Box::new(nist_p::View::try_from(ms)?)) + } + Codec::Rs256Msig => Ok(Box::new(rsa::View::try_from(ms)?)), + Codec::SlhDsaSha2128FMsig + | Codec::SlhDsaSha2128SMsig + | Codec::SlhDsaSha2192FMsig + | Codec::SlhDsaSha2192SMsig + | Codec::SlhDsaSha2256FMsig + | Codec::SlhDsaSha2256SMsig + | Codec::SlhDsaShake128FMsig + | Codec::SlhDsaShake128SMsig + | Codec::SlhDsaShake192FMsig + | Codec::SlhDsaShake192SMsig + | Codec::SlhDsaShake256FMsig + | Codec::SlhDsaShake256SMsig => Ok(Box::new(slh_dsa::View::try_from(ms)?)), + Codec::MlDsa65Msig | Codec::MlDsa87Msig => Ok(Box::new(ml_dsa::View::try_from(ms)?)), + Codec::FnDsa512Msig | Codec::FnDsa1024Msig => Ok(Box::new(fn_dsa::View::try_from(ms)?)), + Codec::Mayo1Msig | Codec::Mayo2Msig | Codec::Mayo3Msig | Codec::Mayo5Msig => { + Ok(Box::new(mayo::View::try_from(ms)?)) + } + Codec::Ed25519Mayo2Msig => Ok(Box::new(ed25519_mayo2::View::try_from(ms)?)), + Codec::Ed25519Mldsa65Msig + | Codec::Ed25519Fndsa512Msig + | Codec::Bls12381G1Mldsa65Msig + | Codec::Bls12381G1Fndsa512Msig + | Codec::Bls12381G1Mayo1Msig + | Codec::Bls12381G1Mayo2Msig => Ok(Box::new(ed25519_hybrid::View::try_from(ms)?)), + #[cfg(feature = "lamport")] + Codec::LamportSha3256Sig + | Codec::LamportSha3384Sig + | Codec::LamportSha3512Sig + | Codec::LamportSha3256SigShare + | Codec::LamportSha3384SigShare + | Codec::LamportSha3512SigShare + | Codec::LamportSha2256Sig + | Codec::LamportSha2384Sig + | Codec::LamportSha2512Sig + | Codec::LamportSha2256SigShare + | Codec::LamportSha2384SigShare + | Codec::LamportSha2512SigShare + | Codec::LamportBlake2B512Sig + | Codec::LamportBlake2S256Sig + | Codec::LamportBlake3256Sig + | Codec::LamportBlake2B512SigShare + | Codec::LamportBlake2S256SigShare + | Codec::LamportBlake3256SigShare + | Codec::LamportShake128Sig + | Codec::LamportShake256Sig + | Codec::LamportShake128SigShare + | Codec::LamportShake256SigShare => Ok(Box::new(lamport::View::try_from(ms)?)), + #[cfg(feature = "lamport")] + Codec::LamportMerkleSha3512Sig + | Codec::LamportMerkleSha3512SigShare + | Codec::LamportMerkleSha3384Sig + | Codec::LamportMerkleSha3384SigShare + | Codec::LamportMerkleSha3256Sig + | Codec::LamportMerkleSha3256SigShare + | Codec::LamportMerkleSha2512Sig + | Codec::LamportMerkleSha2512SigShare + | Codec::LamportMerkleSha2384Sig + | Codec::LamportMerkleSha2384SigShare + | Codec::LamportMerkleSha2256Sig + | Codec::LamportMerkleSha2256SigShare + | Codec::LamportMerkleBlake2B512Sig + | Codec::LamportMerkleBlake2B512SigShare + | Codec::LamportMerkleBlake2S256Sig + | Codec::LamportMerkleBlake2S256SigShare + | Codec::LamportMerkleBlake3256Sig + | Codec::LamportMerkleBlake3256SigShare + | Codec::LamportMerkleShake128Sig + | Codec::LamportMerkleShake128SigShare + | Codec::LamportMerkleShake256Sig + | Codec::LamportMerkleShake256SigShare => Ok(Box::new(lamport_merkle::View::try_from(ms)?)), + #[cfg(feature = "xmss")] + Codec::XmssSha210256Msig | Codec::XmssSha216256Msig | Codec::XmssSha220256Msig => { + Ok(Box::new(xmss::View::try_from(ms)?)) + } + _ => Err(AttributesError::UnsupportedCodec(ms.codec).into()), + } +} + +/// Provide a view for converting to other signature formats +/// +/// Falls back to `AttributesError::UnsupportedCodec` with the codec carried by +/// `ms` when no built-in view supports the codec. +pub(crate) fn dispatch_conv_view(ms: &Multisig) -> Result, Error> { + match ms.codec { + Codec::Bls12381G1Msig + | Codec::Bls12381G2Msig + | Codec::Bls12381G1ShareMsig + | Codec::Bls12381G2ShareMsig => Ok(Box::new(bls12381::View::try_from(ms)?)), + Codec::EddsaMsig | Codec::XeddsaMsig => Ok(Box::new(ed25519::View::try_from(ms)?)), + Codec::Es256KMsig => Ok(Box::new(secp256k1::View::try_from(ms)?)), + Codec::Es256Msig | Codec::Es384Msig | Codec::Es521Msig => { + Ok(Box::new(nist_p::View::try_from(ms)?)) + } + Codec::Rs256Msig => Ok(Box::new(rsa::View::try_from(ms)?)), + Codec::SlhDsaSha2128FMsig + | Codec::SlhDsaSha2128SMsig + | Codec::SlhDsaSha2192FMsig + | Codec::SlhDsaSha2192SMsig + | Codec::SlhDsaSha2256FMsig + | Codec::SlhDsaSha2256SMsig + | Codec::SlhDsaShake128FMsig + | Codec::SlhDsaShake128SMsig + | Codec::SlhDsaShake192FMsig + | Codec::SlhDsaShake192SMsig + | Codec::SlhDsaShake256FMsig + | Codec::SlhDsaShake256SMsig => Ok(Box::new(slh_dsa::View::try_from(ms)?)), + Codec::MlDsa65Msig | Codec::MlDsa87Msig => Ok(Box::new(ml_dsa::View::try_from(ms)?)), + Codec::FnDsa512Msig | Codec::FnDsa1024Msig => Ok(Box::new(fn_dsa::View::try_from(ms)?)), + Codec::Mayo1Msig | Codec::Mayo2Msig | Codec::Mayo3Msig | Codec::Mayo5Msig => { + Ok(Box::new(mayo::View::try_from(ms)?)) + } + Codec::Ed25519Mayo2Msig => Ok(Box::new(ed25519_mayo2::View::try_from(ms)?)), + Codec::Ed25519Mldsa65Msig + | Codec::Ed25519Fndsa512Msig + | Codec::Bls12381G1Mldsa65Msig + | Codec::Bls12381G1Fndsa512Msig + | Codec::Bls12381G1Mayo1Msig + | Codec::Bls12381G1Mayo2Msig => Ok(Box::new(ed25519_hybrid::View::try_from(ms)?)), + #[cfg(feature = "lamport")] + Codec::LamportSha3256Sig + | Codec::LamportSha3384Sig + | Codec::LamportSha3512Sig + | Codec::LamportSha3256SigShare + | Codec::LamportSha3384SigShare + | Codec::LamportSha3512SigShare + | Codec::LamportSha2256Sig + | Codec::LamportSha2384Sig + | Codec::LamportSha2512Sig + | Codec::LamportSha2256SigShare + | Codec::LamportSha2384SigShare + | Codec::LamportSha2512SigShare + | Codec::LamportBlake2B512Sig + | Codec::LamportBlake2S256Sig + | Codec::LamportBlake3256Sig + | Codec::LamportBlake2B512SigShare + | Codec::LamportBlake2S256SigShare + | Codec::LamportBlake3256SigShare + | Codec::LamportShake128Sig + | Codec::LamportShake256Sig + | Codec::LamportShake128SigShare + | Codec::LamportShake256SigShare => Ok(Box::new(lamport::View::try_from(ms)?)), + #[cfg(feature = "lamport")] + Codec::LamportMerkleSha3512Sig + | Codec::LamportMerkleSha3512SigShare + | Codec::LamportMerkleSha3384Sig + | Codec::LamportMerkleSha3384SigShare + | Codec::LamportMerkleSha3256Sig + | Codec::LamportMerkleSha3256SigShare + | Codec::LamportMerkleSha2512Sig + | Codec::LamportMerkleSha2512SigShare + | Codec::LamportMerkleSha2384Sig + | Codec::LamportMerkleSha2384SigShare + | Codec::LamportMerkleSha2256Sig + | Codec::LamportMerkleSha2256SigShare + | Codec::LamportMerkleBlake2B512Sig + | Codec::LamportMerkleBlake2B512SigShare + | Codec::LamportMerkleBlake2S256Sig + | Codec::LamportMerkleBlake2S256SigShare + | Codec::LamportMerkleBlake3256Sig + | Codec::LamportMerkleBlake3256SigShare + | Codec::LamportMerkleShake128Sig + | Codec::LamportMerkleShake128SigShare + | Codec::LamportMerkleShake256Sig + | Codec::LamportMerkleShake256SigShare => Ok(Box::new(lamport_merkle::View::try_from(ms)?)), + #[cfg(feature = "xmss")] + Codec::XmssSha210256Msig | Codec::XmssSha216256Msig | Codec::XmssSha220256Msig => { + Ok(Box::new(xmss::View::try_from(ms)?)) + } + _ => Err(AttributesError::UnsupportedCodec(ms.codec).into()), + } +} + +/// Provide a read-only view to access the threshold signature attributes +/// +/// Only the BLS combined and share codecs plus the hash-based families +/// provide threshold attributes. Other codecs fall back to +/// `AttributesError::UnsupportedCodec` with the codec carried by `ms`. +pub(crate) fn dispatch_threshold_attr_view( + ms: &Multisig, +) -> Result, Error> { + match ms.codec { + Codec::Bls12381G1Msig + | Codec::Bls12381G2Msig + | Codec::Bls12381G1ShareMsig + | Codec::Bls12381G2ShareMsig => Ok(Box::new(bls12381::View::try_from(ms)?)), + #[cfg(feature = "lamport")] + Codec::LamportSha3256Sig + | Codec::LamportSha3256SigShare + | Codec::LamportSha3384Sig + | Codec::LamportSha3384SigShare + | Codec::LamportSha3512Sig + | Codec::LamportSha3512SigShare + | Codec::LamportSha2256Sig + | Codec::LamportSha2256SigShare + | Codec::LamportSha2384Sig + | Codec::LamportSha2384SigShare + | Codec::LamportSha2512Sig + | Codec::LamportSha2512SigShare + | Codec::LamportBlake2B512Sig + | Codec::LamportBlake2B512SigShare + | Codec::LamportBlake2S256Sig + | Codec::LamportBlake2S256SigShare + | Codec::LamportBlake3256Sig + | Codec::LamportBlake3256SigShare + | Codec::LamportShake128Sig + | Codec::LamportShake128SigShare + | Codec::LamportShake256Sig + | Codec::LamportShake256SigShare => Ok(Box::new(lamport::View::try_from(ms)?)), + #[cfg(feature = "lamport")] + Codec::LamportMerkleSha3512Sig + | Codec::LamportMerkleSha3512SigShare + | Codec::LamportMerkleSha3384Sig + | Codec::LamportMerkleSha3384SigShare + | Codec::LamportMerkleSha3256Sig + | Codec::LamportMerkleSha3256SigShare + | Codec::LamportMerkleSha2512Sig + | Codec::LamportMerkleSha2512SigShare + | Codec::LamportMerkleSha2384Sig + | Codec::LamportMerkleSha2384SigShare + | Codec::LamportMerkleSha2256Sig + | Codec::LamportMerkleSha2256SigShare + | Codec::LamportMerkleBlake2B512Sig + | Codec::LamportMerkleBlake2B512SigShare + | Codec::LamportMerkleBlake2S256Sig + | Codec::LamportMerkleBlake2S256SigShare + | Codec::LamportMerkleBlake3256Sig + | Codec::LamportMerkleBlake3256SigShare + | Codec::LamportMerkleShake128Sig + | Codec::LamportMerkleShake128SigShare + | Codec::LamportMerkleShake256Sig + | Codec::LamportMerkleShake256SigShare => Ok(Box::new(lamport_merkle::View::try_from(ms)?)), + _ => Err(AttributesError::UnsupportedCodec(ms.codec).into()), + } +} + +/// Provide the view for adding a share to a multisig +/// +/// Only the BLS combined codecs plus the hash-based families provide share +/// accumulation. Other codecs fall back to +/// `AttributesError::UnsupportedCodec` with the codec carried by `ms`. +pub(crate) fn dispatch_threshold_view(ms: &Multisig) -> Result, Error> { + match ms.codec { + Codec::Bls12381G1Msig | Codec::Bls12381G2Msig => { + Ok(Box::new(bls12381::View::try_from(ms)?)) + } + #[cfg(feature = "lamport")] + Codec::LamportSha3256Sig + | Codec::LamportSha3256SigShare + | Codec::LamportSha3384Sig + | Codec::LamportSha3384SigShare + | Codec::LamportSha3512Sig + | Codec::LamportSha3512SigShare + | Codec::LamportSha2256Sig + | Codec::LamportSha2256SigShare + | Codec::LamportSha2384Sig + | Codec::LamportSha2384SigShare + | Codec::LamportSha2512Sig + | Codec::LamportSha2512SigShare + | Codec::LamportBlake2B512Sig + | Codec::LamportBlake2B512SigShare + | Codec::LamportBlake2S256Sig + | Codec::LamportBlake2S256SigShare + | Codec::LamportBlake3256Sig + | Codec::LamportBlake3256SigShare + | Codec::LamportShake128Sig + | Codec::LamportShake128SigShare + | Codec::LamportShake256Sig + | Codec::LamportShake256SigShare => Ok(Box::new(lamport::View::try_from(ms)?)), + #[cfg(feature = "lamport")] + Codec::LamportMerkleSha3512Sig + | Codec::LamportMerkleSha3512SigShare + | Codec::LamportMerkleSha3384Sig + | Codec::LamportMerkleSha3384SigShare + | Codec::LamportMerkleSha3256Sig + | Codec::LamportMerkleSha3256SigShare + | Codec::LamportMerkleSha2512Sig + | Codec::LamportMerkleSha2512SigShare + | Codec::LamportMerkleSha2384Sig + | Codec::LamportMerkleSha2384SigShare + | Codec::LamportMerkleSha2256Sig + | Codec::LamportMerkleSha2256SigShare + | Codec::LamportMerkleBlake2B512Sig + | Codec::LamportMerkleBlake2B512SigShare + | Codec::LamportMerkleBlake2S256Sig + | Codec::LamportMerkleBlake2S256SigShare + | Codec::LamportMerkleBlake3256Sig + | Codec::LamportMerkleBlake3256SigShare + | Codec::LamportMerkleShake128Sig + | Codec::LamportMerkleShake128SigShare + | Codec::LamportMerkleShake256Sig + | Codec::LamportMerkleShake256SigShare => Ok(Box::new(lamport_merkle::View::try_from(ms)?)), + _ => Err(AttributesError::UnsupportedCodec(ms.codec).into()), + } +} + +/// Provide an interface for threshold disclosure mode operations +/// +/// The disclosure view is codec-agnostic and always available. The result +/// mirrors the `Views` trait method so all dispatch functions share one call +/// shape. +#[allow(clippy::unnecessary_wraps)] +pub(crate) fn dispatch_disclosure_view( + ms: &Multisig, +) -> Result, Error> { + Ok(Box::new(DisclosureView::new(ms))) +} From 2d7730cdb9c769b1b0e95cf33f8e3b2413cb8425 Mon Sep 17 00:00:00 2001 From: Dave Grantham Date: Tue, 6 Oct 2026 21:58:01 -0600 Subject: [PATCH 2/7] add `ViewBuilder` Signed-off-by: Dave Grantham --- src/lib.rs | 7 + src/views.rs | 2 + src/views/builder.rs | 839 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 848 insertions(+) create mode 100644 src/views/builder.rs diff --git a/src/lib.rs b/src/lib.rs index dae5bf7..6eee958 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -154,6 +154,13 @@ pub use views::{ ThresholdView, Views, decrypt_threshold_meta, encrypt_threshold_meta, generate_meta_key, }; +/// Builder-pattern view creation +pub use views::builder::{ + AttrKind, ConvKind, DataKind, DisclosureKind, LocalAttrFn, LocalConvFn, LocalDataFn, + LocalDisclosureFn, LocalThresholdAttrFn, LocalThresholdFn, ThresholdAttrKind, ThresholdKind, + Unselected, ViewBuilder, ViewKind, +}; + /// Merkle-tree Lamport signature view #[cfg(feature = "lamport")] pub use views::lamport_merkle; diff --git a/src/views.rs b/src/views.rs index 2c826b4..85fb966 100644 --- a/src/views.rs +++ b/src/views.rs @@ -4,6 +4,8 @@ use multi_codec::Codec; /// BLS12 381 G1/G2 signature implementation pub mod bls12381; +/// Builder-pattern construction of the view types +pub mod builder; /// Crate-internal per-codec view dispatch shared by view entry points pub(crate) mod dispatch; /// Edwards curve 25519 signature implementation diff --git a/src/views/builder.rs b/src/views/builder.rs new file mode 100644 index 0000000..0daa48c --- /dev/null +++ b/src/views/builder.rs @@ -0,0 +1,839 @@ +// 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 +//! shape. It serves two purposes: +//! +//! 1. Standard codecs reach their built-in views through the same dispatch +//! core that backs the `Views` extension trait. +//! 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). +//! +//! # Flow +//! +//! [`ViewBuilder::new`](crate::views::builder::ViewBuilder::new) returns an +//! [unselected](crate::views::builder::Unselected) builder. A kind selector +//! transitions the builder into the requested view kind. A kind-selected +//! builder optionally registers a local-codec factory with +//! [`ViewBuilder::with_local_codec`](crate::views::builder::ViewBuilder::with_local_codec) +//! and finishes with +//! [`ViewBuilder::build`](crate::views::builder::ViewBuilder::build). +//! +//! # Example +//! +//! ``` +//! use multi_sig::prelude::*; +//! +//! // A custom scheme carries a codec outside `SIG_CODECS`. The convention +//! // uses the `Identity` slot (codec code 0) for demonstration. +//! let ms = Builder::new(Codec::Identity) +//! .with_signature_bytes(&[0u8; 8]) +//! .try_build() +//! .unwrap(); +//! +//! struct Custom; +//! +//! impl AttrView for Custom { +//! fn payload_encoding(&self) -> Result { +//! Ok(Codec::Identity) +//! } +//! fn scheme(&self) -> Result { +//! Ok(0x2A) +//! } +//! } +//! +//! let view = ViewBuilder::new(&ms) +//! .attr() +//! .with_local_codec(Codec::Identity, Box::new(|_ms| Ok(Box::new(Custom)))) +//! .build() +//! .unwrap(); +//! assert_eq!(view.scheme().unwrap(), 0x2A); +//! ``` +//! +//! # Dispatch order +//! +//! `build` consults the built-in codec dispatch first. Only when it reports +//! [`AttributesError::UnsupportedCodec`](crate::error::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 +//! by a factory. +//! +//! The `disclosure` kind is the exception among kinds: its view is +//! codec-agnostic and always built in, so a local factory for that kind is +//! never consulted. +//! +//! # Factory contract +//! +//! A factory is a boxed `Fn(&Multisig) -> Result, Error>` +//! closure that must hold the `Send + Sync + 'static` bounds in its type +//! alias and must not capture borrows. Errors from a factory propagate +//! unchanged. A repeat `with_local_codec` call for the same kind replaces +//! the earlier factory: the last registration wins. +//! +//! A factory may return a view that borrows the `Multisig`. A small +//! lifetime-parameterized helper function keeps closure inference simple +//! for that case; see the unit tests for the pattern. +//! +//! The demonstration slot for a custom scheme is [`Codec::Identity`] +//! (codec code 0), which no built-in dispatch table covers. Schemes that +//! share a slot disambiguate through attributes inside the factory. +//! +//! # 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. + +use crate::{ + AttrView, ConvView, DataView, Error, Multisig, ThresholdAttrView, ThresholdDisclosureView, + ThresholdView, error::AttributesError, views::dispatch, +}; +use multi_codec::Codec; +use multi_util::CodecInfo; +use std::marker::PhantomData; + +/// Sealing for the [`ViewKind`] trait. Kept private so downstream code +/// cannot implement view kinds. +mod sealed { + /// Sealed trait that prevents downstream implementations of view kinds. + #[doc(hidden)] + pub trait Sealed {} +} + +/// Identifies the kind of view a [`ViewBuilder`] can build. +/// +/// Sealed: [`AttrKind`], [`DataKind`], [`ConvKind`], [`ThresholdAttrKind`], +/// [`ThresholdKind`], [`DisclosureKind`], and [`Unselected`] are the only +/// implementors. Adding a view kind is a breaking change. +pub trait ViewKind: sealed::Sealed { + /// Boxed local-codec factory type accepted by + /// [`ViewBuilder::with_local_codec`] for this view kind. + #[doc(hidden)] + type Factory; +} + +/// Marker for the builder state before any view kind is selected. Only the +/// kind selectors are available in this state; `with_local_codec` and +/// `build` become available after a selector runs. +pub struct Unselected; + +/// Marker for the [`AttrView`] view kind, selected by [`ViewBuilder::attr`]. +pub struct AttrKind; + +/// Marker for the [`DataView`] view kind, selected by [`ViewBuilder::data`]. +pub struct DataKind; + +/// Marker for the [`ConvView`] view kind, selected by [`ViewBuilder::conv`]. +pub struct ConvKind; + +/// Marker for the [`ThresholdAttrView`] view kind, selected by +/// [`ViewBuilder::threshold_attr`]. +pub struct ThresholdAttrKind; + +/// Marker for the [`ThresholdView`] view kind, selected by +/// [`ViewBuilder::threshold`]. +pub struct ThresholdKind; + +/// Marker for the [`ThresholdDisclosureView`] view kind, selected by +/// [`ViewBuilder::disclosure`]. +pub struct DisclosureKind; + +/// Boxed local-codec factory for the attributes view kind. +pub type LocalAttrFn = Box< + dyn for<'a> Fn(&'a Multisig) -> Result, Error> + Send + Sync + 'static, +>; + +/// Boxed local-codec factory for the data view kind. +pub type LocalDataFn = Box< + dyn for<'a> Fn(&'a Multisig) -> Result, Error> + Send + Sync + 'static, +>; + +/// Boxed local-codec factory for the conversion view kind. +pub type LocalConvFn = Box< + dyn for<'a> Fn(&'a Multisig) -> Result, Error> + Send + Sync + 'static, +>; + +/// Boxed local-codec factory for the threshold attributes view kind. +pub type LocalThresholdAttrFn = Box< + dyn for<'a> Fn(&'a Multisig) -> Result, Error> + + Send + + Sync + + 'static, +>; + +/// Boxed local-codec factory for the threshold view kind. +pub type LocalThresholdFn = Box< + dyn for<'a> Fn(&'a Multisig) -> Result, Error> + + Send + + Sync + + 'static, +>; + +/// Boxed local-codec factory for the threshold disclosure view kind. Stored +/// only for API symmetry: the built-in disclosure view is codec-agnostic, so +/// this factory is never consulted. +pub type LocalDisclosureFn = Box< + dyn for<'a> Fn(&'a Multisig) -> Result, Error> + + Send + + Sync + + 'static, +>; + +impl sealed::Sealed for Unselected {} + +impl sealed::Sealed for AttrKind {} + +impl sealed::Sealed for DataKind {} + +impl sealed::Sealed for ConvKind {} + +impl sealed::Sealed for ThresholdAttrKind {} + +impl sealed::Sealed for ThresholdKind {} + +impl sealed::Sealed for DisclosureKind {} + +impl ViewKind for Unselected { + /// The unselected state registers no factory, so the slot type is + /// never instantiated. + type Factory = (); +} + +impl ViewKind for AttrKind { + type Factory = LocalAttrFn; +} + +impl ViewKind for DataKind { + type Factory = LocalDataFn; +} + +impl ViewKind for ConvKind { + type Factory = LocalConvFn; +} + +impl ViewKind for ThresholdAttrKind { + type Factory = LocalThresholdAttrFn; +} + +impl ViewKind for ThresholdKind { + type Factory = LocalThresholdFn; +} + +impl ViewKind for DisclosureKind { + type Factory = LocalDisclosureFn; +} + +/// Builder for the read-only view types of a [`Multisig`]. +/// +/// See the module documentation for the full contract. The second type +/// parameter tracks the selected view kind at the type level: +/// +/// - [`ViewBuilder::attr`], [`ViewBuilder::data`], [`ViewBuilder::conv`], +/// [`ViewBuilder::threshold_attr`], [`ViewBuilder::threshold`], and +/// [`ViewBuilder::disclosure`] each transition an +/// [unselected](Unselected) builder into a kind-selected one. +/// - A kind-selected builder accepts `.with_local_codec` and finishes with +/// `.build`. +/// - The builder itself is `Send + Sync` when its factory type is. The +/// returned `Box` carries no `Send`/`Sync` bound; +/// the docs of the view traits must not promise more. +/// +/// Dispatch order: built-in view first, local factory second (on +/// `AttributesError::UnsupportedCodec` fallthrough only), error last. +pub struct ViewBuilder<'ms, K: ViewKind> { + ms: &'ms Multisig, + kind: PhantomData, + local: Option<(Codec, K::Factory)>, +} + +impl<'ms> ViewBuilder<'ms, Unselected> { + /// Start building a view for `ms`. + pub fn new(ms: &'ms Multisig) -> Self { + Self { + ms, + kind: PhantomData, + local: None, + } + } + + /// Re-select a view kind from the held `Multisig` reference. + fn select(self) -> ViewBuilder<'ms, K> { + ViewBuilder { + ms: self.ms, + kind: PhantomData, + local: None, + } + } + + /// Select the attributes view kind; `build` then returns + /// `Result, Error>`. + pub fn attr(self) -> ViewBuilder<'ms, AttrKind> { + self.select() + } + + /// Select the data view kind; `build` then returns + /// `Result, Error>`. + pub fn data(self) -> ViewBuilder<'ms, DataKind> { + self.select() + } + + /// Select the conversion view kind; `build` then returns + /// `Result, Error>`. + pub fn conv(self) -> ViewBuilder<'ms, ConvKind> { + self.select() + } + + /// Select the threshold attributes view kind; `build` then returns + /// `Result, Error>`. + pub fn threshold_attr(self) -> ViewBuilder<'ms, ThresholdAttrKind> { + self.select() + } + + /// Select the threshold view kind; `build` then returns + /// `Result, Error>`. + pub fn threshold(self) -> ViewBuilder<'ms, ThresholdKind> { + self.select() + } + + /// Select the threshold disclosure view kind; `build` then returns + /// `Result, Error>`. + pub fn disclosure(self) -> ViewBuilder<'ms, DisclosureKind> { + self.select() + } +} + +macro_rules! view_kind_api { + ($kind:ident, $factory:ident, $view:ident, $dispatch:ident) => { + impl<'ms> ViewBuilder<'ms, $kind> { + /// Register a local-codec factory for this view kind. + /// + /// `factory` must be the boxed HRTB form named by this kind's + /// `Local*Fn` type alias: a closure that receives the + /// `Multisig`, returns `Result, Error>`, and + /// holds `Send + Sync + 'static`. It must not capture borrows. + /// + /// A repeat call replaces the earlier factory: the last + /// registration wins. + pub fn with_local_codec(mut self, codec: Codec, factory: $factory) -> Self { + self.local = Some((codec, factory)); + self + } + + /// Build the requested view. + /// + /// The built-in codec dispatch runs first. On + /// `AttributesError::UnsupportedCodec` fallthrough with the codec + /// carried by the `Multisig`, a registered local-codec factory + /// runs, and its output or error is returned unchanged. A + /// factory registered for another codec is ignored, and the + /// dispatch error propagates unchanged. The `disclosure` kind is + /// codec-agnostic, so its local factory is never consulted. + pub fn build(self) -> Result, Error> { + let ms = self.ms; + match dispatch::$dispatch(ms) { + Ok(view) => Ok(view), + Err(err @ Error::Attributes(AttributesError::UnsupportedCodec(_))) => { + match &self.local { + Some((codec, factory)) if *codec == ms.codec() => factory(ms), + _ => Err(err), + } + } + Err(err) => Err(err), + } + } + } + }; +} + +view_kind_api!(AttrKind, LocalAttrFn, AttrView, dispatch_attr_view); +view_kind_api!(DataKind, LocalDataFn, DataView, dispatch_data_view); +view_kind_api!(ConvKind, LocalConvFn, ConvView, dispatch_conv_view); +view_kind_api!( + ThresholdAttrKind, + LocalThresholdAttrFn, + ThresholdAttrView, + dispatch_threshold_attr_view +); +view_kind_api!( + ThresholdKind, + LocalThresholdFn, + ThresholdView, + dispatch_threshold_view +); +view_kind_api!( + DisclosureKind, + LocalDisclosureFn, + ThresholdDisclosureView, + dispatch_disclosure_view +); + +#[cfg(test)] +mod tests { + use super::*; + use crate::{AttrId, Builder, SIG_CODECS, SIG_SHARE_CODECS, ThresholdDisclosure}; + use std::sync::{Arc, atomic::AtomicUsize, atomic::Ordering}; + + /// Sentinel attribute view produced by test factories. + struct SchemeAttr(u8); + + impl AttrView for SchemeAttr { + fn payload_encoding(&self) -> Result { + Ok(Codec::Identity) + } + + fn scheme(&self) -> Result { + Ok(self.0) + } + } + + /// Sentinel data view for factory tests; echoes the stored bytes. + struct BytesDataView(Vec); + + impl DataView for BytesDataView { + fn sig_bytes(&self) -> Result, Error> { + Ok(self.0.clone()) + } + } + + /// Sentinel conversion view; every method carries a distinctive marker. + struct FactoryConvView; + + impl ConvView for FactoryConvView { + fn to_ssh_signature(&self) -> Result { + Err(Error::FailedConversion("factory conv marker".into())) + } + } + + /// Sentinel threshold attributes view for factory tests. + struct ThresholdAttrSentinel(Vec); + + impl ThresholdAttrView for ThresholdAttrSentinel { + fn threshold(&self) -> Result { + Ok(6) + } + + fn limit(&self) -> Result { + Ok(9) + } + + fn identifier(&self) -> Result<&[u8], Error> { + Ok(&self.0) + } + + fn threshold_data(&self) -> Result<&[u8], Error> { + Ok(&self.0) + } + } + + /// Sentinel threshold view for factory tests; carries its own share. + struct ThresholdSentinel(Multisig); + + impl ThresholdView for ThresholdSentinel { + fn shares(&self) -> Result, Error> { + Ok(vec![self.0.clone()]) + } + + fn shares_with_disclosure( + &self, + _mode: ThresholdDisclosure, + _meta_key: Option<&[u8]>, + ) -> Result, Error> { + Ok(vec![self.0.clone()]) + } + + fn add_share(&self, share: &Multisig) -> Result { + Ok(share.clone()) + } + + fn add_share_with_meta( + &self, + share: &Multisig, + _meta_key: Option<&[u8]>, + ) -> Result { + Ok(share.clone()) + } + + fn combine(&self) -> Result { + Ok(self.0.clone()) + } + + fn combine_with_meta(&self, _meta_key: Option<&[u8]>) -> Result { + Ok(self.0.clone()) + } + } + + /// Sentinel disclosure view for the never-consulted factory test. Its + /// `disclosure_mode` differs from the built-in answer so that a + /// consultation cannot go undetected. + struct DisclosureSentinel; + + impl ThresholdDisclosureView for DisclosureSentinel { + fn disclosure_mode(&self) -> Result { + Ok(ThresholdDisclosure::Partial) + } + + fn read_threshold_params(&self, _meta_key: Option<&[u8]>) -> Result<(usize, usize), Error> { + Ok((6, 9)) + } + + fn to_disclosure( + &self, + _target: ThresholdDisclosure, + _meta_key: Option<&[u8]>, + _current_meta_key: Option<&[u8]>, + ) -> Result { + Ok(Multisig::default()) + } + } + + /// Data view bound to its source `Multisig`, proving the factory HRTB + /// accepts views that borrow it. + struct BorrowedDataView<'ms>(&'ms Multisig); + + impl DataView for BorrowedDataView<'_> { + fn sig_bytes(&self) -> Result, Error> { + Ok(self.0.message.clone()) + } + } + + /// Attribute factory with a sentinel scheme. + fn scheme_attr_factory(scheme: u8) -> LocalAttrFn { + Box::new(move |_: &Multisig| { + let attr: Box = Box::new(SchemeAttr(scheme)); + Ok(attr) + }) + } + + /// Data factory that echoes the signature bytes of the `Multisig` it + /// receives. + fn ms_data_factory() -> LocalDataFn { + Box::new(|ms: &Multisig| { + let data = ms + .attributes + .get(&AttrId::SigData) + .cloned() + .unwrap_or_default(); + let view: Box = Box::new(BytesDataView(data)); + Ok(view) + }) + } + + /// A multisig with the unregistered custom codec slot. + fn custom_ms() -> Multisig { + Builder::new(Codec::Identity) + .with_signature_bytes(&[0u8; 64]) + .with_scheme(0x2B) + .try_build() + .unwrap() + } + + /// A multisig for a codec that has a built-in data view but no + /// threshold views. + fn es256k_ms() -> Multisig { + Builder::new(Codec::Es256KMsig) + .with_signature_bytes(&[0u8; 64]) + .try_build() + .unwrap() + } + + /// Extract the error from a view-build result; view trait objects carry + /// no `Debug` bound, so `unwrap_err` is unavailable here. + fn build_err(result: Result) -> Error { + match result { + Ok(_) => panic!("expected an error, got Ok"), + Err(err) => err, + } + } + + #[test] + fn test_sig_codecs_data_view_dispatch() { + for codec in SIG_CODECS { + let ms = Builder::new(codec) + .with_signature_bytes(&[0u8; 64]) + .try_build() + .unwrap(); + let result = ViewBuilder::new(&ms).data().build(); + assert!( + result.is_ok(), + "SIG_CODECS entry {codec:?} does not dispatch a data view through the builder (error kind {:?})", + result.err().map(|e| e.to_string()) + ); + } + } + + #[test] + fn test_sig_share_codecs_threshold_attr_dispatch() { + for codec in SIG_SHARE_CODECS { + let ms = Builder::new(codec) + .with_signature_bytes(&[0u8; 64]) + .try_build() + .unwrap(); + let result = ViewBuilder::new(&ms).threshold_attr().build(); + assert!( + result.is_ok(), + "SIG_SHARE_CODECS entry {codec:?} does not dispatch a threshold-attribute view through the builder (error kind {:?})", + result.err().map(|e| e.to_string()) + ); + } + } + + #[test] + fn test_representative_kinds_build() { + let ms = Builder::new(Codec::EddsaMsig) + .with_signature_bytes(&[0u8; 64]) + .try_build() + .unwrap(); + + assert!(ViewBuilder::new(&ms).attr().build().is_ok()); + let data = ViewBuilder::new(&ms).data().build().unwrap(); + assert_eq!(data.sig_bytes().unwrap(), vec![0u8; 64]); + assert!(ViewBuilder::new(&ms).conv().build().is_ok()); + + // A share codec that carries threshold attributes. + let share = Builder::new(Codec::Bls12381G2ShareMsig) + .with_signature_bytes(&[0u8; 64]) + .try_build() + .unwrap(); + assert!(ViewBuilder::new(&share).threshold_attr().build().is_ok()); + + // A combined BLS codec that carries share accumulation. + let combined = Builder::new(Codec::Bls12381G1Msig) + .with_signature_bytes(&[0u8; 64]) + .try_build() + .unwrap(); + assert!(ViewBuilder::new(&combined).threshold().build().is_ok()); + + // The disclosure view builds for any codec. + assert!(ViewBuilder::new(&combined).disclosure().build().is_ok()); + } + + #[test] + fn test_unsupported_codec_without_factory() { + let ms = es256k_ms(); + let err = build_err(ViewBuilder::new(&ms).threshold().build()); + assert!(matches!( + err, + Error::Attributes(AttributesError::UnsupportedCodec(Codec::Es256KMsig)) + )); + } + + #[test] + fn test_custom_codec_factories_return_output() { + let ms = custom_ms(); + + // Attributes kind: the factory output carries the sentinel scheme. + let attr = ViewBuilder::new(&ms) + .attr() + .with_local_codec(Codec::Identity, scheme_attr_factory(0x2A)) + .build() + .unwrap(); + assert_eq!(attr.scheme().unwrap(), 0x2A); + + // Data kind: the factory receives the multisig and echoes its data. + let data = ViewBuilder::new(&ms) + .data() + .with_local_codec(Codec::Identity, ms_data_factory()) + .build() + .unwrap(); + assert_eq!(data.sig_bytes().unwrap(), vec![0u8; 64]); + + // Threshold attributes kind. + let threshold_attr = ViewBuilder::new(&ms) + .threshold_attr() + .with_local_codec( + Codec::Identity, + Box::new(move |_: &Multisig| { + let view: Box = + Box::new(ThresholdAttrSentinel(vec![7u8])); + Ok(view) + }), + ) + .build() + .unwrap(); + assert_eq!(threshold_attr.threshold().unwrap(), 6); + assert_eq!(threshold_attr.limit().unwrap(), 9); + assert_eq!(threshold_attr.identifier().unwrap(), &[7u8]); + + // Threshold kind. The sentinel carries its own deterministic share. + let threshold = ViewBuilder::new(&ms) + .threshold() + .with_local_codec( + Codec::Identity, + Box::new(|_: &Multisig| { + let view: Box = Box::new(ThresholdSentinel(custom_ms())); + Ok(view) + }), + ) + .build() + .unwrap(); + assert_eq!(threshold.combine().unwrap(), custom_ms()); + } + + #[test] + fn test_custom_codec_conv_factory() { + let ms = custom_ms(); + let conv = ViewBuilder::new(&ms) + .conv() + .with_local_codec( + Codec::Identity, + Box::new(|_: &Multisig| { + let view: Box = Box::new(FactoryConvView); + Ok(view) + }), + ) + .build() + .unwrap(); + // The built box is the factory's view: its marker error identifies it. + let err = conv.to_ssh_signature().unwrap_err(); + assert!(matches!(err, Error::FailedConversion(msg) if msg == "factory conv marker")); + } + + #[test] + fn test_factory_error_propagates() { + let ms = custom_ms(); + let result = ViewBuilder::new(&ms) + .attr() + .with_local_codec( + Codec::Identity, + Box::new(|_: &Multisig| -> Result, Error> { + Err(Error::FailedConversion("factory boom".into())) + }), + ) + .build(); + let err = build_err(result); + assert!(matches!(err, Error::FailedConversion(msg) if msg == "factory boom")); + } + + #[test] + fn test_builtin_view_wins_over_factory() { + let ms = es256k_ms(); + let hits = Arc::new(AtomicUsize::new(0)); + let data = ViewBuilder::new(&ms) + .data() + .with_local_codec(Codec::Es256KMsig, ms_data_factory_with_hits(hits.clone())) + .build() + .unwrap(); + assert_eq!(hits.load(Ordering::SeqCst), 0); + // The built-in view holds the real signature data, not the sentinel. + assert_eq!(data.sig_bytes().unwrap(), vec![0u8; 64]); + } + + /// Data factory with a call counter and a sentinel payload. + fn ms_data_factory_with_hits(hits: Arc) -> LocalDataFn { + Box::new(move |_: &Multisig| { + hits.fetch_add(1, Ordering::SeqCst); + let view: Box = Box::new(BytesDataView(vec![0xEEu8])); + Ok(view) + }) + } + + #[test] + fn test_factory_for_other_codec_ignored() { + let ms = es256k_ms(); + let result = ViewBuilder::new(&ms) + .threshold() + .with_local_codec( + Codec::Identity, + Box::new(|_: &Multisig| { + let view: Box = Box::new(ThresholdSentinel(custom_ms())); + Ok(view) + }), + ) + .build(); + let err = build_err(result); + assert!(matches!( + err, + Error::Attributes(AttributesError::UnsupportedCodec(Codec::Es256KMsig)) + )); + } + + #[test] + fn test_last_registration_wins() { + let ms = custom_ms(); + let attr = ViewBuilder::new(&ms) + .attr() + .with_local_codec(Codec::Identity, scheme_attr_factory(0x01)) + .with_local_codec(Codec::Identity, scheme_attr_factory(0x02)) + .build() + .unwrap(); + assert_eq!(attr.scheme().unwrap(), 0x02); + } + + #[test] + fn test_disclosure_factory_never_consulted() { + let ms = custom_ms(); + let hits = Arc::new(AtomicUsize::new(0)); + let disclosure = ViewBuilder::new(&ms) + .disclosure() + .with_local_codec( + Codec::Identity, + Box::new({ + let hits = hits.clone(); + move |_: &Multisig| { + hits.fetch_add(1, Ordering::SeqCst); + let view: Box = Box::new(DisclosureSentinel); + Ok(view) + } + }), + ) + .build() + .unwrap(); + assert_eq!(hits.load(Ordering::SeqCst), 0); + // The built-in disclosure view answers, not the sentinel. + assert!(matches!( + disclosure.disclosure_mode().unwrap(), + ThresholdDisclosure::Full + )); + } + + #[test] + fn test_builder_send_sync() { + fn assert_send_sync() {} + fn assert_send_sync_value(_: &T) {} + + assert_send_sync::>(); + assert_send_sync::>(); + assert_send_sync::>(); + assert_send_sync::>(); + assert_send_sync::>(); + assert_send_sync::>(); + assert_send_sync::>(); + + let ms = custom_ms(); + let plain = ViewBuilder::new(&ms).attr(); + let with_factory = ViewBuilder::new(&ms) + .attr() + .with_local_codec(Codec::Identity, scheme_attr_factory(0x01)); + assert_send_sync_value(&plain); + assert_send_sync_value(&with_factory); + } + + #[test] + fn test_factory_hrtb_closure_feasibility() { + // A factory may return a view that borrows the multisig. The helper + // function pins the lifetime so closure inference stays simple. + fn borrowed_data_view(ms: &Multisig) -> Box { + Box::new(BorrowedDataView(ms)) + } + + let ms = Builder::new(Codec::Identity) + .with_message_bytes(&[0xCCu8; 3]) + .with_signature_bytes(&[0u8; 64]) + .try_build() + .unwrap(); + let data = ViewBuilder::new(&ms) + .data() + .with_local_codec( + Codec::Identity, + Box::new(|ms: &Multisig| Ok(borrowed_data_view(ms))), + ) + .build() + .unwrap(); + assert_eq!(data.sig_bytes().unwrap(), vec![0xCCu8; 3]); + } +} From 575e664f1ea37639b7b6654890178f937ff9c091 Mon Sep 17 00:00:00 2001 From: Dave Grantham Date: Wed, 7 Oct 2026 09:30:43 -0600 Subject: [PATCH 3/7] deprecate the `Views` trait Signed-off-by: Dave Grantham --- src/lib.rs | 7 +++- src/ms.rs | 12 +++++-- src/views.rs | 6 ++++ src/views/bls12381.rs | 64 ++++++++++++++++++++----------------- src/views/ed25519.rs | 5 +-- src/views/lamport.rs | 6 ++-- src/views/lamport_merkle.rs | 20 ++++++++---- src/views/nist_p.rs | 5 +-- src/views/rsa.rs | 5 +-- src/views/secp256k1.rs | 5 +-- 10 files changed, 85 insertions(+), 50 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 6eee958..bd54b72 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -151,7 +151,7 @@ pub mod views; pub use views::{ AttrView, ConvView, DataView, MAX_THRESHOLD_PARTICIPANTS, ThresholdAttrView, ThresholdDisclosure, ThresholdDisclosureView, ThresholdMetaCipher, ThresholdMetadata, - ThresholdView, Views, decrypt_threshold_meta, encrypt_threshold_meta, generate_meta_key, + ThresholdView, decrypt_threshold_meta, encrypt_threshold_meta, generate_meta_key, }; /// Builder-pattern view creation @@ -161,6 +161,11 @@ 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; diff --git a/src/ms.rs b/src/ms.rs index 6dadcb9..9af77c8 100644 --- a/src/ms.rs +++ b/src/ms.rs @@ -1,12 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 use crate::{ - AttrId, AttrView, ConvView, DataView, Error, ThresholdAttrView, ThresholdView, Views, + AttrId, AttrView, ConvView, DataView, Error, ThresholdAttrView, ThresholdView, views::{ ThresholdDisclosure, ThresholdDisclosureView, bls12381::{self, SchemeTypeId}, dispatch, secp256k1, threshold_meta, }, }; +// `Views` is deprecated; this import supports the deprecated delegating impl. +#[allow(deprecated)] +use crate::Views; use blsful::{ Signature, SignatureShare, inner_types::{GroupEncoding, PrimeField}, @@ -368,6 +371,8 @@ 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> { @@ -788,7 +793,7 @@ impl Builder { if let Some(shares) = self.shares { for share in &shares { ms = { - let tv = ms.threshold_view()?; + let tv = dispatch::dispatch_threshold_view(&ms)?; tv.add_share(share)? }; } @@ -800,6 +805,9 @@ impl Builder { } #[cfg(test)] +// These tests still exercise the deprecated `Views` trait; remove this +// allowance when the module migrates to `ViewBuilder`. +#[allow(deprecated)] mod tests { use super::*; diff --git a/src/views.rs b/src/views.rs index 85fb966..6c1e7df 100644 --- a/src/views.rs +++ b/src/views.rs @@ -124,6 +124,12 @@ pub trait ThresholdDisclosureView { } /// trait for getting the other views +/// +/// Deprecated: create views with `ViewBuilder` instead. +#[deprecated( + since = "1.5.0", + note = "use ViewBuilder; this trait will be removed in 2.0.0" +)] pub trait Views { /// Provide a read-only view to access the signature attributes fn attr_view<'a>(&'a self) -> Result, Error>; diff --git a/src/views/bls12381.rs b/src/views/bls12381.rs index 5c2bb94..430d1b2 100644 --- a/src/views/bls12381.rs +++ b/src/views/bls12381.rs @@ -1,9 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 use crate::{ AttrId, AttrView, Builder, ConvView, DataView, Error, Multisig, ThresholdAttrView, - ThresholdView, Views, + ThresholdView, error::{AttributesError, ConversionsError, SharesError}, - views::threshold_meta::{self, ThresholdDisclosure}, + views::{ + dispatch::{ + dispatch_attr_view, dispatch_data_view, dispatch_disclosure_view, + dispatch_threshold_attr_view, + }, + threshold_meta::{self, ThresholdDisclosure}, + }, }; use blsful::{ Bls12381G1Impl, Bls12381G2Impl, Signature, SignatureSchemes, SignatureShare, @@ -392,11 +398,11 @@ impl<'a> ConvView for View<'a> { /// convert to SSH signature format fn to_ssh_signature(&self) -> Result { // get the signature data - let dv = self.ms.data_view()?; + let dv = dispatch_data_view(self.ms)?; let sig_bytes = dv.sig_bytes()?; // get the scheme - let av = self.ms.attr_view()?; + let av = dispatch_attr_view(self.ms)?; let scheme_type = SchemeTypeId::try_from(av.scheme()?)?; match self.ms.codec { @@ -428,7 +434,7 @@ impl<'a> ConvView for View<'a> { } Codec::Bls12381G1ShareMsig => { // get the threshold attributes - let av = self.ms.threshold_attr_view()?; + let av = dispatch_threshold_attr_view(self.ms)?; let threshold = av.threshold()?; let limit = av.limit()?; let identifier_bytes = av.identifier()?; @@ -465,7 +471,7 @@ impl<'a> ConvView for View<'a> { } Codec::Bls12381G2ShareMsig => { // get the threshold attributes - let av = self.ms.threshold_attr_view()?; + let av = dispatch_threshold_attr_view(self.ms)?; let threshold = av.threshold()?; let limit = av.limit()?; let identifier_bytes = av.identifier()?; @@ -565,7 +571,7 @@ impl<'a> ThresholdView for View<'a> { // current Multisig threshold data let threshold_data = { - let av = self.ms.threshold_attr_view()?; + let av = dispatch_threshold_attr_view(self.ms)?; match av.threshold_data() { Ok(b) => ThresholdData::try_from(b) .map_err(|e| SharesError::InvalidThresholdData(e.to_string()))?, @@ -582,7 +588,7 @@ impl<'a> ThresholdView for View<'a> { .values() .try_for_each(|share| -> Result<(), Error> { let encoding = { - let av = self.ms.attr_view()?; + let av = dispatch_attr_view(self.ms)?; av.payload_encoding()? }; // build a multisig share out of the share, preserve the message @@ -616,10 +622,10 @@ impl<'a> ThresholdView for View<'a> { let (sdata, identifier, threshold, limit, encoding) = { // get the scheme - let av = share.attr_view()?; + let av = dispatch_attr_view(share)?; let scheme_type = SchemeTypeId::try_from(av.scheme()?)?; // get the share's attributes - let av = share.threshold_attr_view()?; + let av = dispatch_threshold_attr_view(share)?; let threshold = av.threshold()?; let limit = av.limit()?; let identifier_bytes = av.identifier()?; @@ -637,11 +643,11 @@ impl<'a> ThresholdView for View<'a> { ); // get the share's signature data - let dv = share.data_view()?; + let dv = dispatch_data_view(share)?; let sig_bytes = dv.sig_bytes()?; let encoding = { - let av = self.ms.attr_view()?; + let av = dispatch_attr_view(self.ms)?; av.payload_encoding().ok() }; @@ -657,7 +663,7 @@ impl<'a> ThresholdView for View<'a> { // update the threshold data let threshold_data: Vec = { - let av = self.ms.threshold_attr_view()?; + let av = dispatch_threshold_attr_view(self.ms)?; let mut tdata = match av.threshold_data() { Ok(b) => ThresholdData::try_from(b) .map_err(|e| SharesError::InvalidThresholdData(e.to_string()))?, @@ -674,7 +680,7 @@ impl<'a> ThresholdView for View<'a> { // get the payload encoding let encoding = { - let av = self.ms.attr_view()?; + let av = dispatch_attr_view(self.ms)?; // if this multisig doesn't have payload encoding set, set it to // the value from the first share added match av.payload_encoding() { @@ -685,7 +691,7 @@ impl<'a> ThresholdView for View<'a> { // if this multisig doesn't already have the threshold/limit set then // set it to match the values from the first share added - let av = share.threshold_attr_view()?; + let av = dispatch_threshold_attr_view(share)?; let threshold = av.threshold().unwrap_or(threshold); let limit = av.limit().unwrap_or(limit); @@ -705,7 +711,7 @@ impl<'a> ThresholdView for View<'a> { fn combine(&self) -> Result { // current Multisig threshold data let threshold_data = { - let av = self.ms.threshold_attr_view()?; + let av = dispatch_threshold_attr_view(self.ms)?; match av.threshold_data() { Ok(b) => ThresholdData::try_from(b) .map_err(|e| SharesError::InvalidThresholdData(e.to_string()))?, @@ -715,7 +721,7 @@ impl<'a> ThresholdView for View<'a> { // check that we have enough shares to combine let num_shares = threshold_data.0.len(); - let av = self.ms.threshold_attr_view()?; + let av = dispatch_threshold_attr_view(self.ms)?; if num_shares < av.threshold()? { return Err(SharesError::NotEnoughShares.into()); } @@ -759,7 +765,7 @@ impl<'a> ThresholdView for View<'a> { let sig = Signature::from_shares(shares.as_slice()) .map_err(|e| SharesError::ShareCombineFailed(e.to_string()))?; let encoding = { - let av = self.ms.attr_view()?; + let av = dispatch_attr_view(self.ms)?; av.payload_encoding()? }; Builder::new_from_bls_signature_with_codec(self.ms.codec, &sig)? @@ -805,7 +811,7 @@ impl<'a> ThresholdView for View<'a> { let sig = Signature::from_shares(shares.as_slice()) .map_err(|e| SharesError::ShareCombineFailed(e.to_string()))?; let encoding = { - let av = self.ms.attr_view()?; + let av = dispatch_attr_view(self.ms)?; av.payload_encoding()? }; Builder::new_from_bls_signature_with_codec(self.ms.codec, &sig)? @@ -826,7 +832,7 @@ impl<'a> ThresholdView for View<'a> { let shares = self.shares()?; shares .iter() - .map(|s| s.disclosure_view()?.to_disclosure(mode, meta_key, None)) + .map(|s| dispatch_disclosure_view(s)?.to_disclosure(mode, meta_key, None)) .collect() } @@ -839,9 +845,9 @@ impl<'a> ThresholdView for View<'a> { let (share_t, share_n) = threshold_meta::read_threshold_params(share, meta_key)?; let (sdata, identifier, encoding) = { - let av = share.attr_view()?; + let av = dispatch_attr_view(share)?; let scheme_type = SchemeTypeId::try_from(av.scheme()?)?; - let tav = share.threshold_attr_view()?; + let tav = dispatch_threshold_attr_view(share)?; let identifier_bytes = tav.identifier()?; if identifier_bytes.len() != 32 { return Err(Error::FailedConversion( @@ -855,10 +861,10 @@ impl<'a> ThresholdView for View<'a> { Error::FailedConversion("Incorrect identifier bytes".to_string()), )?, ); - let dv = share.data_view()?; + let dv = dispatch_data_view(share)?; let sig_bytes = dv.sig_bytes()?; let encoding = { - let av = self.ms.attr_view()?; + let av = dispatch_attr_view(self.ms)?; av.payload_encoding().ok() }; ( @@ -869,7 +875,7 @@ impl<'a> ThresholdView for View<'a> { }; let threshold_data: Vec = { - let av = self.ms.threshold_attr_view()?; + let av = dispatch_threshold_attr_view(self.ms)?; let mut tdata = match av.threshold_data() { Ok(b) => ThresholdData::try_from(b) .map_err(|e| SharesError::InvalidThresholdData(e.to_string()))?, @@ -883,7 +889,7 @@ impl<'a> ThresholdView for View<'a> { }; let encoding = { - let av = self.ms.attr_view()?; + let av = dispatch_attr_view(self.ms)?; match av.payload_encoding() { Ok(encoding) => Some(encoding), Err(_) => encoding, @@ -908,7 +914,7 @@ impl<'a> ThresholdView for View<'a> { let (threshold, _limit) = threshold_meta::read_threshold_params(self.ms, meta_key)?; let threshold_data = { - let av = self.ms.threshold_attr_view()?; + let av = dispatch_threshold_attr_view(self.ms)?; match av.threshold_data() { Ok(b) => ThresholdData::try_from(b) .map_err(|e| SharesError::InvalidThresholdData(e.to_string()))?, @@ -959,7 +965,7 @@ impl<'a> ThresholdView for View<'a> { let sig = Signature::from_shares(shares.as_slice()) .map_err(|e| SharesError::ShareCombineFailed(e.to_string()))?; let encoding = { - let av = self.ms.attr_view()?; + let av = dispatch_attr_view(self.ms)?; av.payload_encoding()? }; Builder::new_from_bls_signature_with_codec(self.ms.codec, &sig)? @@ -1004,7 +1010,7 @@ impl<'a> ThresholdView for View<'a> { let sig = Signature::from_shares(shares.as_slice()) .map_err(|e| SharesError::ShareCombineFailed(e.to_string()))?; let encoding = { - let av = self.ms.attr_view()?; + let av = dispatch_attr_view(self.ms)?; av.payload_encoding()? }; Builder::new_from_bls_signature_with_codec(self.ms.codec, &sig)? diff --git a/src/views/ed25519.rs b/src/views/ed25519.rs index 0d7895e..bfff617 100644 --- a/src/views/ed25519.rs +++ b/src/views/ed25519.rs @@ -1,7 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 use crate::{ - AttrId, AttrView, ConvView, DataView, Error, Multisig, Views, + AttrId, AttrView, ConvView, DataView, Error, Multisig, error::{AttributesError, ConversionsError}, + views::dispatch::dispatch_data_view, }; use multi_codec::Codec; @@ -52,7 +53,7 @@ impl<'a> ConvView for View<'a> { /// convert to SSH signature format fn to_ssh_signature(&self) -> Result { // get the signature data - let dv = self.ms.data_view()?; + let dv = dispatch_data_view(self.ms)?; let sig_bytes = dv.sig_bytes()?; Ok( ssh_key::Signature::new(ssh_key::Algorithm::Ed25519, sig_bytes) diff --git a/src/views/lamport.rs b/src/views/lamport.rs index 53124e3..e532a9e 100644 --- a/src/views/lamport.rs +++ b/src/views/lamport.rs @@ -12,9 +12,9 @@ use crate::{ AttrId, AttrView, Builder, ConvView, DataView, Error, Multisig, ThresholdAttrView, - ThresholdView, Views, + ThresholdView, error::{AttributesError, SharesError}, - views::ThresholdDisclosure, + views::{ThresholdDisclosure, dispatch::dispatch_data_view}, }; use blake2::{Blake2b512, Blake2s256}; use lamport_signature_plus::{ @@ -245,7 +245,7 @@ impl<'a> ThresholdView for View<'a> { /// Add a Lamport signature share to the accumulator. fn add_share(&self, share: &Multisig) -> Result { share_codec(self.ms.codec)?; - let blob = share.data_view()?.sig_bytes()?; + let blob = dispatch_data_view(share)?.sig_bytes()?; let mut blobs = accumulated(self.ms)?; blobs.push(blob); Builder::new(self.ms.codec) diff --git a/src/views/lamport_merkle.rs b/src/views/lamport_merkle.rs index bf4a6ee..f4dc562 100644 --- a/src/views/lamport_merkle.rs +++ b/src/views/lamport_merkle.rs @@ -14,13 +14,16 @@ use crate::{ AttrId, AttrView, Builder, ConvView, DataView, Error, Multisig, ThresholdAttrView, - ThresholdView, Views, + ThresholdView, error::{AttributesError, SharesError}, - views::ThresholdDisclosure, - views::lamport::{ - Blake2b512Digest, Blake2s256Digest, Blake3_256Digest, Sha2_256Digest, Sha2_384Digest, - Sha2_512Digest, Sha3_256Digest, Sha3_384Digest, Sha3_512Digest, Shake128Digest, - Shake256Digest, + views::{ + ThresholdDisclosure, + dispatch::dispatch_data_view, + lamport::{ + Blake2b512Digest, Blake2s256Digest, Blake3_256Digest, Sha2_256Digest, Sha2_384Digest, + Sha2_512Digest, Sha3_256Digest, Sha3_384Digest, Sha3_512Digest, Shake128Digest, + Shake256Digest, + }, }, }; use lamport_signature_plus::{LamportDigest, MtSignature, MtSignatureShare}; @@ -266,7 +269,7 @@ impl<'a> ThresholdView for View<'a> { if share.codec() != share_codec { return Err(SharesError::ShareTypeMismatch.into()); } - let blob = share.data_view()?.sig_bytes()?; + let blob = dispatch_data_view(share)?.sig_bytes()?; let blobs = accumulated(self.ms)?; let expected = accumulator_depth(self.ms, &blobs)?; let depth = check_share_depth(expected, &blob)?; @@ -311,6 +314,9 @@ impl<'a> ThresholdView for View<'a> { } #[cfg(test)] +// These tests still exercise the deprecated `Views` trait; remove this +// allowance when the module migrates to `ViewBuilder`. +#[allow(deprecated)] mod tests { use super::*; use crate::views::Views as _; diff --git a/src/views/nist_p.rs b/src/views/nist_p.rs index 1484e09..5ee31b9 100644 --- a/src/views/nist_p.rs +++ b/src/views/nist_p.rs @@ -2,8 +2,9 @@ //! NIST P-256/P-384/P-521 ECDSA multisig view. use crate::{ - AttrId, AttrView, ConvView, DataView, Error, Multisig, Views, + AttrId, AttrView, ConvView, DataView, Error, Multisig, error::{AttributesError, ConversionsError}, + views::dispatch::dispatch_data_view, }; use multi_codec::Codec; @@ -57,7 +58,7 @@ impl<'a> DataView for View<'a> { impl<'a> ConvView for View<'a> { fn to_ssh_signature(&self) -> Result { - let dv = self.ms.data_view()?; + let dv = dispatch_data_view(self.ms)?; let sig_bytes = dv.sig_bytes()?; let algo_name = algorithm_name(self.ms.codec); Ok(ssh_key::Signature::new( diff --git a/src/views/rsa.rs b/src/views/rsa.rs index d0f6ee2..764226e 100644 --- a/src/views/rsa.rs +++ b/src/views/rsa.rs @@ -2,8 +2,9 @@ //! RSA-SHA256 multisig view. use crate::{ - AttrId, AttrView, ConvView, DataView, Error, Multisig, Views, + AttrId, AttrView, ConvView, DataView, Error, Multisig, error::{AttributesError, ConversionsError}, + views::dispatch::dispatch_data_view, }; use multi_codec::Codec; @@ -50,7 +51,7 @@ impl<'a> DataView for View<'a> { impl<'a> ConvView for View<'a> { fn to_ssh_signature(&self) -> Result { - let dv = self.ms.data_view()?; + let dv = dispatch_data_view(self.ms)?; let sig_bytes = dv.sig_bytes()?; Ok(ssh_key::Signature::new( ssh_key::Algorithm::Other( diff --git a/src/views/secp256k1.rs b/src/views/secp256k1.rs index 9c1f2de..6cde543 100644 --- a/src/views/secp256k1.rs +++ b/src/views/secp256k1.rs @@ -1,7 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 use crate::{ - AttrId, AttrView, ConvView, DataView, Error, Multisig, Views, + AttrId, AttrView, ConvView, DataView, Error, Multisig, error::{AttributesError, ConversionsError}, + views::dispatch::dispatch_data_view, }; use multi_codec::Codec; @@ -55,7 +56,7 @@ impl<'a> ConvView for View<'a> { /// convert to SSH signature format fn to_ssh_signature(&self) -> Result { // get the signature data - let dv = self.ms.data_view()?; + let dv = dispatch_data_view(self.ms)?; let sig_bytes = dv.sig_bytes()?; Ok(ssh_key::Signature::new( ssh_key::Algorithm::Other( From 2af02bedc452ace0c8b73c1ddac9ab3f62350eb2 Mon Sep 17 00:00:00 2001 From: Dave Grantham Date: Wed, 7 Oct 2026 14:08:18 -0600 Subject: [PATCH 4/7] add custom codec Signed-off-by: Dave Grantham --- src/views/builder.rs | 43 ++- tests/custom_codec_tests.rs | 540 ++++++++++++++++++++++++++++++++++++ 2 files changed, 581 insertions(+), 2 deletions(-) create mode 100644 tests/custom_codec_tests.rs diff --git a/src/views/builder.rs b/src/views/builder.rs index 0daa48c..f962e8b 100644 --- a/src/views/builder.rs +++ b/src/views/builder.rs @@ -76,9 +76,40 @@ //! lifetime-parameterized helper function keeps closure inference simple //! for that case; see the unit tests for the pattern. //! +//! # Custom signature schemes +//! +//! A custom scheme is a signature scheme this crate does not standardize +//! yet, identified by a codec outside [`SIG_CODECS`](crate::SIG_CODECS). +//! Build its [`Multisig`] with the existing public [`Builder`](crate::Builder) +//! API alone: [`Builder::new`](crate::Builder::new) accepts any +//! `multi_codec::Codec`, and +//! [`Builder::with_signature_bytes`](crate::Builder::with_signature_bytes), +//! [`Builder::with_payload_encoding`](crate::Builder::with_payload_encoding), +//! and [`Builder::with_scheme`](crate::Builder::with_scheme) store their +//! attributes generically. No dedicated custom-codec setters exist, and +//! none are needed. The wire encoder carries arbitrary attributes, so the +//! built `Multisig` roundtrips through encode and decode unchanged. Views +//! for the custom scheme come from `with_local_codec` factories on +//! built-in fallthrough. +//! //! The demonstration slot for a custom scheme is [`Codec::Identity`] -//! (codec code 0), which no built-in dispatch table covers. Schemes that -//! share a slot disambiguate through attributes inside the factory. +//! (codec code 0), which no built-in dispatch table covers and which the +//! companion `multi-key` crate uses for custom protocol keys. The +//! integration tests in `tests/custom_codec_tests.rs` exercise the flow +//! end to end, including the wire roundtrip. +//! +//! # Custom schemes that share a codec slot +//! +//! Two custom schemes may share one unregistered codec slot. Their views +//! disambiguate inside the factory: the factory branches on the +//! [`AttrId::Scheme`](crate::AttrId::Scheme) attribute value, which +//! [`Builder::with_scheme`](crate::Builder::with_scheme) stores as a +//! varuint. This mirrors the multi-key convention of branching on the +//! algorithm name for custom protocol keys that share `Codec::Identity`. +//! The factory reads the attribute from the public +//! [`Multisig::attributes`](crate::Multisig::attributes) field. An unset +//! `Scheme` attribute yields `None` inside the factory; the factory then +//! chooses its own default or returns an error. //! //! # Cross-crate alignment //! @@ -245,6 +276,14 @@ impl ViewKind for DisclosureKind { /// /// Dispatch order: built-in view first, local factory second (on /// `AttributesError::UnsupportedCodec` fallthrough only), error last. +/// +/// For a custom signature scheme (a codec outside +/// [`SIG_CODECS`](crate::SIG_CODECS)), construct the [`Multisig`] with the +/// existing public [`Builder`](crate::Builder) setters and build its views +/// with `with_local_codec` factories on fallthrough. Schemes that share a +/// codec slot disambiguate by branching on the +/// [`AttrId::Scheme`](crate::AttrId::Scheme) attribute inside the factory. +/// See the module documentation for the convention. pub struct ViewBuilder<'ms, K: ViewKind> { ms: &'ms Multisig, kind: PhantomData, diff --git a/tests/custom_codec_tests.rs b/tests/custom_codec_tests.rs new file mode 100644 index 0000000..160267a --- /dev/null +++ b/tests/custom_codec_tests.rs @@ -0,0 +1,540 @@ +// SPDX-License-Identifier: Apache-2.0 +//! End-to-end tests for custom signature schemes on unregistered codecs. +//! +//! A custom scheme identifies itself with a codec outside `SIG_CODECS` +//! and constructs its [`Multisig`] through the existing public `Builder` +//! setters, so no dedicated custom-codec setters exist. The wire encoder +//! carries arbitrary attributes, which makes the container roundtrip +//! unchanged, and `ViewBuilder` local-codec factories supply the views on +//! built-in fallthrough. +//! +//! The tests use `Codec::Identity` (codec code 0) as the unregistered +//! demonstration slot, the convention the companion `multi-key` crate +//! uses for custom protocol keys. + +use multi_codec::Codec; +use multi_sig::error::AttributesError; +use multi_sig::{ + AttrId, AttrView, Builder, ConvView, DataView, Error, LocalAttrFn, LocalConvFn, LocalDataFn, + LocalDisclosureFn, LocalThresholdAttrFn, LocalThresholdFn, Multisig, ThresholdAttrView, + ThresholdDisclosure, ThresholdDisclosureView, ThresholdView, ViewBuilder, +}; +use multi_util::Varuint; +use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, +}; + +/// Attribute view that echoes the `Scheme` and `PayloadEncoding` +/// attributes the factory decoded from its `Multisig`. +struct CustomAttrView { + scheme: u8, + payload_encoding: Codec, +} + +impl AttrView for CustomAttrView { + fn payload_encoding(&self) -> Result { + Ok(self.payload_encoding) + } + + fn scheme(&self) -> Result { + Ok(self.scheme) + } +} + +/// First custom scheme sharing the `Identity` codec slot. Distinct from +/// the second scheme's view so a wrong factory branch cannot pass. +struct SchemeAAttr; + +impl AttrView for SchemeAAttr { + fn payload_encoding(&self) -> Result { + Ok(Codec::Raw) + } + + fn scheme(&self) -> Result { + Ok(0x2A) + } +} + +/// Second custom scheme sharing the `Identity` codec slot. +struct SchemeBAttr; + +impl AttrView for SchemeBAttr { + fn payload_encoding(&self) -> Result { + Ok(Codec::Identity) + } + + fn scheme(&self) -> Result { + Ok(0x2B) + } +} + +/// Data view that echoes the stored signature bytes. +struct CustomDataView(Vec); + +impl DataView for CustomDataView { + fn sig_bytes(&self) -> Result, Error> { + Ok(self.0.clone()) + } +} + +/// Conversion view for the custom scheme. Its marker error identifies the +/// factory output deterministically. +struct CustomConvView; + +impl ConvView for CustomConvView { + fn to_ssh_signature(&self) -> Result { + Err(Error::FailedConversion("custom scheme conv marker".into())) + } +} + +/// Threshold-attribute view that echoes the shared threshold attributes +/// the factory decoded from its `Multisig`. +struct CustomThresholdAttrView { + threshold: usize, + limit: usize, + identifier: Vec, + threshold_data: Vec, +} + +impl ThresholdAttrView for CustomThresholdAttrView { + fn threshold(&self) -> Result { + Ok(self.threshold) + } + + fn limit(&self) -> Result { + Ok(self.limit) + } + + fn identifier(&self) -> Result<&[u8], Error> { + Ok(&self.identifier) + } + + fn threshold_data(&self) -> Result<&[u8], Error> { + Ok(&self.threshold_data) + } +} + +/// Threshold view for the custom scheme: treats the `Multisig` the +/// factory received as a single share of itself. +struct CustomThresholdView(Multisig); + +impl ThresholdView for CustomThresholdView { + fn shares(&self) -> Result, Error> { + Ok(vec![self.0.clone()]) + } + + fn shares_with_disclosure( + &self, + _mode: ThresholdDisclosure, + _meta_key: Option<&[u8]>, + ) -> Result, Error> { + Ok(vec![self.0.clone()]) + } + + fn add_share(&self, share: &Multisig) -> Result { + Ok(share.clone()) + } + + fn add_share_with_meta( + &self, + share: &Multisig, + _meta_key: Option<&[u8]>, + ) -> Result { + Ok(share.clone()) + } + + fn combine(&self) -> Result { + Ok(self.0.clone()) + } + + fn combine_with_meta(&self, _meta_key: Option<&[u8]>) -> Result { + Ok(self.0.clone()) + } +} + +/// Disclosure view that would only answer if the built-in codec-agnostic +/// disclosure view were overridden. Its `Partial` mode differs from the +/// built-in `Full` mode so a consultation cannot go undetected. +struct CustomDisclosureView; + +impl ThresholdDisclosureView for CustomDisclosureView { + fn disclosure_mode(&self) -> Result { + Ok(ThresholdDisclosure::Partial) + } + + fn read_threshold_params(&self, _meta_key: Option<&[u8]>) -> Result<(usize, usize), Error> { + Ok((2, 3)) + } + + fn to_disclosure( + &self, + _target: ThresholdDisclosure, + _meta_key: Option<&[u8]>, + _current_meta_key: Option<&[u8]>, + ) -> Result { + Ok(Multisig::default()) + } +} + +/// Decode the `AttrId::Scheme` attribute the way built-in views do, as a +/// varuint-stored scheme value. An unset attribute yields `None`. +fn scheme_attr(ms: &Multisig) -> Option { + let bytes = ms.attributes.get(&AttrId::Scheme)?; + Some(*Varuint::::try_from(bytes.as_slice()).ok()?) +} + +/// Decode a varuint-stored `usize` attribute. An unset attribute yields +/// `None`. +fn usize_attr(ms: &Multisig, id: AttrId) -> Option { + let bytes = ms.attributes.get(&id)?; + Some(*Varuint::::try_from(bytes.as_slice()).ok()?) +} + +/// Decode the `AttrId::PayloadEncoding` attribute. An unset attribute +/// yields `None`. +fn payload_encoding_attr(ms: &Multisig) -> Option { + let bytes = ms.attributes.get(&AttrId::PayloadEncoding)?; + Codec::try_from(bytes.as_slice()).ok() +} + +/// Attribute factory for one custom scheme. It defaults to scheme `0` and +/// payload encoding `Codec::Identity` when the attributes are unset. +fn attr_factory() -> LocalAttrFn { + Box::new(|ms: &Multisig| { + let view: Box = Box::new(CustomAttrView { + scheme: scheme_attr(ms).unwrap_or(0), + payload_encoding: payload_encoding_attr(ms).unwrap_or(Codec::Identity), + }); + Ok(view) + }) +} + +/// One factory implementation that serves two custom schemes sharing the +/// `Identity` codec slot. It branches on the `Scheme` attribute value and +/// returns the scheme-specific view. +fn branching_attr_factory() -> LocalAttrFn { + Box::new(|ms: &Multisig| { + let view: Box = match scheme_attr(ms) { + Some(0x2A) => Box::new(SchemeAAttr), + Some(0x2B) => Box::new(SchemeBAttr), + _ => return Err(Error::Attributes(AttributesError::MissingScheme)), + }; + Ok(view) + }) +} + +/// Attribute factory that treats an unset `Scheme` attribute as an error +/// instead of a default. +fn failing_attr_factory() -> LocalAttrFn { + Box::new(|ms: &Multisig| { + let scheme = scheme_attr(ms).ok_or(Error::Attributes(AttributesError::MissingScheme))?; + let view: Box = Box::new(CustomAttrView { + scheme, + payload_encoding: Codec::Identity, + }); + Ok(view) + }) +} + +/// Data factory that echoes the `SigData` attribute of the received +/// `Multisig`. +fn data_factory() -> LocalDataFn { + Box::new(|ms: &Multisig| { + let data = ms + .attributes + .get(&AttrId::SigData) + .cloned() + .unwrap_or_default(); + let view: Box = Box::new(CustomDataView(data)); + Ok(view) + }) +} + +/// Data factory with a consultation counter and sentinel payload, used to +/// prove the factory is not consulted for a supported standard codec. +fn counting_data_factory(hits: Arc) -> LocalDataFn { + Box::new(move |_: &Multisig| { + hits.fetch_add(1, Ordering::SeqCst); + let view: Box = Box::new(CustomDataView(vec![0xEEu8])); + Ok(view) + }) +} + +/// Conversion factory that returns the marker conversion view. +fn conv_factory() -> LocalConvFn { + Box::new(|_: &Multisig| { + let view: Box = Box::new(CustomConvView); + Ok(view) + }) +} + +/// Threshold-attribute factory that echoes the shared threshold +/// attributes of the received `Multisig`. +fn threshold_attr_factory() -> LocalThresholdAttrFn { + Box::new(|ms: &Multisig| { + let view: Box = Box::new(CustomThresholdAttrView { + threshold: usize_attr(ms, AttrId::Threshold).unwrap_or(0), + limit: usize_attr(ms, AttrId::Limit).unwrap_or(0), + identifier: ms + .attributes + .get(&AttrId::ShareIdentifier) + .cloned() + .unwrap_or_default(), + threshold_data: ms + .attributes + .get(&AttrId::ThresholdData) + .cloned() + .unwrap_or_default(), + }); + Ok(view) + }) +} + +/// Threshold factory that holds the received `Multisig` as its share. +fn threshold_factory() -> LocalThresholdFn { + Box::new(|ms: &Multisig| { + let view: Box = Box::new(CustomThresholdView(ms.clone())); + Ok(view) + }) +} + +/// Disclosure factory with a consultation counter. The built-in +/// disclosure view is codec-agnostic, so this factory is never consulted. +fn disclosure_factory(hits: Arc) -> LocalDisclosureFn { + Box::new(move |_: &Multisig| { + hits.fetch_add(1, Ordering::SeqCst); + let view: Box = Box::new(CustomDisclosureView); + Ok(view) + }) +} + +/// A custom-scheme multisig on the demonstration slot, built through the +/// public `Builder` setters alone. +fn custom_ms() -> Multisig { + Builder::new(Codec::Identity) + .with_signature_bytes(&[0xA5u8; 32]) + .with_payload_encoding(Codec::Raw) + .with_scheme(0x2A) + .try_build() + .unwrap() +} + +/// A custom scheme that also stores the shared threshold attributes. +fn custom_share_ms() -> Multisig { + Builder::new(Codec::Identity) + .with_signature_bytes(&[0xA5u8; 32]) + .with_threshold(2) + .with_limit(3) + .with_identifier(b"custom-share-id") + .with_threshold_data(b"custom-threshold-data") + .try_build() + .unwrap() +} + +/// Extract the error from a view-build result; view trait objects carry +/// no `Debug` bound, so `unwrap_err` is unavailable there. +fn build_err(result: Result) -> Error { + match result { + Ok(_) => panic!("expected an error, got Ok"), + Err(err) => err, + } +} + +/// The custom-scheme container roundtrips through the wire format +/// losslessly: identical after decode, and byte-identical when +/// re-encoded. +#[test] +fn test_custom_codec_wire_roundtrip() { + let ms = custom_ms(); + let bytes: Vec = ms.clone().into(); + let decoded = Multisig::try_from(bytes.as_slice()).unwrap(); + assert_eq!(decoded, ms); + let reencoded: Vec = decoded.into(); + assert_eq!(reencoded, bytes); +} + +/// The attribute factory decodes the scheme and payload-encoding +/// attributes of the received custom-scheme multisig. +#[test] +fn test_custom_attr_view_reports_scheme_and_encoding() { + let ms = custom_ms(); + let attr = ViewBuilder::new(&ms) + .attr() + .with_local_codec(Codec::Identity, attr_factory()) + .build() + .unwrap(); + assert_eq!(attr.scheme().unwrap(), 0x2A); + assert_eq!(attr.payload_encoding().unwrap(), Codec::Raw); +} + +/// The data factory echoes the signature bytes of the received +/// custom-scheme multisig. +#[test] +fn test_custom_data_view_echoes_signature_bytes() { + let ms = custom_ms(); + let data = ViewBuilder::new(&ms) + .data() + .with_local_codec(Codec::Identity, data_factory()) + .build() + .unwrap(); + assert_eq!(data.sig_bytes().unwrap(), vec![0xA5u8; 32]); +} + +/// The conversion factory output is usable; its marker error identifies +/// it deterministically. +#[test] +fn test_custom_conv_view_factory_output() { + let ms = custom_ms(); + let conv = ViewBuilder::new(&ms) + .conv() + .with_local_codec(Codec::Identity, conv_factory()) + .build() + .unwrap(); + let err = conv.to_ssh_signature().unwrap_err(); + assert!(matches!(err, Error::FailedConversion(msg) if msg == "custom scheme conv marker")); +} + +/// The threshold-attribute factory reads the shared threshold attributes +/// the custom scheme stores. +#[test] +fn test_custom_threshold_attr_view_reads_attributes() { + let ms = custom_share_ms(); + let attr = ViewBuilder::new(&ms) + .threshold_attr() + .with_local_codec(Codec::Identity, threshold_attr_factory()) + .build() + .unwrap(); + assert_eq!(attr.threshold().unwrap(), 2); + assert_eq!(attr.limit().unwrap(), 3); + assert_eq!(attr.identifier().unwrap(), &b"custom-share-id"[..]); + assert_eq!( + attr.threshold_data().unwrap(), + &b"custom-threshold-data"[..] + ); +} + +/// The threshold factory receives the real container: it treats the +/// custom-scheme multisig as its own single share. +#[test] +fn test_custom_threshold_view_receives_multisig() { + let ms = custom_ms(); + let threshold = ViewBuilder::new(&ms) + .threshold() + .with_local_codec(Codec::Identity, threshold_factory()) + .build() + .unwrap(); + assert_eq!(threshold.combine().unwrap(), ms); + assert_eq!(threshold.shares().unwrap(), vec![ms.clone()]); + assert_eq!( + threshold + .shares_with_disclosure(ThresholdDisclosure::Full, None) + .unwrap(), + vec![ms.clone()] + ); +} + +/// The built-in disclosure view is codec-agnostic: the registered +/// factory is never consulted and the built-in `Full` mode answers. +#[test] +fn test_disclosure_factory_never_consulted() { + let ms = custom_ms(); + let hits = Arc::new(AtomicUsize::new(0)); + let disclosure = ViewBuilder::new(&ms) + .disclosure() + .with_local_codec(Codec::Identity, disclosure_factory(hits.clone())) + .build() + .unwrap(); + assert_eq!(hits.load(Ordering::SeqCst), 0); + assert!(matches!( + disclosure.disclosure_mode().unwrap(), + ThresholdDisclosure::Full + )); +} + +/// One factory implementation serves two custom schemes that share the +/// `Identity` slot by branching on the `Scheme` attribute; each multisig +/// reaches its own scheme-specific view. +#[test] +fn test_factory_branches_on_scheme_attribute() { + for (scheme_value, expected_encoding) in [(0x2Au8, Codec::Raw), (0x2Bu8, Codec::Identity)] { + let ms = Builder::new(Codec::Identity) + .with_signature_bytes(&[0xA5u8; 32]) + .with_scheme(scheme_value) + .try_build() + .unwrap(); + let attr = ViewBuilder::new(&ms) + .attr() + .with_local_codec(Codec::Identity, branching_attr_factory()) + .build() + .unwrap(); + assert_eq!(attr.scheme().unwrap(), scheme_value); + assert_eq!(attr.payload_encoding().unwrap(), expected_encoding); + } +} + +/// An unset `Scheme` attribute yields `None` inside the factory; this +/// factory's convention chooses its documented defaults. +#[test] +fn test_missing_scheme_default_branch() { + let ms = Builder::new(Codec::Identity) + .with_signature_bytes(&[0xA5u8; 32]) + .try_build() + .unwrap(); + let attr = ViewBuilder::new(&ms) + .attr() + .with_local_codec(Codec::Identity, attr_factory()) + .build() + .unwrap(); + assert_eq!(attr.scheme().unwrap(), 0); + assert_eq!(attr.payload_encoding().unwrap(), Codec::Identity); +} + +/// A factory error propagates unchanged, including a structured error +/// raised for an unset `Scheme` attribute. +#[test] +fn test_factory_error_propagates() { + let ms = Builder::new(Codec::Identity) + .with_signature_bytes(&[0xA5u8; 32]) + .try_build() + .unwrap(); + let err = build_err( + ViewBuilder::new(&ms) + .attr() + .with_local_codec(Codec::Identity, failing_attr_factory()) + .build(), + ); + assert!(matches!( + err, + Error::Attributes(AttributesError::MissingScheme) + )); +} + +/// A factory registered for a standard codec with built-in support is +/// never consulted; the built-in view answers with the real data. +#[test] +fn test_factory_not_consulted_for_standard_codec() { + let ms = Builder::new(Codec::EddsaMsig) + .with_signature_bytes(&[0xA5u8; 32]) + .try_build() + .unwrap(); + let hits = Arc::new(AtomicUsize::new(0)); + let data = ViewBuilder::new(&ms) + .data() + .with_local_codec(Codec::EddsaMsig, counting_data_factory(hits.clone())) + .build() + .unwrap(); + assert_eq!(hits.load(Ordering::SeqCst), 0); + assert_eq!(data.sig_bytes().unwrap(), vec![0xA5u8; 32]); +} + +/// The custom-scheme container passes a JSON roundtrip unchanged: the +/// human-readable serde path encodes attributes by name. +#[cfg(feature = "serde")] +#[test] +fn test_custom_codec_serde_roundtrip() { + let ms = custom_ms(); + let text = serde_json::to_string(&ms).unwrap(); + let decoded: Multisig = serde_json::from_str(&text).unwrap(); + assert_eq!(decoded, ms); +} From a5c17a3f1c830d0b5565425ba75062d2ff7effdb Mon Sep 17 00:00:00 2001 From: Dave Grantham Date: Wed, 7 Oct 2026 14:35:59 -0600 Subject: [PATCH 5/7] migrate all tests to `ViewBuilder` Signed-off-by: Dave Grantham --- src/ms.rs | 62 ++++++++++++++++++++----------------- src/views/lamport_merkle.rs | 60 ++++++++++++++++++++++++++++------- 2 files changed, 82 insertions(+), 40 deletions(-) diff --git a/src/ms.rs b/src/ms.rs index 9af77c8..e9f9760 100644 --- a/src/ms.rs +++ b/src/ms.rs @@ -805,11 +805,9 @@ impl Builder { } #[cfg(test)] -// These tests still exercise the deprecated `Views` trait; remove this -// allowance when the module migrates to `ViewBuilder`. -#[allow(deprecated)] mod tests { use super::*; + use crate::ViewBuilder; #[test] fn test_encoded() { @@ -855,7 +853,7 @@ mod tests { // Every listed codec must produce a working sign-data view. A // codec in SIG_CODECS that fails to dispatch here has drifted // from the view dispatch tables. - let result = ms.data_view(); + let result = ViewBuilder::new(&ms).data().build(); assert!( result.is_ok(), "SIG_CODECS entry {codec:?} does not dispatch to a data view (error kind {:?})", @@ -885,7 +883,6 @@ mod tests { } #[test] - #[allow(deprecated)] fn test_bls_signature() { let sk = blsful::Bls12381G2::new_secret_key(); let sig = sk @@ -895,7 +892,7 @@ mod tests { ) .unwrap(); - let ms = Builder::new_from_bls_signature(&sig) + let ms = Builder::new_from_bls_signature_with_codec(Codec::Bls12381G2Msig, &sig) .unwrap() .try_build() .unwrap(); @@ -905,7 +902,6 @@ mod tests { } #[test] - #[allow(deprecated)] fn test_bls_signature_combine() { let sk = blsful::Bls12381G2::new_secret_key(); let sig = sk @@ -915,7 +911,7 @@ mod tests { ) .unwrap(); - let ms1 = Builder::new_from_bls_signature(&sig) + let ms1 = Builder::new_from_bls_signature_with_codec(Codec::Bls12381G2Msig, &sig) .unwrap() .with_payload_encoding(Codec::Raw) .try_build() @@ -932,11 +928,16 @@ mod tests { ) .unwrap(); sigs.push( - Builder::new_from_bls_signature_share(3, 4, &sig) - .unwrap() - .with_payload_encoding(Codec::Raw) - .try_build() - .unwrap(), + Builder::new_from_bls_signature_share_with_codec( + Codec::Bls12381G2ShareMsig, + 3, + 4, + &sig, + ) + .unwrap() + .with_payload_encoding(Codec::Raw) + .try_build() + .unwrap(), ); }); @@ -947,11 +948,11 @@ mod tests { } let ms2 = builder.try_build().unwrap(); - let av = ms2.threshold_attr_view().unwrap(); + let av = ViewBuilder::new(&ms2).threshold_attr().build().unwrap(); assert_eq!(3, av.threshold().unwrap()); assert_eq!(4, av.limit().unwrap()); - let tv = ms2.threshold_view().unwrap(); + let tv = ViewBuilder::new(&ms2).threshold().build().unwrap(); let ms3 = tv.combine().unwrap(); assert_eq!(ms1, ms3); @@ -963,7 +964,7 @@ mod tests { .with_signature_bytes(&[0u8; 64]) .try_build() .unwrap(); - let cv = ms1.conv_view().unwrap(); + let cv = ViewBuilder::new(&ms1).conv().build().unwrap(); let ms_ssh = cv.to_ssh_signature().unwrap(); let ms2 = Builder::new_from_ssh_signature(&ms_ssh) .unwrap() @@ -978,7 +979,7 @@ mod tests { .with_signature_bytes(&[0u8; 64]) .try_build() .unwrap(); - let cv = ms1.conv_view().unwrap(); + let cv = ViewBuilder::new(&ms1).conv().build().unwrap(); let ms_ssh = cv.to_ssh_signature().unwrap(); let ms2 = Builder::new_from_ssh_signature(&ms_ssh) .unwrap() @@ -988,7 +989,6 @@ mod tests { } #[test] - #[allow(deprecated)] fn test_bls_signature_ssh_roundtrip() { let sk = blsful::Bls12381G1::new_secret_key(); let sig = sk @@ -998,12 +998,12 @@ mod tests { ) .unwrap(); - let ms1 = Builder::new_from_bls_signature(&sig) + let ms1 = Builder::new_from_bls_signature_with_codec(Codec::Bls12381G1Msig, &sig) .unwrap() .try_build() .unwrap(); - let cv = ms1.conv_view().unwrap(); + let cv = ViewBuilder::new(&ms1).conv().build().unwrap(); let ssh_ms = cv.to_ssh_signature().unwrap(); let ms2 = Builder::new_from_ssh_signature(&ssh_ms) @@ -1015,7 +1015,6 @@ mod tests { } #[test] - #[allow(deprecated)] fn test_bls_signature_combine_ssh_roundtrip() { let sk = blsful::Bls12381G2::new_secret_key(); let sig = sk @@ -1025,7 +1024,7 @@ mod tests { ) .unwrap(); - let ms1 = Builder::new_from_bls_signature(&sig) + let ms1 = Builder::new_from_bls_signature_with_codec(Codec::Bls12381G2Msig, &sig) .unwrap() .with_payload_encoding(Codec::Raw) .try_build() @@ -1042,11 +1041,16 @@ mod tests { ) .unwrap(); sigs.push({ - let ms = Builder::new_from_bls_signature_share(3, 4, &sig) - .unwrap() - .try_build() - .unwrap(); - let sc = ms.conv_view().unwrap(); + let ms = Builder::new_from_bls_signature_share_with_codec( + Codec::Bls12381G2ShareMsig, + 3, + 4, + &sig, + ) + .unwrap() + .try_build() + .unwrap(); + let sc = ViewBuilder::new(&ms).conv().build().unwrap(); sc.to_ssh_signature().unwrap() }); }); @@ -1062,11 +1066,11 @@ mod tests { } let ms2 = builder.try_build().unwrap(); - let av = ms2.threshold_attr_view().unwrap(); + let av = ViewBuilder::new(&ms2).threshold_attr().build().unwrap(); assert_eq!(3, av.threshold().unwrap()); assert_eq!(4, av.limit().unwrap()); - let tv = ms2.threshold_view().unwrap(); + let tv = ViewBuilder::new(&ms2).threshold().build().unwrap(); let ms3 = tv.combine().unwrap(); assert_eq!(ms1, ms3); diff --git a/src/views/lamport_merkle.rs b/src/views/lamport_merkle.rs index f4dc562..a6441ac 100644 --- a/src/views/lamport_merkle.rs +++ b/src/views/lamport_merkle.rs @@ -314,12 +314,9 @@ impl<'a> ThresholdView for View<'a> { } #[cfg(test)] -// These tests still exercise the deprecated `Views` trait; remove this -// allowance when the module migrates to `ViewBuilder`. -#[allow(deprecated)] mod tests { use super::*; - use crate::views::Views as _; + use crate::ViewBuilder; use lamport_signature_plus::MtVerifyingKey; type MtSha2_256Digest = lamport_signature_plus::LamportFixedDigest; @@ -380,26 +377,46 @@ mod tests { .unwrap(); assert!(acc.depth().is_none()); for share_ms in &share_ms { - let next = acc.threshold_view().unwrap().add_share(share_ms).unwrap(); + let next = ViewBuilder::new(&acc) + .threshold() + .build() + .unwrap() + .add_share(share_ms) + .unwrap(); acc = next; } // depth propagated from the share blobs assert_eq!(acc.depth(), Some(1)); // shares() roundtrip - let recovered = acc.threshold_view().unwrap().shares().unwrap(); + let recovered = ViewBuilder::new(&acc) + .threshold() + .build() + .unwrap() + .shares() + .unwrap(); assert_eq!(recovered.len(), 2); assert_eq!(recovered[0].depth(), Some(1)); // combine into a full signature - let combined = acc.threshold_view().unwrap().combine().unwrap(); + let combined = ViewBuilder::new(&acc) + .threshold() + .build() + .unwrap() + .combine() + .unwrap(); assert_eq!(combined.codec(), Codec::LamportMerkleSha2256Sig); assert_eq!(combined.depth(), Some(1)); assert_eq!(combined.message, msg.to_vec()); // verify under the tree root let pk = MtVerifyingKey::::from_bytes(&pk_bytes).unwrap(); - let sig_bytes = combined.data_view().unwrap().sig_bytes().unwrap(); + let sig_bytes = ViewBuilder::new(&combined) + .data() + .build() + .unwrap() + .sig_bytes() + .unwrap(); let sig = MtSignature::::from_bytes(&sig_bytes).unwrap(); pk.verify(&sig, msg).unwrap(); } @@ -433,14 +450,28 @@ mod tests { .with_depth(2) .try_build() .unwrap(); - assert!(acc2.threshold_view().unwrap().add_share(&share_ms).is_err()); + assert!( + ViewBuilder::new(&acc2) + .threshold() + .build() + .unwrap() + .add_share(&share_ms) + .is_err() + ); // sanity: the honest accumulator accepts the honest share let _ = acc; let ok = Builder::new(Codec::LamportMerkleSha2256Sig) .with_message_bytes(&b"m".to_vec()) .try_build() .unwrap(); - assert!(ok.threshold_view().unwrap().add_share(&share_ms).is_ok()); + assert!( + ViewBuilder::new(&ok) + .threshold() + .build() + .unwrap() + .add_share(&share_ms) + .is_ok() + ); } #[test] @@ -449,6 +480,13 @@ mod tests { .with_message_bytes(&b"m".to_vec()) .try_build() .unwrap(); - assert!(acc.threshold_view().unwrap().combine().is_err()); + assert!( + ViewBuilder::new(&acc) + .threshold() + .build() + .unwrap() + .combine() + .is_err() + ); } } From f7189ba8e9dd5ae1443cc9158d0233f4b7d3429c Mon Sep 17 00:00:00 2001 From: Dave Grantham Date: Wed, 7 Oct 2026 15:02:41 -0600 Subject: [PATCH 6/7] update docs Signed-off-by: Dave Grantham --- README.md | 155 ++++++++++++++++++++++++++++++++++++------- src/lib.rs | 29 +++++++- src/views.rs | 20 +++++- src/views/builder.rs | 20 ++++-- 4 files changed, 191 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index 98c87ee..d4a92d3 100644 --- a/README.md +++ b/README.md @@ -126,6 +126,85 @@ Each Multisig carries a set of attributes identified by a `u8` code: To provide an abstract interface to digital signatures of all schemes, this crate gives "views" on the Multisig data. These are read-only or copy-on-write abstract interfaces with implementations for different supporting signature protocols. +### Creating Views + +Create views through the builder-pattern `multi_sig::ViewBuilder` (re-exported at the crate root and in the prelude). Select a view kind fluently, then build: + +```rust +use multi_sig::{Builder, ViewBuilder}; +use multi_codec::Codec; + +let sig_data = vec![0u8; 64]; +let ms = Builder::new(Codec::EddsaMsig) + .with_signature_bytes(&sig_data) + .try_build() + .unwrap(); + +// a data view reads the signature bytes +let data = ViewBuilder::new(&ms).data().build().unwrap(); +assert_eq!(data.sig_bytes().unwrap(), sig_data); + +// an attributes view reads the payload encoding and the scheme +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. + +`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. + +### Custom Signature Schemes + +A custom scheme is a signature scheme this crate does not standardize yet. It carries a codec outside `SIG_CODECS`. The convention uses the `Codec::Identity` codec slot (code 0), which no built-in dispatch table covers. Construct the `Multisig` with the existing public `Builder` setters. `Builder::new` accepts any codec. `with_signature_bytes`, `with_payload_encoding`, and `with_scheme` store their attributes generically. A custom scheme has no built-in views, so `ViewBuilder` dispatches it to caller-supplied local-codec factories registered with `with_local_codec`: + +```rust +use multi_sig::{AttrId, AttrView, Builder, Error, Multisig, ViewBuilder}; +use multi_codec::Codec; +use multi_util::Varuint; + +// a custom scheme uses the Codec::Identity slot. The public Builder +// setters store its attributes generically +let ms = Builder::new(Codec::Identity) + .with_signature_bytes(b"my-custom-signature".as_slice()) + .with_scheme(0x2A) + .try_build() + .unwrap(); + +struct CustomAttrsView { + scheme: u8, +} + +impl AttrView for CustomAttrsView { + fn payload_encoding(&self) -> Result { + Ok(Codec::Identity) + } + fn scheme(&self) -> Result { + Ok(self.scheme) + } +} + +// the factory reads the AttrId::Scheme attribute (stored as a varuint) +// and serves its own scheme. Schemes that share the Identity codec slot +// branch on this attribute inside the factory. +let attrs = ViewBuilder::new(&ms) + .attr() + .with_local_codec(Codec::Identity, Box::new(|ms: &Multisig| { + let scheme = ms + .attributes + .get(&AttrId::Scheme) + .and_then(|bytes| Varuint::::try_from(bytes.as_slice()).ok()) + .map(|decoded| *decoded) + .unwrap_or(0); + let view: Box = Box::new(CustomAttrsView { scheme }); + Ok(view) + })) + .build() + .unwrap(); +assert_eq!(attrs.scheme().unwrap(), 0x2A); +``` + +Built-in views always win: a factory registered for a codec that has a built-in view is never consulted. A repeat `with_local_codec` call for the same kind replaces the earlier factory: the last registration wins. Factory errors propagate unchanged. The `disclosure` view is codec-agnostic, so a factory registered for that kind is never consulted. The wire encoder carries arbitrary attributes, so the built `Multisig` roundtrips through encode and decode unchanged. The tests in `tests/custom_codec_tests.rs` exercise this flow end to end. + ### View Traits | Trait | Methods | Purpose | @@ -136,7 +215,7 @@ To provide an abstract interface to digital signatures of all schemes, this crat | `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) | | `ThresholdDisclosureView` | `disclosure_mode()`, `read_threshold_params()`, `to_disclosure()` | Read or convert the threshold disclosure mode (all codecs) | -| `Views` | `attr_view()`, `data_view()`, `conv_view()`, `threshold_attr_view()`, `threshold_view()`, `disclosure_view()` | Dispatcher trait — obtain any view from a `Multisig` | +| `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 @@ -154,7 +233,7 @@ To provide an abstract interface to digital signatures of all schemes, this crat | Ed25519-MAYO2 | `ed25519_mayo2::View` | `ed25519_mayo2::View` | `ed25519_mayo2::View` | — | — | | Other hybrids | `ed25519_hybrid::View` | `ed25519_hybrid::View` | `ed25519_hybrid::View` | — | — | -The `disclosure_view()` method is codec-agnostic. It is available on all codecs. +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. ### Copy-on-Write Semantics @@ -164,8 +243,8 @@ Operations that appear to mutate the Multisig (`add_share`, `combine`, `to_discl let mut ms = Builder::new(Codec::Bls12381G2Msig).try_build()?; for share in &shares { ms = { - let tv = ms.threshold_view()?; - // CoW — returns a new Multisig with the share added + let tv = ViewBuilder::new(&ms).threshold().build()?; + // CoW — returns a new Multisig with the share added tv.add_share(share)? }; } @@ -173,7 +252,7 @@ for share in &shares { ## Builder API -The `Builder` constructs `Multisig` objects: +The `Builder` constructs `Multisig` objects. It is a different type from `ViewBuilder` ([Views on the Multisig Data](#views-on-the-multisig-data)), which builds views over an existing `Multisig`: | Method | Description | |---|---| @@ -196,12 +275,12 @@ The `Builder` constructs `Multisig` objects: ## Generating and Verifying Signatures -Signature generation and verification are in the companion [`Multi-Key`][MULTIKEY] crate. They use the `SignView` and `VerifyView` traits on a `Multikey`. The `Multikey::sign_view()` method produces a `Multisig`. The `Multikey::verify_view()` method verifies a `Multisig` against an optional message. +Signature generation and verification are in the companion [`Multi-Key`][MULTIKEY] crate. They use the `SignView` and `VerifyView` views on a `Multikey`, built with `multi_key::ViewBuilder`. The sign view produces a `Multisig`. The verify view verifies a `Multisig` against an optional message. ### Generating a Signature ```rust -use multi_key::{Builder, Views}; +use multi_key::{Builder, ViewBuilder}; use multi_codec::Codec; // Generate an Ed25519 key and sign a message @@ -209,22 +288,34 @@ let mk = Builder::new_from_random_bytes(Codec::Ed25519Priv, &mut rand::rng())? .try_build()?; // Combined signature (carries the message in-band) -let multisig = mk.sign_view()?.sign(b"hello world", true, None)?; +let multisig = ViewBuilder::new(&mk) + .sign() + .build()? + .sign(b"hello world", true, None)?; // Detached signature (message supplied out-of-band for verification) -let detached = mk.sign_view()?.sign(b"hello world", false, None)?; +let detached = ViewBuilder::new(&mk) + .sign() + .build()? + .sign(b"hello world", false, None)?; ``` ### Verifying a Signature ```rust -use multi_key::Views; +use multi_key::ViewBuilder; // Verify a combined signature (message is carried in the Multisig) -mk.verify_view()?.verify(&multisig, None)?; +ViewBuilder::new(&mk) + .verify() + .build()? + .verify(&multisig, None)?; // Verify a detached signature (message supplied separately) -mk.verify_view()?.verify(&detached, Some(b"hello world"))?; +ViewBuilder::new(&mk) + .verify() + .build()? + .verify(&detached, Some(b"hello world"))?; ``` ### Combined vs Detached Signatures @@ -263,27 +354,29 @@ BLS12-381 supports three signature schemes, stored as `AttrId::Scheme`: ### Accumulating and Combining Shares ```rust -use multi_key::{Builder, Views}; +use multi_key::Builder; +use multi_sig::ViewBuilder; use multi_codec::Codec; // Split a BLS G2 key into 3-of-5 shares let mk = Builder::new_from_random_bytes(Codec::Bls12381G2Priv, &mut rand::rng())? .try_build()?; -let shares = mk.threshold_view()?.split(3, 5)?; +// the companion crate has its own ViewBuilder, so this snippet qualifies it +let shares = multi_key::ViewBuilder::new(&mk).threshold().build()?.split(3, 5)?; // Each share signs the message (done by the shareholder) let partial_sigs: Vec<_> = shares.iter() - .map(|s| s.sign_view()?.sign(b"message", true, Some(2))?) // scheme 2 = PoP + .map(|s| multi_key::ViewBuilder::new(&s).sign().build()?.sign(b"message", true, Some(2))?) // scheme 2 = PoP .collect(); // Accumulate shares into a combined Multisig let mut ms = partial_sigs[0].clone(); for ps in &partial_sigs[1..] { - ms = ms.threshold_view()?.add_share(ps)?; + ms = ViewBuilder::new(&ms).threshold().build()?.add_share(ps)?; } // Combine into the final signature -let combined = ms.threshold_view()?.combine()?; +let combined = ViewBuilder::new(&ms).threshold().build()?.combine()?; ``` ### SSH Round-Trip for BLS Share Signatures @@ -333,14 +426,14 @@ There are three ways to produce shares in a given disclosure mode: **1. Direct creation via `split_with_disclosure()`:** ```rust -use multi_key::{Builder, Views, ThresholdDisclosure}; +use multi_key::{Builder, ThresholdDisclosure, ViewBuilder}; let meta_key = multi_key::generate_meta_key(); let meta_mk = Builder::new(Codec::Chacha20Poly1305) .with_key_bytes(&meta_key.as_slice()) .try_build()?; -let shares = mk.threshold_view()?.split_with_disclosure(3, 5, +let shares = ViewBuilder::new(&mk).threshold().build()?.split_with_disclosure(3, 5, ThresholdDisclosure::FullConfidentialial, Some(&meta_mk))?; ``` @@ -357,7 +450,9 @@ let share = Builder::new(Codec::Bls12381G2ShareMsig) **3. Convert an existing share:** ```rust -let encrypted = share.disclosure_view()? +let encrypted = ViewBuilder::new(&share) + .disclosure() + .build()? .to_disclosure(ThresholdDisclosure::FullConfidentialial, Some(&meta_mk), None)?; ``` @@ -366,14 +461,18 @@ let encrypted = share.disclosure_view()? Use `read_threshold_params()` with the `meta_key` to decrypt `t` and `n`: ```rust -let (t, n) = encrypted.disclosure_view()? +let (t, n) = ViewBuilder::new(&encrypted) + .disclosure() + .build()? .read_threshold_params(Some(&meta_mk))?; ``` ### Combining Encrypted Shares ```rust -let combined = ms.threshold_view()? +let combined = ViewBuilder::new(&ms) + .threshold() + .build()? .combine_with_meta(Some(&meta_mk))?; ``` @@ -383,15 +482,21 @@ The `to_disclosure()` method converts between any pair of modes. It reads the cu ```rust // Full -> Partial -let partial = full.disclosure_view()? +let partial = ViewBuilder::new(&full) + .disclosure() + .build()? .to_disclosure(ThresholdDisclosure::Partial, Some(&meta_mk), None)?; // Partial -> FullConfidentialial -let confidential = partial.disclosure_view()? +let confidential = ViewBuilder::new(&partial) + .disclosure() + .build()? .to_disclosure(ThresholdDisclosure::FullConfidentialial, Some(&meta_mk), Some(&meta_mk))?; // FullConfidentialial -> Full -let full_again = confidential.disclosure_view()? +let full_again = ViewBuilder::new(&confidential) + .disclosure() + .build()? .to_disclosure(ThresholdDisclosure::Full, None, Some(&meta_mk))?; ``` diff --git a/src/lib.rs b/src/lib.rs index bd54b72..ce2c168 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -51,13 +51,40 @@ //! assert_eq!(ms1, ms2); //! ``` //! +//! ### Creating Views +//! +//! Views give type-safe access to the parts of a `Multisig`. Build them with +//! [`ViewBuilder`], which selects a view kind fluently and dispatches +//! built-in views by codec. See `views::builder` for local-codec factories +//! for custom signature schemes. +//! +//! ```rust +//! use multi_sig::prelude::*; +//! +//! let sig_data = vec![0u8; 64]; +//! let ms = Builder::new(Codec::EddsaMsig) +//! .with_signature_bytes(&sig_data) +//! .try_build() +//! .unwrap(); +//! +//! // a data view reads the signature bytes +//! let data = ViewBuilder::new(&ms).data().build().unwrap(); +//! assert_eq!(data.sig_bytes().unwrap(), sig_data); +//! +//! // an attributes view reads the payload encoding and the scheme +//! let attrs = ViewBuilder::new(&ms).attr().build().unwrap(); +//! assert_eq!(attrs.scheme().unwrap(), 0); +//! ``` +//! //! ## Features //! //! - **`serde`** (default): Enables serde serialization support //! //! ## Thread Safety //! -//! All types are `Send + Sync` and safe for concurrent use. +//! Most types are `Send + Sync`. A [`ViewBuilder`] is `Send + Sync` when its +//! registered factories are. The returned view trait objects carry no +//! `Send`/`Sync` supertrait. #![warn(missing_docs)] #![deny( diff --git a/src/views.rs b/src/views.rs index 6c1e7df..ba65f66 100644 --- a/src/views.rs +++ b/src/views.rs @@ -1,4 +1,15 @@ // 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. +//! +//! 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. use crate::{Error, Multisig}; use multi_codec::Codec; @@ -125,10 +136,15 @@ pub trait ThresholdDisclosureView { /// trait for getting the other views /// -/// Deprecated: create views with `ViewBuilder` instead. +/// 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" + 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 diff --git a/src/views/builder.rs b/src/views/builder.rs index f962e8b..18d2ecc 100644 --- a/src/views/builder.rs +++ b/src/views/builder.rs @@ -66,16 +66,26 @@ //! //! # Factory contract //! -//! A factory is a boxed `Fn(&Multisig) -> Result, Error>` -//! closure that must hold the `Send + Sync + 'static` bounds in its type -//! alias and must not capture borrows. Errors from a factory propagate -//! unchanged. A repeat `with_local_codec` call for the same kind replaces -//! the earlier factory: the last registration wins. +//! A factory holds the HRTB boxed form of its kind's `Local*Fn` type alias: +//! +//! ```text +//! Box Fn(&'a Multisig) -> Result, Error> +//! + Send + Sync + 'static> +//! ``` +//! +//! The closure must not capture borrows; it works from owned state. Errors +//! from a factory propagate unchanged. A repeat `with_local_codec` call for +//! the same kind replaces the earlier factory: the last registration wins. //! //! A factory may return a view that borrows the `Multisig`. A small //! lifetime-parameterized helper function keeps closure inference simple //! for that case; see the unit tests for the pattern. //! +//! The builder itself is `Send + Sync` when its factory type is, and the +//! boxed factories in this crate are. The returned view boxes carry no +//! `Send`/`Sync` supertrait, so the docs of the view traits must not +//! promise more. +//! //! # Custom signature schemes //! //! A custom scheme is a signature scheme this crate does not standardize From 061aada2dc91425cc0d6974448f02f60c1982a1d Mon Sep 17 00:00:00 2001 From: Dave Grantham Date: Wed, 7 Oct 2026 16:03:35 -0600 Subject: [PATCH 7/7] release metadata Signed-off-by: Dave Grantham --- CHANGELOG.md | 15 +++++++++++++++ Cargo.toml | 2 +- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe16792..2173b3e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,20 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm ## [Unreleased] +## [1.5.0] - 2026-10-07 + +### Added + +- `ViewBuilder` (`views::builder`): builder-pattern view creation with a fluent kind selector (`.attr()`, `.data()`, `.conv()`, `.threshold_attr()`, `.threshold()`, `.disclosure()`) and a `.build()` terminal, re-exported at the crate root and in the prelude. Standard codecs dispatch to the built-in views. Custom signature schemes (a codec outside `SIG_CODECS`, constructed through the existing public `Builder` setters) dispatch to caller-supplied local-codec factories on fallthrough, per issue #3 and cryptidtech/multi-key#6. Factories share the multi-key factory contract: HRTB, `Send + Sync + 'static`, last registration wins, and built-in views always win. + +### Changed + +- Version bumped from `1.4.0` to `1.5.0` (minor: new feature and deprecations, no removals). The view dispatch tables moved from `impl Views for Multisig` into the crate-internal `views::dispatch` functions shared by the shim and the new builder. Dispatch behavior is unchanged. + +### Deprecated + +- The `Views` extension trait and `impl Views for Multisig`. Source-compatible in this release. Use `ViewBuilder` instead. Both will be removed in the next major release. Note: `multi_key::Views` is a different, unrelated trait in the companion crate. + ## [1.4.0] - 2026-09-03 ### Added @@ -228,4 +242,5 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - Added the `types.rs` module with type-safe wrappers. - Added a comprehensive test suite for edge cases, proptests, and security. - Initial published release on crates.io as `multi-sig`. +[1.5.0]: https://github.com/cryptidtech/multi-sig/compare/v1.4.0...v1.5.0 [1.2.0]: https://github.com/cryptidtech/multi-sig/compare/v1.1.0...v1.2.0 diff --git a/Cargo.toml b/Cargo.toml index dbdad81..880f676 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "multi-sig" -version = "1.4.0" +version = "1.5.0" edition = "2024" rust-version = "1.96" authors = ["Dave Grantham "]