diff --git a/cabal.project b/cabal.project index fe7cb9024..b131cee32 100644 --- a/cabal.project +++ b/cabal.project @@ -19,6 +19,7 @@ packages: cardano-base cardano-binary cardano-crypto-class + cardano-crypto-leios cardano-crypto-peras cardano-crypto-praos cardano-crypto-wallet diff --git a/cardano-crypto-leios/CHANGELOG.md b/cardano-crypto-leios/CHANGELOG.md new file mode 100644 index 000000000..96e4d7f3d --- /dev/null +++ b/cardano-crypto-leios/CHANGELOG.md @@ -0,0 +1,6 @@ +# Changelog for `cardano-crypto-leios` + +## 0.1.0.0 + +* Initial version: `EbHash` and `LeiosCert` extracted from + `ouroboros-consensus` and `cardano-ledger-core` per CIP-0164. diff --git a/cardano-crypto-leios/LICENSE b/cardano-crypto-leios/LICENSE new file mode 100644 index 000000000..ec6d17953 --- /dev/null +++ b/cardano-crypto-leios/LICENSE @@ -0,0 +1,72 @@ +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and +You must cause any modified files to carry prominent notices stating that You changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright 2026 Input Output Global, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + diff --git a/cardano-crypto-leios/README.md b/cardano-crypto-leios/README.md new file mode 100644 index 000000000..2555c4f8d --- /dev/null +++ b/cardano-crypto-leios/README.md @@ -0,0 +1,11 @@ +# cardano-crypto-leios + +Data types for Leios protocol artifacts as specified in +[CIP-0164](https://github.com/cardano-scaling/CIPs/blob/leios/CIP-0164/README.md): + +- `EbHash` — hash of the RB header that announced an endorser block (`hash32`). +- `LeiosCert` — an aggregated BLS certificate over committee votes for an EB. + +Both `cardano-ledger` (which embeds `LeiosCert` in the Dijkstra-era block body) +and `ouroboros-consensus` (which validates and resolves CertRBs) depend on this +package so they agree on the type. diff --git a/cardano-crypto-leios/cardano-crypto-leios.cabal b/cardano-crypto-leios/cardano-crypto-leios.cabal new file mode 100644 index 000000000..2b52524c7 --- /dev/null +++ b/cardano-crypto-leios/cardano-crypto-leios.cabal @@ -0,0 +1,91 @@ +cabal-version: 3.0 +name: cardano-crypto-leios +version: 0.1.0.0 +synopsis: Crypto primitives for Leios +description: + Data types for the Leios cryptographic artifacts as specified in CIP-0164. + +license: Apache-2.0 +license-files: LICENSE +author: IOHK +maintainer: operations@iohk.io +copyright: 2026 Input Output Global, Inc. +category: Currency +build-type: Simple +extra-doc-files: + CHANGELOG.md + README.md + +common base + build-depends: base >=4.18 && <5 + +common project-config + default-language: Haskell2010 + ghc-options: + -Wall + -Wcompat + -Wincomplete-record-updates + -Wincomplete-uni-patterns + -Wpartial-fields + -Wredundant-constraints + -Wunused-packages + +library + import: base, project-config + hs-source-dirs: src + exposed-modules: + Cardano.Crypto.Leios + + build-depends: + bytestring, + cardano-base, + cardano-binary, + cardano-crypto-class, + cborg, + containers, + deepseq, + nothunks, + primitive >=0.7.3, + text, + vector, + +library testlib + import: base, project-config + visibility: public + hs-source-dirs: testlib + exposed-modules: + Test.Cardano.Crypto.Leios.Gen + + build-depends: + QuickCheck, + cardano-base:testlib, + cardano-crypto-class, + cardano-crypto-leios, + containers, + vector, + +test-suite tests + import: base, project-config + type: exitcode-stdio-1.0 + hs-source-dirs: test + main-is: Main.hs + other-modules: + Test.Cardano.Crypto.Leios + + build-depends: + QuickCheck, + base16-bytestring, + bytestring, + cardano-base:testlib, + cardano-binary, + cardano-crypto-class, + cardano-crypto-leios:{cardano-crypto-leios, testlib}, + cborg, + containers, + hspec, + hspec-golden, + vector, + + ghc-options: + -threaded + -rtsopts diff --git a/cardano-crypto-leios/src/Cardano/Crypto/Leios.hs b/cardano-crypto-leios/src/Cardano/Crypto/Leios.hs new file mode 100644 index 000000000..2312c09b0 --- /dev/null +++ b/cardano-crypto-leios/src/Cardano/Crypto/Leios.hs @@ -0,0 +1,424 @@ +{-# LANGUAGE BangPatterns #-} +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE DeriveAnyClass #-} +{-# LANGUAGE DeriveGeneric #-} +{-# LANGUAGE DerivingVia #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE TypeApplications #-} + +-- | Cryptographic data types and operations used in Leios per CIP-164. Leios +-- uses BLS12-381 MinSig as its signature scheme and defines a 'LeiosCert' that +-- can be included into blocks. This module deliberately not includes a +-- 'LeiosVote' because the vote itself is not an artifact that is on-chain. +module Cardano.Crypto.Leios ( + -- * Cryptographic primitives + LeiosDSIGN, + LeiosSigningKey, + LeiosVerificationKey, + LeiosSignature, + leiosSignContext, + leiosSignatureSize, + leiosSignatureToBytes, + + -- * Voting committee + Weight, + LeiosVoterId (..), + encodeLeiosVoterId, + decodeLeiosVoterId, + LeiosVoter (..), + LeiosCommittee (..), + leiosCommitteeSize, + resolveLeiosVoter, + getLeiosVoterId, + + -- * Leios certificates + LeiosCert (..), + encodeLeiosCert, + decodeLeiosCert, + + -- ** Construction + AggregationError (..), + aggregateLeiosCert, + + -- ** Verification + VerificationError (..), + verifyLeiosCert, + + -- * Bitfield wire-format helpers + BitField, + encodeBitField, + decodeBitField, +) where + +import Cardano.Base.Bytes (byteArrayFromByteString) +import Cardano.Binary (matchSize, toCBOR) +import Cardano.Crypto.DSIGN ( + DSIGNAggregatable (aggregateSigsDSIGN, uncheckedAggregateVerKeysDSIGN), + DSIGNAlgorithm (rawSerialiseSigDSIGN), + SigDSIGN, + SignKeyDSIGN, + VerKeyDSIGN, + decodeSigDSIGN, + encodeSigDSIGN, + verifyDSIGN, + ) +import Cardano.Crypto.DSIGN.BLS12381 (BLS12381MinSigDSIGN, BLS12381SignContext, minSigPoPDST) +import Cardano.Crypto.DSIGN.Class (sigSizeDSIGN) +import Cardano.Crypto.Util (SignableRepresentation) +import Codec.CBOR.Decoding (Decoder, decodeBreakOr, decodeBytes, decodeListLenOrIndef, decodeWord16) +import Codec.CBOR.Encoding (Encoding, encodeListLen, encodeWord16) +import Control.DeepSeq (NFData) +import Control.Monad (forM_, unless, when) +import Data.Array.Byte (ByteArray) +import Data.Bifunctor (first) +import Data.Bits (setBit, shiftR, testBit, (.&.)) +import Data.ByteString (ByteString) +import Data.Data (Proxy (..)) +import Data.Foldable (foldrM) +import Data.Function ((&)) +import Data.List.NonEmpty (NonEmpty, nonEmpty) +import Data.Map.Strict (Map) +import qualified Data.Map.Strict as Map +import Data.Maybe (isNothing) +import Data.Primitive.ByteArray ( + fillByteArray, + indexByteArray, + newByteArray, + readByteArray, + runByteArray, + sizeofByteArray, + writeByteArray, + ) +import Data.Text (Text) +import qualified Data.Text as T +import Data.Vector.Strict (Vector) +import qualified Data.Vector.Strict as V +import Data.Word (Word16, Word8) +import GHC.Generics (Generic) +import NoThunks.Class (NoThunks, OnlyCheckWhnfNamed (..)) + +type LeiosDSIGN = BLS12381MinSigDSIGN + +type LeiosSigningKey = SignKeyDSIGN LeiosDSIGN + +type LeiosVerificationKey = VerKeyDSIGN LeiosDSIGN + +type LeiosSignature = SigDSIGN LeiosDSIGN + +-- | The BLS12-381 MinSig proof-of-possession ciphersuite DST used by Leios, +-- per CIP-164. Pass this as the 'ContextDSIGN' to 'signDSIGN' / 'verifyDSIGN'. +leiosSignContext :: BLS12381SignContext +leiosSignContext = minSigPoPDST + +-- | Size of a Leios signature in the chosen signature scheme. +leiosSignatureSize :: Word +leiosSignatureSize = sigSizeDSIGN (Proxy @LeiosDSIGN) + +-- | Get the bytes of a Leios signature. +leiosSignatureToBytes :: LeiosSignature -> ByteString +leiosSignatureToBytes = rawSerialiseSigDSIGN + +-- | A weight assigned to a committee voter, normalised so the total over a +-- committee sums to @1@. Threshold checks in 'verifyLeiosCert' are against +-- this same scale. +type Weight = Rational + +-- | A committee member's seat index. The index is the voter's position in +-- 'committeeVoters' and determines its bit in the 'LeiosCert' @signers@ +-- bitfield (MSB-first within each byte, so voter @i@ ↔ bit @7-(i mod 8)@ of +-- byte @i \`div\` 8@). +newtype LeiosVoterId = LeiosVoterId {voterIndex :: Word16} + deriving stock (Eq, Ord, Show, Generic) + deriving anyclass (NFData, NoThunks) + +-- | Plain CBOR encoder for 'LeiosVoterId'. +encodeLeiosVoterId :: LeiosVoterId -> Encoding +encodeLeiosVoterId (LeiosVoterId idx) = encodeWord16 idx + +-- | Plain CBOR decoder for 'LeiosVoterId'. +decodeLeiosVoterId :: Decoder s LeiosVoterId +decodeLeiosVoterId = LeiosVoterId <$> decodeWord16 + +-- | A single seat in a 'LeiosCommittee': a voter's normalised weight paired with +-- its BLS verification key. +data LeiosVoter = LeiosVoter + { voterWeight :: !Weight + , voterVKey :: !LeiosVerificationKey + } + deriving stock (Show, Eq, Generic) + deriving anyclass (NFData, NoThunks) + +-- | The voting committee for a Leios epoch: an ordered vector of +-- 'LeiosVoter' seats. +-- +-- Ixition determines the voter's 'LeiosVoterId' and its bit in the certificate's +-- bitfield, so callers must keep the order stable between construction and +-- verification of any cert. +-- +-- This package intentionally does not provide committee selection — sampling +-- voters from the active stake distribution lives in consensus/ledger. +-- However, callers are responsible for ensuring that every voter's BLS +-- proof-of-possession has been verified before a 'LeiosCommittee' value is built; +-- 'verifyLeiosCert' and 'aggregateLeiosCert' both rely on this invariant to +-- skip per-key PoP checks (they use 'uncheckedAggregateVerKeysDSIGN' / +-- 'aggregateSigsDSIGN' under the hood). Passing in unchecked keys defeats +-- the security of the aggregate signature. +newtype LeiosCommittee = LeiosCommittee {committeeVoters :: Vector LeiosVoter} + deriving stock (Show, Eq, Generic) + deriving anyclass (NFData) + -- 'nothunks' ships no instance for 'Data.Vector.Strict.Vector' and we don't + -- want to add an orphan. A WHNF-only check on the wrapper is sufficient here: + -- the strict 'Vector' forces every cell to WHNF, and a WHNF 'LeiosVoter' + -- forces both of its strict fields, so "LeiosCommittee in WHNF" structurally + -- implies no thunks anywhere inside. + deriving (NoThunks) via OnlyCheckWhnfNamed "LeiosCommittee" LeiosCommittee + +-- | Number of seats in the committee. +leiosCommitteeSize :: LeiosCommittee -> Int +leiosCommitteeSize LeiosCommittee {committeeVoters} = length committeeVoters + +-- | Resolve a 'LeiosVoterId' to its 'LeiosVoter' on the 'LeiosCommittee', or 'Nothing' +-- if the index is past the committee bound. +resolveLeiosVoter :: LeiosCommittee -> LeiosVoterId -> Maybe LeiosVoter +resolveLeiosVoter committee voterId = + committee.committeeVoters V.!? idx + where + idx = fromIntegral @Word16 @Int voterId.voterIndex + +-- | Find a voter's 'LeiosVoterId' on the 'LeiosCommittee' by its +-- 'LeiosVerificationKey', or 'Nothing' if the key is not on the committee. +-- +-- If the committee carries duplicate verification keys, returns the smallest +-- index matching @vk@ (committee selection is expected to deduplicate, but +-- this module does not enforce it). +-- +-- Errors if the matching index does not fit in 'Word16'. The wire format of +-- 'LeiosCert' indexes voters by a 16-bit field, so a committee with more than +-- @2^16@ seats is already malformed. NOTE: this partiality could later be +-- avoided by introducing a smart constructor for 'LeiosCommittee' (or for the +-- committee-selection step in consensus) that rejects oversized committees +-- up front. +getLeiosVoterId :: LeiosVerificationKey -> LeiosCommittee -> Maybe LeiosVoterId +getLeiosVoterId vk committee = + toVoterId <$> V.findIndex ((== vk) . voterVKey) committee.committeeVoters + where + toVoterId i + | i > fromIntegral @Word16 @Int maxBound = + error $ + "Cardano.Crypto.Leios.getVoterId: committee index " + <> show i + <> " does not fit in Word16" + | otherwise = LeiosVoterId (fromIntegral @Int @Word16 i) + +-- | A Leios certificate over an endorser block, as specified in CIP-164: +-- +-- @ +-- leios_certificate = +-- [ signers : bytes ; bitfield over the epoch's committee, MSB-first +-- , aggregated_signature : leios_bls_signature +-- ] +-- @ +-- +-- The committee is derived deterministically from the active stake +-- distribution for the epoch of the announcing RB, so individual voter +-- identities and eligibility proofs are not carried in the certificate; +-- 'signers' is a @⌈N\/8⌉@-byte bitfield over the committee where bit @i@ is +-- set iff voter index @i@ signed. +-- +-- Producers should build 'LeiosCert' values via 'aggregateLeiosCert' and +-- consumers verify them via 'verifyLeiosCert'; the bitfield layout is an +-- implementation detail of the wire format. +-- +-- XXX: This says it's over an EB, but this modules does not specify the +-- "message" that is signed anymore and only it's usage within a block will add +-- these semantics. +data LeiosCert = LeiosCert + { signers :: !BitField + , aggregatedSignature :: !LeiosSignature + } + deriving stock (Show, Eq, Generic) + deriving anyclass (NFData, NoThunks) + +-- | Plain CBOR encoder for 'LeiosCert', matching the CDDL in 'LeiosCert'. +encodeLeiosCert :: LeiosCert -> Encoding +encodeLeiosCert cert = + encodeListLen 2 + <> encodeBitField cert.signers + <> encodeSigDSIGN cert.aggregatedSignature + +-- | Plain CBOR decoder for 'LeiosCert', matching the CDDL in 'LeiosCert'. +-- Accepts both definite-length and indefinite-length encodings of the +-- outer 2-element array. +decodeLeiosCert :: Decoder s LeiosCert +decodeLeiosCert = do + isIndef <- + decodeListLenOrIndef >>= \case + Just n -> False <$ matchSize "LeiosCert" 2 n + Nothing -> pure True + cert <- + LeiosCert + <$> decodeBitField + <*> decodeSigDSIGN + when isIndef $ do + isBreak <- decodeBreakOr + unless isBreak $ + fail "LeiosCert: expected break after 2 elements of indefinite-length list" + pure cert + +data AggregationError + = -- | One or more voter indices in the sigs are past the committee bound. + VoterIdsOutOfBounds (NonEmpty LeiosVoterId) + | -- | BLS signature aggregation failed (e.g. malformed input signature). + BLSAggregationFailed Text + deriving stock (Eq, Show, Generic) + deriving anyclass (NFData) + +-- | Build a 'LeiosCert' from the sigs of committee members. +-- +-- == Caller obligations +-- +-- All signatures must be over the same message. Individual 'LeiosSignature' +-- values are not verified here, and once aggregated they cannot be told apart. +-- Feeding signatures cast over different messages produces a 'LeiosCert' that +-- will silently fail 'verifyLeiosCert' with no indication of which contribution +-- was wrong. +-- +-- == What this function does +-- +-- * Range-checks each 'LeiosVoterId' against the committee. +-- * Encodes the bitfield over the committee and aggregates the input +-- signatures. +-- +-- This is the only way to construct a 'LeiosCert' from outside the package; +-- the bitfield layout is an internal wire-format detail. +aggregateLeiosCert :: + LeiosCommittee -> + Map LeiosVoterId LeiosSignature -> + Either AggregationError LeiosCert +aggregateLeiosCert committee sigs = do + case nonEmpty outOfBoundsVoterIds of + Just vs -> Left (VoterIdsOutOfBounds vs) + Nothing -> pure () + aggregatedSignature <- + first (BLSAggregationFailed . T.pack) $ + aggregateSigsDSIGN (Map.elems sigs) + pure LeiosCert {signers, aggregatedSignature} + where + outOfBoundsVoterIds = + [vid | vid <- Map.keys sigs, isNothing $ resolveLeiosVoter committee vid] + + -- Builds directly into a mutable 'ByteArray' via a single allocation and + -- writes one bit per member of the input set. + signers = BitField $ runByteArray $ do + mba <- newByteArray len + fillByteArray mba 0 len 0 + forM_ (Map.keys sigs) $ \(LeiosVoterId i) -> do + let idx = fromIntegral @Word16 @Int i + when (idx < n) $ do + let byteIx = idx `shiftR` 3 + bitIx = 7 - (idx .&. 7) + b <- readByteArray @Word8 mba byteIx + writeByteArray mba byteIx (b `setBit` bitIx) + pure mba + + n = leiosCommitteeSize committee + + len = (n + 7) `div` 8 + +data VerificationError + = -- | 'signers' bitfield is longer than @⌈leiosCommitteeSize/8⌉@ bytes. + MalformedSigners + | -- | The aggregate-BLS verification failed (wrong message, tampered + -- signature, or a bitfield/aggregate mismatch). + InvalidSignature + | -- | Sum of signers' weights is below the required threshold. + InsufficientWeight Weight + deriving stock (Eq, Show, Generic) + deriving anyclass (NFData) + +-- | Verify a 'LeiosCert' against a 'LeiosCommittee', a weight threshold, and the +-- message the signers were supposed to have signed. +-- +-- == Caller obligations +-- +-- Every voter in the 'LeiosCommittee' must have had its BLS proof-of-possession +-- verified beforehand (when the committee was selected). 'verifyLeiosCert' +-- uses 'uncheckedAggregateVerKeysDSIGN' and does not re-check PoPs; passing +-- in an unchecked committee breaks the security of the aggregate signature. +-- +-- == What this function does +-- +-- 1. Decodes the 'signers' bitfield to the list of contributing voter +-- indices, rejecting too small or big bitfield with 'MalformedSigners'. +-- +-- 2. Sums those voters' weights from the committee; short-circuits with +-- 'InsufficientWeight' if the sum is below the threshold. +-- +-- 3. Aggregates the contributing verification keys and verifies the +-- certificate's 'aggregatedSignature' against the aggregate key over +-- @msg@. +verifyLeiosCert :: + SignableRepresentation msg => + LeiosCommittee -> + -- | Minimum signer weight required to accept the cert. + Weight -> + -- | The message the signers signed. + msg -> + LeiosCert -> + -- | Total weight of the contributing signers on success. + Either VerificationError Weight +verifyLeiosCert committee weightRequired msg cert = do + -- The bitfield must be exactly the canonical 'committee-many bits, padded + -- to a whole byte' length. Trailing bytes (zero-padded or otherwise) are + -- not accepted; the wire form is fixed for a given committee size. + when (sizeofByteArray (bitFieldBytes cert.signers) /= (n + 7) `div` 8) $ + Left MalformedSigners + (weightReceived, vks) <- foldrM accumSigner (0, []) $ bitFieldMembers cert.signers + when (weightReceived < weightRequired) $ + Left (InsufficientWeight weightReceived) + aggVk <- + uncheckedAggregateVerKeysDSIGN vks + & first (const InvalidSignature) + verifyDSIGN leiosSignContext aggVk msg cert.aggregatedSignature + & first (const InvalidSignature) + pure weightReceived + where + n = leiosCommitteeSize committee + + accumSigner vid (!w, !ks) = + case resolveLeiosVoter committee vid of + Nothing -> Left MalformedSigners + Just (LeiosVoter w' vk) -> Right (w + w', vk : ks) + + bitFieldMembers (BitField ba) = + [ LeiosVoterId (fromIntegral @Int @Word16 globalIx) + | byteIx <- [0 .. sizeofByteArray ba - 1] + , let byte = indexByteArray ba byteIx :: Word8 + , bitIx <- [0 .. 7] + , let globalIx = byteIx * 8 + bitIx + , globalIx < n + , testBit byte (7 - bitIx) + ] + +-- | The @signers@ bitfield of a 'LeiosCert': a @⌈leiosCommitteeSize\/8⌉@-byte +-- MSB-first packed-bits representation of which committee voters contributed +-- to the aggregate signature. +-- +-- A 'newtype' wrapper around 'ByteArray' so type signatures throughout the +-- aggregate / verify path say what they're working on, and so the on-wire +-- form cannot be accidentally confused with arbitrary @bytes@. +newtype BitField = BitField {bitFieldBytes :: ByteArray} + deriving stock (Show, Eq, Generic) + deriving anyclass (NFData) + deriving (NoThunks) via OnlyCheckWhnfNamed "BitField" BitField + +-- | Encode a 'BitField' to CBOR bytes. +encodeBitField :: BitField -> Encoding +encodeBitField = toCBOR . bitFieldBytes + +-- | Decode a 'BitField' from CBOR bytes. +decodeBitField :: Decoder s BitField +decodeBitField = BitField . byteArrayFromByteString <$> decodeBytes diff --git a/cardano-crypto-leios/test/Main.hs b/cardano-crypto-leios/test/Main.hs new file mode 100644 index 000000000..5ffe47587 --- /dev/null +++ b/cardano-crypto-leios/test/Main.hs @@ -0,0 +1,8 @@ +module Main (main) where + +import qualified Test.Cardano.Crypto.Leios +import Test.Hspec (hspec) +import Prelude + +main :: IO () +main = hspec Test.Cardano.Crypto.Leios.spec diff --git a/cardano-crypto-leios/test/Test/Cardano/Crypto/Leios.hs b/cardano-crypto-leios/test/Test/Cardano/Crypto/Leios.hs new file mode 100644 index 000000000..bc254ec71 --- /dev/null +++ b/cardano-crypto-leios/test/Test/Cardano/Crypto/Leios.hs @@ -0,0 +1,338 @@ +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TypeApplications #-} + +module Test.Cardano.Crypto.Leios (spec, exampleCert) where + +import qualified Cardano.Binary as CBOR +import Cardano.Crypto.DSIGN ( + DSIGNAlgorithm (deriveVerKeyDSIGN), + encodeSigDSIGN, + genKeyDSIGN, + seedSizeDSIGN, + signDSIGN, + ) +import Cardano.Crypto.Leios ( + AggregationError (..), + LeiosCert (..), + LeiosCommittee (..), + LeiosDSIGN, + LeiosSignature, + LeiosSigningKey, + LeiosVoter (..), + LeiosVoterId (..), + VerificationError (..), + Weight, + aggregateLeiosCert, + decodeLeiosCert, + decodeLeiosVoterId, + encodeBitField, + encodeLeiosCert, + encodeLeiosVoterId, + getLeiosVoterId, + leiosSignContext, + resolveLeiosVoter, + verifyLeiosCert, + ) +import Cardano.Crypto.Seed (mkSeedFromBytes) +import Codec.CBOR.Encoding (Encoding, encodeBreak, encodeListLenIndef) +import qualified Data.ByteString as BS +import qualified Data.ByteString.Base16 as BS16 +import qualified Data.ByteString.Char8 as BS8 +import qualified Data.ByteString.Lazy as BSL +import Data.Foldable (toList) +import Data.List.NonEmpty (NonEmpty (..), fromList) +import Data.Map.Strict (Map) +import qualified Data.Map.Strict as Map +import Data.Proxy (Proxy (Proxy)) +import qualified Data.Vector.Strict as V +import Data.Word (Word16, Word8) +import Test.Cardano.Base.Bytes (genByteString) +import Test.Cardano.Crypto.Leios.Gen (genLeiosCert) +import Test.Hspec (Spec, context, describe, it) +import Test.Hspec.Golden (Golden (..)) +import Test.Hspec.QuickCheck (prop) +import Test.QuickCheck ( + Property, + chooseInt, + counterexample, + forAll, + (===), + ) +import qualified Test.QuickCheck as QC + +spec :: Spec +spec = do + describe "LeiosCert" $ do + prop "round-trips through CBOR" prop_roundtrip_LeiosCert + prop "decodes indefinite-length encoding" prop_decode_indefinite_LeiosCert + it "matches golden encoding" $ + goldenEncoding "test/golden/LeiosCert" encodeLeiosCert exampleCert + + describe "aggregateLeiosCert" $ do + prop "rejects an out-of-range LeiosVoterId" prop_aggregateLeiosCert_rejects_out_of_range + prop "rejects empty contributions" prop_aggregateLeiosCert_rejects_empty + + describe "verifyLeiosCert" $ do + context "with a valid certificate" $ do + prop "accepts a full-committee aggregation" prop_verifyLeiosCert_accepts_aggregated + prop "accepts a subset of signers above threshold" prop_verifyLeiosCert_accepts_subset + context "with an invalid certificate" $ do + prop "rejects a wrong message" prop_verifyLeiosCert_rejects_wrong_message + prop "rejects when total weight is below threshold" prop_verifyLeiosCert_rejects_below_threshold + prop "rejects a bitfield wider than the committee" prop_verifyLeiosCert_rejects_oversized_signers + prop "rejects a tampered bitfield" prop_verifyLeiosCert_rejects_tampered_bitfield + + describe "LeiosVoterId" $ do + prop "round-trips through CBOR" prop_roundtrip_VoterId + it "matches golden encoding" $ + goldenEncoding "test/golden/LeiosVoterId" encodeLeiosVoterId exampleVoterId + + describe "LeiosCommittee" $ do + prop + "getLeiosVoterId and resolveLeiosVoter agree on verification keys" + prop_resolveVoter_getVoterId_inverse + prop "getLeiosVoterId returns the first matching index" prop_getVoterId_returns_first_index + +-- * CBOR roundtrip / golden + +prop_roundtrip_LeiosCert :: Property +prop_roundtrip_LeiosCert = forAll genLeiosCert $ \cert -> + let bs = CBOR.serialize (encodeLeiosCert cert) + in CBOR.decodeFullDecoder "LeiosCert" decodeLeiosCert bs === Right cert + +-- | The decoder must accept indefinite-length encodings of the outer +-- 2-element array, not just the canonical definite-length form. +prop_decode_indefinite_LeiosCert :: Property +prop_decode_indefinite_LeiosCert = forAll genLeiosCert $ \cert -> + let indef = + encodeListLenIndef + <> encodeBitField (signers cert) + <> encodeSigDSIGN (aggregatedSignature cert) + <> encodeBreak + in CBOR.decodeFullDecoder "LeiosCert" decodeLeiosCert (CBOR.serialize indef) + === Right cert + +-- | Pin the byte-for-byte CBOR encoding of a value to a golden file using +-- 'hspec-golden'. Failure diffs are rendered as base16 hex. Decode +-- round-trip of arbitrary values is covered by the matching @roundtrip_@ +-- property; this only locks the encoding shape. +goldenEncoding :: FilePath -> (a -> Encoding) -> a -> Golden BSL.ByteString +goldenEncoding path enc value = + Golden + { output = CBOR.serialize (enc value) + , encodePretty = BS8.unpack . BS16.encode . BSL.toStrict + , writeToFile = BSL.writeFile + , readFromFile = BSL.readFile + , goldenFile = path + , actualFile = Nothing + , failFirstTime = False + } + +exampleCert :: LeiosCert +exampleCert = case aggregateLeiosCert committee contributions of + Right c -> c + Left e -> error ("exampleCert: aggregation failed: " <> show e) + where + (sks, committee) = fixedCommittee 1000 + msg = "leios-golden-message" :: BS.ByteString + contributions = signContribs msg (zip [0 ..] (toList sks)) + +-- * LeiosVoterId CBOR / committee lookup + +prop_roundtrip_VoterId :: Property +prop_roundtrip_VoterId = forAll (LeiosVoterId <$> QC.arbitrary) $ \vid -> + let bs = CBOR.serialize (encodeLeiosVoterId vid) + in CBOR.decodeFullDecoder "LeiosVoterId" decodeLeiosVoterId bs === Right vid + +exampleVoterId :: LeiosVoterId +exampleVoterId = LeiosVoterId 0xABCD + +-- | 'getLeiosVoterId' and 'resolveLeiosVoter' are mutual inverses on the verification +-- key projection: for any voter in the committee, looking up its 'LeiosVoterId' +-- via its key and resolving back to a 'LeiosVoter' yields the same key. +prop_resolveVoter_getVoterId_inverse :: Property +prop_resolveVoter_getVoterId_inverse = + forAll genN $ \n -> + let (_, committee) = fixedCommittee n + voters = V.toList committee.committeeVoters + in QC.conjoin + [ counterexample ("voter index " <> show i) $ + case getLeiosVoterId (voterVKey voter) committee of + Nothing -> QC.property False + Just vid -> + case resolveLeiosVoter committee vid of + Nothing -> QC.property False + Just voter' -> voterVKey voter' === voterVKey voter + | (i :: Int, voter) <- zip [0 ..] voters + ] + +-- | When the committee carries duplicate verification keys, 'getLeiosVoterId' +-- returns the smallest matching index. We don't deduplicate committees +-- internally; downstream selection is expected to. +prop_getVoterId_returns_first_index :: Property +prop_getVoterId_returns_first_index = + forAll genN $ \n -> + let (_, committee) = fixedCommittee n + voters = V.toList committee.committeeVoters + in QC.conjoin + [ counterexample ("first occurrence at " <> show i) $ + getLeiosVoterId (voterVKey voter) duped + === Just (LeiosVoterId (fromIntegral i)) + | let duped = + LeiosCommittee + (committee.committeeVoters <> committee.committeeVoters) + , (i :: Int, voter) <- zip [0 ..] voters + ] + +-- * aggregate / verify + +-- | Equal-weighted committee of @n@ voters derived from a fixed seed pattern. +-- Returns the signing keys alongside the committee so tests can produce +-- contributions. The 'NonEmpty' return reflects the @n ≥ 1@ precondition and +-- gives tests a total 'head' for "any-one-signer" cases. +fixedCommittee :: Int -> (NonEmpty LeiosSigningKey, LeiosCommittee) +fixedCommittee n = + ( sks + , LeiosCommittee + ( V.fromList + [LeiosVoter (1 / fromIntegral @Int @Weight n) (deriveVerKeyDSIGN sk) | sk <- toList sks] + ) + ) + where + seedLen = fromIntegral @Word @Int (seedSizeDSIGN (Proxy @LeiosDSIGN)) + sks = + fromList + [ genKeyDSIGN @LeiosDSIGN (mkSeedFromBytes (BS.replicate seedLen (fromIntegral @Int @Word8 i))) + | i <- [1 .. max 1 n] + ] + +-- | Default committee size range exercised by the verify/aggregate properties. +-- 1 ≤ n ≤ 16 covers single-voter (n=1), single-byte bitfield (n ≤ 8) and the +-- two-byte boundary (n=9..16). +genN :: QC.Gen Int +genN = chooseInt (1, 16) + +genMsg :: QC.Gen BS.ByteString +genMsg = chooseInt (0, 64) >>= genByteString + +-- | Sign @msg@ with each of the given keys and pack them into a 'Map' keyed +-- by 'LeiosVoterId', matching the input shape of 'aggregateLeiosCert'. +signContribs :: BS.ByteString -> [(Int, LeiosSigningKey)] -> Map LeiosVoterId LeiosSignature +signContribs msg pairs = + Map.fromList + [(LeiosVoterId (fromIntegral @Int @Word16 i), signDSIGN leiosSignContext msg sk) | (i, sk) <- pairs] + +-- | Aggregate or fail the property with the error. +aggregateOrFail :: + LeiosCommittee -> + Map LeiosVoterId LeiosSignature -> + (LeiosCert -> Property) -> + Property +aggregateOrFail committee contributions k = case aggregateLeiosCert committee contributions of + Right c -> k c + Left e -> counterexample (show e) (QC.property False) + +-- | All committee members sign the same message; the resulting cert verifies +-- against that committee, threshold and message, and reports full weight. +prop_verifyLeiosCert_accepts_aggregated :: Property +prop_verifyLeiosCert_accepts_aggregated = forAll genN $ \n -> forAll genMsg $ \msg -> + let (sks, committee) = fixedCommittee n + contributions = signContribs msg (zip [0 :: Int ..] (toList sks)) + in aggregateOrFail committee contributions $ \cert -> + verifyLeiosCert committee 1 msg cert === Right 1 + +-- | An arbitrary subset of @k@ committee members signs the same message. +-- The cert must verify against any threshold @≤ k/n@ and report weight +-- @k/n@. Catches bugs where the verifier doesn't actually sum the correct +-- subset of weights. +prop_verifyLeiosCert_accepts_subset :: Property +prop_verifyLeiosCert_accepts_subset = forAll genN $ \n -> + forAll (chooseInt (1, n)) $ \k -> + forAll genMsg $ \msg -> + let (sks, committee) = fixedCommittee n + contributions = signContribs msg (take k (zip [0 :: Int ..] (toList sks))) + expectedWeight = fromIntegral @Int @Weight k / fromIntegral @Int @Weight n + in aggregateOrFail committee contributions $ \cert -> + verifyLeiosCert committee expectedWeight msg cert === Right expectedWeight + +-- | A cert built over message @m1@ must not verify against message @m2@. +prop_verifyLeiosCert_rejects_wrong_message :: Property +prop_verifyLeiosCert_rejects_wrong_message = forAll genN $ \n -> + let (sks, committee) = fixedCommittee n + m1 = "leios-message-one" :: BS.ByteString + m2 = "leios-message-two" :: BS.ByteString + contributions = signContribs m1 (zip [0 :: Int ..] (toList sks)) + in aggregateOrFail committee contributions $ \cert -> + verifyLeiosCert committee 1 m2 cert === Left InvalidSignature + +-- | A cert whose signers' summed weight is below the threshold must be +-- rejected with 'InsufficientWeight', without ever performing the BLS +-- pairing. Uses n ≥ 2 so a single signer's weight @1/n@ is strictly less +-- than the full-weight threshold. +prop_verifyLeiosCert_rejects_below_threshold :: Property +prop_verifyLeiosCert_rejects_below_threshold = forAll (chooseInt (2, 16)) $ \n -> + let (sk0 :| _, committee) = fixedCommittee n + msg = "leios-quorum-test" :: BS.ByteString + contributions = signContribs msg [(0, sk0)] + in aggregateOrFail committee contributions $ \cert -> + verifyLeiosCert committee 1 msg cert + === Left (InsufficientWeight (1 / fromIntegral @Int @Weight n)) + +-- | A 'signers' bitfield whose byte length differs from @⌈n/8⌉@ must be +-- rejected as 'MalformedSigners' before any signature work is done. We +-- build a cert against committee A and verify against committee B whose +-- size sits in the next byte bucket (A's bitfield is one byte short of +-- what B expects). +prop_verifyLeiosCert_rejects_oversized_signers :: Property +prop_verifyLeiosCert_rejects_oversized_signers = forAll genN $ \n -> + let (sks, committeeA) = fixedCommittee n + (_, committeeB) = fixedCommittee (n + 8) + msg = "leios-malformed-test" :: BS.ByteString + contributions = signContribs msg (zip [0 :: Int ..] (toList sks)) + in aggregateOrFail committeeA contributions $ \cert -> + verifyLeiosCert committeeB 1 msg cert === Left MalformedSigners + +-- | A cert whose 'signers' bitfield disagrees with its 'aggregatedSignature' +-- must be rejected with 'InvalidSignature'. We construct two real certs +-- against the same committee (voter 0 alone, then voters 0+1), then splice +-- certA's signature with certB's bitfield. The bitfield claims voter 1 also +-- signed but the aggregate doesn't include voter 1's signature, so the BLS +-- pairing fails. Uses n ≥ 2 so there are at least two voters to splice. +prop_verifyLeiosCert_rejects_tampered_bitfield :: Property +prop_verifyLeiosCert_rejects_tampered_bitfield = forAll (chooseInt (2, 16)) $ \n -> + let (sks, committee) = fixedCommittee n + (sks0, sks1) = case sks of + s0 :| (s1 : _) -> (s0, s1) + _ -> error "prop_verifyLeiosCert_rejects_tampered_bitfield: n >= 2 invariant violated" + msg = "leios-tamper-test" :: BS.ByteString + contribsAlone = signContribs msg [(0, sks0)] + contribsPair = signContribs msg [(0, sks0), (1, sks1)] + in aggregateOrFail committee contribsAlone $ \certA -> + aggregateOrFail committee contribsPair $ \certB -> + let tampered = certA {signers = certB.signers} + in -- Threshold is below the tampered weight 2/n so we exercise the BLS + -- pairing failure, not the short-circuit. + verifyLeiosCert committee (1 / fromIntegral @Int @Weight n) msg tampered + === Left InvalidSignature + +-- | A 'LeiosVoterId' past the committee bound is rejected at aggregation time. +prop_aggregateLeiosCert_rejects_out_of_range :: Property +prop_aggregateLeiosCert_rejects_out_of_range = forAll genN $ \n -> + forAll (chooseInt (n, n + 100)) $ \badIdx -> + let (sk0 :| _, committee) = fixedCommittee n + msg = "x" :: BS.ByteString + bad = LeiosVoterId (fromIntegral @Int @Word16 badIdx) + contributions = Map.singleton bad (signDSIGN leiosSignContext msg sk0) + in aggregateLeiosCert committee contributions === Left (VoterIdsOutOfBounds (bad :| [])) + +-- | Aggregating an empty contribution set must fail: the underlying BLS +-- 'aggregateSigsDSIGN' rejects the empty input, which surfaces as +-- 'BLSAggregationFailed'. We don't pin the exact message string. +prop_aggregateLeiosCert_rejects_empty :: Property +prop_aggregateLeiosCert_rejects_empty = forAll genN $ \n -> + let (_, committee) = fixedCommittee n + in case aggregateLeiosCert committee Map.empty of + Left BLSAggregationFailed {} -> QC.property True + other -> counterexample (show other) (QC.property False) diff --git a/cardano-crypto-leios/test/golden/LeiosCert b/cardano-crypto-leios/test/golden/LeiosCert new file mode 100644 index 000000000..ed19b53d0 Binary files /dev/null and b/cardano-crypto-leios/test/golden/LeiosCert differ diff --git a/cardano-crypto-leios/test/golden/LeiosVoterId b/cardano-crypto-leios/test/golden/LeiosVoterId new file mode 100644 index 000000000..503ff1aaa --- /dev/null +++ b/cardano-crypto-leios/test/golden/LeiosVoterId @@ -0,0 +1 @@ +«Í \ No newline at end of file diff --git a/cardano-crypto-leios/testlib/Test/Cardano/Crypto/Leios/Gen.hs b/cardano-crypto-leios/testlib/Test/Cardano/Crypto/Leios/Gen.hs new file mode 100644 index 000000000..f5aad0613 --- /dev/null +++ b/cardano-crypto-leios/testlib/Test/Cardano/Crypto/Leios/Gen.hs @@ -0,0 +1,101 @@ +{-# LANGUAGE TypeApplications #-} + +-- | QuickCheck generators for 'Cardano.Crypto.Leios' types, intended for +-- downstream test suites (e.g. @cardano-ledger@) that want a real +-- structurally-valid 'LeiosCert' without depending on the BLS plumbing. +-- +-- These generators produce values whose CBOR encoding round-trips, but they +-- do not attempt to satisfy 'verifyLeiosCert' against any particular +-- committee or message — the @signers@ bitfield is uncorrelated with the +-- aggregated signature. That makes them suitable for serialisation and +-- AST-shape tests, not for protocol-level acceptance tests. +module Test.Cardano.Crypto.Leios.Gen ( + genLeiosCert, + genLeiosSignature, + genLeiosSigningKey, + generateWith, +) where + +import Cardano.Crypto.DSIGN ( + DSIGNAlgorithm (deriveVerKeyDSIGN), + genKeyDSIGN, + seedSizeDSIGN, + signDSIGN, + ) +import Cardano.Crypto.Leios ( + LeiosCert, + LeiosCommittee (..), + LeiosDSIGN, + LeiosSignature, + LeiosSigningKey, + LeiosVoter (..), + LeiosVoterId (..), + aggregateLeiosCert, + leiosSignContext, + ) +import Cardano.Crypto.Seed (mkSeedFromBytes) +import qualified Data.Map.Strict as Map +import Data.Proxy (Proxy (Proxy)) +import Data.Ratio ((%)) +import qualified Data.Vector.Strict as V +import Data.Word (Word16, Word64) +import Test.Cardano.Base.Bytes (genByteString) +import Test.QuickCheck (Gen, choose, chooseInt, elements, shuffle, vectorOf) +import Test.QuickCheck.Gen (unGen) +import Test.QuickCheck.Random (mkQCGen) + +-- | Generate a 'LeiosSigningKey' from a uniformly random seed of the +-- algorithm's expected size. +genLeiosSigningKey :: Gen LeiosSigningKey +genLeiosSigningKey = do + let seedLen = fromIntegral @Word @Int (seedSizeDSIGN (Proxy @LeiosDSIGN)) + seedBytes <- genByteString seedLen + pure $ genKeyDSIGN @LeiosDSIGN (mkSeedFromBytes seedBytes) + +-- | Generate a real BLS 'LeiosSignature' by signing a random message with a +-- freshly-generated signing key. Suitable as a byte-generator source for +-- CDDL specs that need on-wire bytes which round-trip through +-- 'Cardano.Crypto.DSIGN.rawDeserialiseSigDSIGN' — uniformly random 48-byte +-- strings do /not/ decode to valid BLS G1 points and will crash there. +genLeiosSignature :: Gen LeiosSignature +genLeiosSignature = do + sk <- genLeiosSigningKey + msgLen <- choose (0, 256) + msg <- genByteString msgLen + pure $ signDSIGN leiosSignContext msg sk + +-- | Generate a real, canonical 'LeiosCert' by building a fresh committee +-- and aggregating a non-empty subset of its members' signatures over a +-- random message. The cert is structurally valid (bitfield length matches +-- the committee, aggregate signature is well-formed) but the committee is +-- not returned — suitable for CBOR / AST-shape tests, not for +-- protocol-acceptance tests in downstream packages. +-- +-- Coverage of bitfield byte-length boundaries (CBOR uint widths > 256 +-- bytes) is not exercised here; that belongs in this package's own test +-- suite, not in the shared testlib. +genLeiosCert :: Gen LeiosCert +genLeiosCert = do + n <- elements [1, 8, 9, 16, 17, 24] + sks <- vectorOf n genLeiosSigningKey + let committee = + LeiosCommittee . V.fromList $ + [LeiosVoter (1 % toInteger n) (deriveVerKeyDSIGN sk) | sk <- sks] + k <- chooseInt (1, n) + signerIxs <- take k <$> shuffle [0 .. n - 1] + msgLen <- choose (0, 64) + msg <- genByteString msgLen + let sigs = + Map.fromList + [ (LeiosVoterId (fromIntegral @Int @Word16 i), signDSIGN leiosSignContext msg (sks !! i)) + | i <- signerIxs + ] + case aggregateLeiosCert committee sigs of + Right cert -> pure cert + Left e -> error ("genLeiosCert: aggregation failed: " <> show e) + +-- | Deterministically evaluate a QuickCheck 'Gen' at a fixed seed. Useful for +-- pinning a single value (e.g. for golden tests) without going through +-- 'Test.QuickCheck.generate' in 'IO'. +generateWith :: Gen a -> Word64 -> a +generateWith gen seed = unGen gen (mkQCGen (fromIntegral @Word64 @Int seed)) 30 diff --git a/cardano-crypto-wallet/src/Cardano/Crypto/WalletHD/Encrypted.hs b/cardano-crypto-wallet/src/Cardano/Crypto/WalletHD/Encrypted.hs index 49ce85493..b5a2a83c1 100644 --- a/cardano-crypto-wallet/src/Cardano/Crypto/WalletHD/Encrypted.hs +++ b/cardano-crypto-wallet/src/Cardano/Crypto/WalletHD/Encrypted.hs @@ -289,7 +289,10 @@ unEncryptedKey (EncryptedKey e) = e encryptedCreate :: (ByteArrayAccess passphrase, ByteArrayAccess secret, ByteArrayAccess cc) => - secret -> passphrase -> cc -> IO (Either XPrvError EncryptedKey) + secret -> + passphrase -> + cc -> + IO (Either XPrvError EncryptedKey) encryptedCreate sec pass cc | B.length sec /= 32 = pure (Left XPrvInvalidSecretKey) | B.length cc /= ccSize = pure (Left XPrvInvalidChainCode) @@ -303,7 +306,9 @@ encryptedCreate sec pass cc encryptedCreateDirectWithTweak :: (ByteArrayAccess passphrase, ByteArrayAccess secret) => - secret -> passphrase -> IO (Either XPrvError EncryptedKey) + secret -> + passphrase -> + IO (Either XPrvError EncryptedKey) encryptedCreateDirectWithTweak sec pass | B.length sec /= 96 = pure (Left XPrvInvalidSecretKey) | otherwise = do @@ -316,7 +321,9 @@ encryptedCreateDirectWithTweak sec pass encryptedValidatePassphrase :: ByteArrayAccess passphrase => - EncryptedKey -> passphrase -> IO (Either XPrvError ()) + EncryptedKey -> + passphrase -> + IO (Either XPrvError ()) encryptedValidatePassphrase ekey pass = do emat <- decryptKeyMaterial ekey pass case emat of @@ -327,7 +334,10 @@ encryptedValidatePassphrase ekey pass = do encryptedChangePass :: (ByteArrayAccess oldPassPhrase, ByteArrayAccess newPassPhrase) => - oldPassPhrase -> newPassPhrase -> EncryptedKey -> IO (Either XPrvError EncryptedKey) + oldPassPhrase -> + newPassPhrase -> + EncryptedKey -> + IO (Either XPrvError EncryptedKey) encryptedChangePass oldPass newPass ekey = mask $ \restore -> do emat <- restore (decryptKeyMaterial ekey oldPass) @@ -338,7 +348,10 @@ encryptedChangePass oldPass newPass ekey = encryptedSign :: (ByteArrayAccess passphrase, ByteArrayAccess msg) => - EncryptedKey -> passphrase -> msg -> IO (Either XPrvError Signature) + EncryptedKey -> + passphrase -> + msg -> + IO (Either XPrvError Signature) encryptedSign ekey pass msg = mask $ \restore -> do emat <- restore (decryptKeyMaterial ekey pass) @@ -429,7 +442,9 @@ encryptedChainCode (EncryptedKey ekey) = -- done with it. encryptedKeyMaterial :: ByteArrayAccess passphrase => - EncryptedKey -> passphrase -> IO (Either XPrvError (MLockedSizedBytes 64)) + EncryptedKey -> + passphrase -> + IO (Either XPrvError (MLockedSizedBytes 64)) encryptedKeyMaterial ekey pass = do emat <- decryptKeyMaterial ekey pass case emat of @@ -580,7 +595,9 @@ decodeAadFields = do decryptKeyMaterial :: ByteArrayAccess passphrase => - EncryptedKey -> passphrase -> IO (Either XPrvError KeyMaterial) + EncryptedKey -> + passphrase -> + IO (Either XPrvError KeyMaterial) decryptKeyMaterial ekey pass = case encryptedKeyFormat ekey of LegacyV1 -> pure (Left XPrvDecodeError) @@ -588,7 +605,9 @@ decryptKeyMaterial ekey pass = v2Decrypt :: ByteArrayAccess passphrase => - EncryptedKey -> passphrase -> IO (Either XPrvError KeyMaterial) + EncryptedKey -> + passphrase -> + IO (Either XPrvError KeyMaterial) v2Decrypt (EncryptedKey bs) pass = case decodeV2Envelope bs of Left err -> pure (Left err) @@ -630,7 +649,9 @@ v2Decrypt (EncryptedKey bs) pass = wrapKeyMaterial :: ByteArrayAccess passphrase => - passphrase -> KeyMaterial -> IO (Either XPrvError EncryptedKey) + passphrase -> + KeyMaterial -> + IO (Either XPrvError EncryptedKey) wrapKeyMaterial pass material = do eVal <- validateKeyMaterial material case eVal of @@ -725,7 +746,9 @@ withEncryptedKeyOutput onFailure action = legacyMaterialFromSecret :: (ByteArrayAccess secret, ByteArrayAccess cc) => - secret -> cc -> IO (Either XPrvError KeyMaterial) + secret -> + cc -> + IO (Either XPrvError KeyMaterial) legacyMaterialFromSecret sec cc = withEncryptedKeyOutput XPrvInvalidSecretKey $ \outPtr -> withByteArray sec $ \psec -> @@ -756,7 +779,9 @@ legacyDerivePrivate dscheme parent childIndex = deriveWrappingKey :: ByteArrayAccess passphrase => - passphrase -> ByteString -> IO (Either XPrvError B.ScrubbedBytes) + passphrase -> + ByteString -> + IO (Either XPrvError B.ScrubbedBytes) deriveWrappingKey pass salt | BS.length salt /= saltSize = pure (Left XPrvInvalidSaltLength) | otherwise = do