-
Notifications
You must be signed in to change notification settings - Fork 30
Praos headers validation properties and generators #1285
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
jasagredo
merged 11 commits into
IntersectMBO:main
from
abailly:abailly/generate-headers
Nov 14, 2024
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
a15fcc5
Provide first integrated tools and tests for header validation
abailly e3cf89b
[wip] Make mutation depend on header to ensure consistency
abailly e6c5f32
Add changelog entry
abailly 86c337e
Add Paths module to autogen section
abailly 8516152
Remove unneeded imports and traces
abailly 5bd0a37
Add missing exports
abailly b2be80c
Format cabal files w/ cabal-gild
abailly 76ceb6f
Added changelog entry for o-c-cardano
abailly c5eeeb2
Run stylish haskell
abailly a0d5dd2
Address review comments
abailly 0653bac
Address reviewers comments
abailly File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
module GenHeader.Parsers (parseOptions) where | ||
|
||
import Cardano.Tools.Headers (Options (..)) | ||
import Data.Version (showVersion) | ||
import Options.Applicative (Parser, ParserInfo, auto, command, | ||
execParser, help, helper, hsubparser, info, long, metavar, | ||
option, progDesc, short, (<**>)) | ||
import Paths_ouroboros_consensus_cardano (version) | ||
|
||
parseOptions :: IO Options | ||
parseOptions = execParser argsParser | ||
|
||
argsParser :: ParserInfo Options | ||
argsParser = | ||
info | ||
(optionsParser <**> helper) | ||
( progDesc $ | ||
unlines | ||
[ "gen-header - A utility to generate valid and invalid Praos headers for testing purpose" | ||
, "version: " <> showVersion version | ||
] | ||
) | ||
|
||
optionsParser :: Parser Options | ||
optionsParser = | ||
hsubparser | ||
( command "generate" (info generateOptionsParser (progDesc "Generate Praos headers context and valid/invalid headers. Writes JSON formatted context to stdout and headers to stdout.")) | ||
<> command "validate" (info validateOptionsParser (progDesc "Validate a sample of Praos headers within a context. Reads JSON formatted sample from stdin.")) | ||
) | ||
|
||
validateOptionsParser :: Parser Options | ||
validateOptionsParser = pure Validate | ||
|
||
generateOptionsParser :: Parser Options | ||
generateOptionsParser = | ||
Generate <$> countParser | ||
|
||
countParser :: Parser Int | ||
countParser = | ||
option | ||
auto | ||
( long "count" | ||
<> short 'c' | ||
<> metavar "INT" | ||
<> help "Number of headers to generate" | ||
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
-- | This tool generates valid and invalid Cardano headers. | ||
module Main (main) where | ||
|
||
import Cardano.Crypto.Init (cryptoInit) | ||
import Cardano.Tools.Headers (run) | ||
import GenHeader.Parsers (parseOptions) | ||
import Main.Utf8 (withUtf8) | ||
|
||
main :: IO () | ||
main = withUtf8 $ do | ||
cryptoInit | ||
parseOptions >>= run |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
81 changes: 81 additions & 0 deletions
81
ouroboros-consensus-cardano/src/unstable-cardano-tools/Cardano/Tools/Headers.hs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
{-# LANGUAGE LambdaCase #-} | ||
{-# LANGUAGE NamedFieldPuns #-} | ||
{-# LANGUAGE OverloadedStrings #-} | ||
{-# LANGUAGE TypeApplications #-} | ||
|
||
-- | Tooling to generate and validate (Praos) headers. | ||
module Cardano.Tools.Headers ( | ||
Options (..) | ||
, ValidationResult (..) | ||
, run | ||
, validate | ||
) where | ||
|
||
import Cardano.Crypto.DSIGN (deriveVerKeyDSIGN) | ||
import Cardano.Crypto.VRF | ||
(VRFAlgorithm (deriveVerKeyVRF, hashVerKeyVRF)) | ||
import Cardano.Ledger.Api (ConwayEra, StandardCrypto) | ||
import Cardano.Ledger.Coin (Coin (..)) | ||
import Cardano.Ledger.Compactible (toCompact) | ||
import Cardano.Ledger.Keys (VKey (..), hashKey) | ||
import Cardano.Ledger.PoolDistr (IndividualPoolStake (..)) | ||
import Cardano.Prelude (ExitCode (..), exitWith, forM_, hPutStrLn, | ||
stderr) | ||
import Control.Monad.Except (runExcept) | ||
import qualified Data.Aeson as Json | ||
import qualified Data.ByteString.Lazy as LBS | ||
import qualified Data.Map as Map | ||
import Data.Maybe (fromJust) | ||
import Ouroboros.Consensus.Block (validateView) | ||
import Ouroboros.Consensus.Protocol.Praos (Praos, | ||
doValidateKESSignature, doValidateVRFSignature) | ||
import Ouroboros.Consensus.Shelley.HFEras () | ||
import Ouroboros.Consensus.Shelley.Ledger (ShelleyBlock, | ||
mkShelleyHeader) | ||
import Ouroboros.Consensus.Shelley.Protocol.Praos () | ||
import Test.Ouroboros.Consensus.Protocol.Praos.Header | ||
(GeneratorContext (..), MutatedHeader (..), Mutation (..), | ||
Sample (..), expectedError, generateSamples, header, | ||
mutation) | ||
|
||
type ConwayBlock = ShelleyBlock (Praos StandardCrypto) (ConwayEra StandardCrypto) | ||
|
||
-- * Running Generator | ||
data Options | ||
= Generate Int | ||
| Validate | ||
|
||
run :: Options -> IO () | ||
run = \case | ||
Generate n -> do | ||
sample <- generateSamples n | ||
LBS.putStr $ Json.encode sample <> "\n" | ||
Validate -> | ||
Json.eitherDecode <$> LBS.getContents >>= \case | ||
Left err -> hPutStrLn stderr err >> exitWith (ExitFailure 1) | ||
Right Sample{sample} -> | ||
forM_ sample $ \(context, mutatedHeader) -> do | ||
print $ validate context mutatedHeader | ||
|
||
data ValidationResult = Valid !Mutation | Invalid !Mutation !String | ||
deriving (Eq, Show) | ||
|
||
validate :: GeneratorContext -> MutatedHeader -> ValidationResult | ||
abailly marked this conversation as resolved.
Show resolved
Hide resolved
|
||
validate context MutatedHeader{header, mutation} = | ||
case (runExcept $ validateKES >> validateVRF, mutation) of | ||
(Left err, mut) | expectedError mut err -> Valid mut | ||
(Left err, mut) -> Invalid mut (show err) | ||
(Right _, NoMutation) -> Valid NoMutation | ||
(Right _, mut) -> Invalid mut $ "Expected error from mutation " <> show mut <> ", but validation succeeded" | ||
where | ||
GeneratorContext{praosSlotsPerKESPeriod, praosMaxKESEvo, nonce, coldSignKey, vrfSignKey, ocertCounters, activeSlotCoeff} = context | ||
-- TODO: get these from the context | ||
coin = fromJust . toCompact . Coin | ||
ownsAllStake vrfKey = IndividualPoolStake 1 (coin 1) vrfKey | ||
poolDistr = Map.fromList [(poolId, ownsAllStake hashVRFKey)] | ||
abailly marked this conversation as resolved.
Show resolved
Hide resolved
|
||
poolId = hashKey $ VKey $ deriveVerKeyDSIGN coldSignKey | ||
hashVRFKey = hashVerKeyVRF $ deriveVerKeyVRF vrfSignKey | ||
|
||
headerView = validateView @ConwayBlock undefined (mkShelleyHeader header) | ||
validateKES = doValidateKESSignature praosMaxKESEvo praosSlotsPerKESPeriod poolDistr ocertCounters headerView | ||
validateVRF = doValidateVRFSignature nonce poolDistr activeSlotCoeff headerView |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
50 changes: 50 additions & 0 deletions
50
ouroboros-consensus-cardano/test/tools-test/Test/Cardano/Tools/Headers.hs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
module Test.Cardano.Tools.Headers (tests) where | ||
|
||
import Cardano.Tools.Headers (ValidationResult (..), validate) | ||
import qualified Data.Aeson as Json | ||
import Data.Function ((&)) | ||
import qualified Data.Text.Lazy as LT | ||
import Data.Text.Lazy.Encoding (decodeUtf8) | ||
import Test.Ouroboros.Consensus.Protocol.Praos.Header (genContext, | ||
genMutatedHeader, genSample) | ||
import Test.QuickCheck (Property, counterexample, forAll, forAllBlind, | ||
label, property, (===)) | ||
import Test.Tasty (TestTree, testGroup) | ||
import Test.Tasty.QuickCheck (testProperty) | ||
|
||
tests :: TestTree | ||
tests = | ||
testGroup | ||
"HeaderValidation" | ||
[ testProperty "roundtrip To/FromJSON samples" prop_roundtrip_json_samples | ||
, testProperty "validate legit header" prop_validate_legit_header | ||
] | ||
|
||
prop_roundtrip_json_samples :: Property | ||
prop_roundtrip_json_samples = | ||
forAll genSample $ \sample -> | ||
let encoded = Json.encode sample | ||
decoded = Json.eitherDecode encoded | ||
in decoded === Right sample | ||
|
||
prop_validate_legit_header :: Property | ||
prop_validate_legit_header = | ||
forAllBlind genContext $ \context -> | ||
forAllBlind (genMutatedHeader context) $ \(context', header) -> | ||
annotate context' header $ | ||
case validate context' header of | ||
Valid mut -> property True & label (show mut) | ||
Invalid mut err -> property False & counterexample ("Expected: " <> show mut <> "\nError: " <> err) | ||
where | ||
annotate context header = | ||
counterexample | ||
( unlines $ | ||
[ "context:" | ||
, asJson context | ||
, "header:" | ||
, show header | ||
] | ||
) | ||
|
||
asJson :: (Json.ToJSON a) => a -> String | ||
asJson = LT.unpack . decodeUtf8 . Json.encode |
4 changes: 4 additions & 0 deletions
4
...onsensus-protocol/changelog.d/20241029_062000_abailly_header_validation_test.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
### Patch | ||
|
||
- Expose functions to simplify thorough testing of header validation | ||
logic, and introduce generators and properties to actually test it. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.