-- Hoogle documentation, generated by Haddock
-- See Hoogle, http://www.haskell.org/hoogle/


-- | The blockchain layer of Cardano
--   
--   The blockchain layer of Cardano
@package cardano-ledger
@version 0.1.0.0

module Cardano.Chain.Common

-- | A linear equation on the transaction size. Represents the <tt>s -&gt;
--   a + b*s</tt> function where <tt>s</tt> is the transaction size in
--   bytes, <tt>a</tt> and <tt>b</tt> are constant coefficients.
data TxSizeLinear
TxSizeLinear :: !Lovelace -> !Rational -> TxSizeLinear
txSizeLinearMinValue :: TxSizeLinear -> Lovelace
calculateTxSizeLinear :: TxSizeLinear -> Natural -> Either LovelaceError Lovelace

-- | Transaction fee policy represents a formula to compute the minimal
--   allowed Fee for a transaction. Transactions with lesser fees won't be
--   accepted. The Minimal fee may depend on the properties of a
--   transaction (for example, its Size in bytes), so the policy can't be
--   represented simply as a number.
--   
--   Recall that a transaction fee is the difference between the sum of its
--   Inputs and the sum of its outputs. The transaction is accepted when
--   <tt>minimal_fee(tx) &lt;= fee(tx)</tt>, where <tt>minimal_fee</tt> is
--   the function defined By the policy.
--   
--   The policy can change during the lifetime of the blockchain (using the
--   Update mechanism). At the moment we have just one policy type (a
--   linear Equation on the transaction size), but in the future other
--   policies may Be added. To make this future-proof, we also have an
--   "unknown" policy used By older node versions (the ones that haven't
--   updated yet).
data TxFeePolicy
TxFeePolicyTxSizeLinear :: !TxSizeLinear -> TxFeePolicy

-- | A <a>KeyHash</a> refers to a <a>VerificationKey</a>
newtype KeyHash
KeyHash :: AddressHash VerificationKey -> KeyHash
[unKeyHash] :: KeyHash -> AddressHash VerificationKey
hashKey :: VerificationKey -> KeyHash
data NetworkMagic
NetworkMainOrStage :: NetworkMagic
NetworkTestnet :: {-# UNPACK #-} !Word32 -> NetworkMagic
makeNetworkMagic :: AProtocolMagic a -> NetworkMagic

-- | Data type for root of Merkle tree
newtype MerkleRoot a
MerkleRoot :: Hash Raw -> MerkleRoot a

-- | returns root <a>Hash</a> of Merkle Tree
[getMerkleRoot] :: MerkleRoot a -> Hash Raw
data MerkleTree a
MerkleEmpty :: MerkleTree a
MerkleTree :: !Word32 -> !MerkleNode a -> MerkleTree a

-- | Returns root of Merkle tree
mtRoot :: MerkleTree a -> MerkleRoot a

-- | Smart constructor for <a>MerkleTree</a>
mkMerkleTree :: ToCBOR a => [a] -> MerkleTree a

-- | Reconstruct a <a>MerkleTree</a> from a decoded list of items
mkMerkleTreeDecoded :: [Annotated a ByteString] -> MerkleTree a
data MerkleNode a

-- | MerkleBranch mRoot mLeft mRight
MerkleBranch :: !MerkleRoot a -> !MerkleNode a -> !MerkleNode a -> MerkleNode a

-- | MerkleLeaf mRoot mVal
MerkleLeaf :: !MerkleRoot a -> a -> MerkleNode a
mkBranch :: MerkleNode a -> MerkleNode a -> MerkleNode a
mkLeaf :: forall a. ToCBOR a => a -> MerkleNode a
mkLeafDecoded :: Annotated a ByteString -> MerkleNode a

-- | <a>LovelacePortion</a> is a legacy Byron type that we keep only for
--   compatibility. It was originally intended to represent a fraction of
--   stake in the system. It is used only for the thresholds used in the
--   update system rules, most of which are now themselves unused. The
--   remaining case is no longer interpreted as a fraction of all stake,
--   but as a fraction of the number of genesis keys.
--   
--   It has enormous precision, due to the fact that it was originally
--   intended to represent a fraction of all stake and can cover the
--   precision of all the Lovelace in the system.
--   
--   It is represented as a rational nominator with a fixed implicit
--   denominator of 1e15. So the nominator must be in the range
--   <tt>[0..1e15]</tt>. This is also the representation used on-chain (in
--   update proposals) and in the JSON genesis file.
--   
--   It is interpreted as a <a>Rational</a> via the provided conversion
--   functions.
data LovelacePortion

-- | Make a <a>LovelacePortion</a> from a <a>Rational</a> which must be in
--   the range <tt>[0..1]</tt>.
rationalToLovelacePortion :: Rational -> LovelacePortion

-- | Turn a <a>LovelacePortion</a> into a <a>Rational</a> in the range
--   <tt>[0..1]</tt>.
lovelacePortionToRational :: LovelacePortion -> Rational

-- | Lovelace is the least possible unit of currency
data Lovelace
data LovelaceError
LovelaceOverflow :: Word64 -> LovelaceError
LovelaceTooLarge :: Integer -> LovelaceError
LovelaceTooSmall :: Integer -> LovelaceError
LovelaceUnderflow :: Word64 -> Word64 -> LovelaceError

-- | Maximal possible value of <a>Lovelace</a>
maxLovelaceVal :: Word64

-- | Constructor for <a>Lovelace</a> returning <a>LovelaceError</a> when
--   <tt>c</tt> exceeds <a>maxLovelaceVal</a>
mkLovelace :: Word64 -> Either LovelaceError Lovelace

-- | Construct a <a>Lovelace</a> from a <a>KnownNat</a>, known to be less
--   than <a>maxLovelaceVal</a>
mkKnownLovelace :: forall n. (KnownNat n, n <= 45000000000000000) => Lovelace

-- | Lovelace formatter which restricts type.
lovelaceF :: Format r (Lovelace -> r)

-- | Unwraps <a>Lovelace</a>. It's called “unsafe” so that people wouldn't
--   use it willy-nilly if they want to sum lovelace or something. It's
--   actually safe.
unsafeGetLovelace :: Lovelace -> Word64
lovelaceToInteger :: Lovelace -> Integer
integerToLovelace :: Integer -> Either LovelaceError Lovelace

-- | Compute sum of all lovelace in container. Result is <a>Integer</a> as
--   a protection against possible overflow.
sumLovelace :: (Foldable t, Functor t) => t Lovelace -> Either LovelaceError Lovelace

-- | Addition of lovelace, returning <a>LovelaceError</a> in case of
--   overflow
addLovelace :: Lovelace -> Lovelace -> Either LovelaceError Lovelace

-- | Subtraction of lovelace, returning <a>LovelaceError</a> on underflow
subLovelace :: Lovelace -> Lovelace -> Either LovelaceError Lovelace

-- | Scale a <a>Lovelace</a> by an <a>Integral</a> factor, returning
--   <a>LovelaceError</a> when the result is too large
scaleLovelace :: Integral b => Lovelace -> b -> Either LovelaceError Lovelace

-- | Scale a <a>Lovelace</a> by a rational factor, rounding down.
scaleLovelaceRational :: Lovelace -> Rational -> Lovelace

-- | Scale a <a>Lovelace</a> by a rational factor, rounding up.
scaleLovelaceRationalUp :: Lovelace -> Rational -> Lovelace

-- | Integer division of a <a>Lovelace</a> by an <a>Integral</a> factor
divLovelace :: Integral b => Lovelace -> b -> Either LovelaceError Lovelace

-- | Integer modulus of a <a>Lovelace</a> by an <a>Integral</a> factor
modLovelace :: Integral b => Lovelace -> b -> Either LovelaceError Lovelace

-- | A compact in-memory representation for an <a>Address</a>.
--   
--   Convert using <a>toCompactAddress</a> and <a>fromCompactAddress</a>.
data CompactAddress
toCompactAddress :: Address -> CompactAddress
fromCompactAddress :: CompactAddress -> Address
unsafeGetCompactAddress :: CompactAddress -> ShortByteString

-- | Chain difficulty represents necessary effort to generate a chain. In
--   the simplest case it can be number of blocks in chain.
newtype ChainDifficulty
ChainDifficulty :: Word64 -> ChainDifficulty
[unChainDifficulty] :: ChainDifficulty -> Word64
dropChainDifficulty :: Dropper s

-- | This is an alias for <a>encodeNestedCbor</a>.
--   
--   This function is used to handle the case of a known type, but
--   compatible with the encoding used by <a>encodeUnknownCborDataItem</a>.
encodeKnownCborDataItem :: ToCBOR a => a -> Encoding

-- | This is an alias for <a>encodeNestedCborBytes</a>, so all its details
--   apply.
--   
--   This function is used to handle the case of an unknown type, so it
--   takes an opaque blob that is the representation of the value of the
--   unknown type.
encodeUnknownCborDataItem :: LByteString -> Encoding
knownCborDataItemSizeExpr :: Size -> Size
unknownCborDataItemSizeExpr :: Size -> Size

-- | This is an alias for <a>decodeNestedCbor</a>.
--   
--   This function is used to handle the case of a known type, but
--   compatible with the encoding used by <a>decodeUnknownCborDataItem</a>.
decodeKnownCborDataItem :: FromCBOR a => Decoder s a

-- | This is an alias for <a>decodeNestedCborBytes</a>, so all its details
--   apply.
--   
--   This function is used to handle the case of an unknown type, so it
--   returns an opaque blob that is the representation of the value of the
--   unknown type.
decodeUnknownCborDataItem :: Decoder s ByteString

-- | Encodes a value of type <tt>a</tt>, protecting it from accidental
--   corruption by protecting it with a CRC.
encodeCrcProtected :: ToCBOR a => a -> Encoding
encodedCrcProtectedSizeExpr :: forall a. ToCBOR a => (forall t. ToCBOR t => Proxy t -> Size) -> Proxy a -> Size

-- | Decodes a CBOR blob into a value of type <tt>a</tt>, checking the
--   serialised CRC corresponds to the computed one
decodeCrcProtected :: forall s a. FromCBOR a => Decoder s a
newtype BlockCount
BlockCount :: Word64 -> BlockCount
[unBlockCount] :: BlockCount -> Word64

-- | Representation of unparsed fields in Attributes. Newtype wrapper is
--   used for clear backward compatibility between previous representation
--   (which was just a single ByteString) during transition from Store to
--   CBOR.
newtype UnparsedFields
UnparsedFields :: Map Word8 ByteString -> UnparsedFields

-- | Convenient wrapper for the datatype to represent it (in binary format)
--   as k-v map
data Attributes h
Attributes :: !h -> !UnparsedFields -> Attributes h

-- | Data, containing known keys (deserialized)
[attrData] :: Attributes h -> !h

-- | Remaining, unparsed fields
[attrRemain] :: Attributes h -> !UnparsedFields

-- | Check whether all data from <a>Attributes</a> is known, i. e. was
--   successfully parsed into some structured data
attributesAreKnown :: Attributes a -> Bool
unknownAttributesLength :: Attributes a -> Int
toCBORAttributes :: forall t. [(Word8, t -> ByteString)] -> Attributes t -> Encoding
fromCBORAttributes :: forall t s. t -> (Word8 -> ByteString -> t -> Decoder s (Maybe t)) -> Decoder s (Attributes t)
mkAttributes :: h -> Attributes h
dropAttributes :: Dropper s

-- | Drop `Attributes ()` making sure that the <a>UnparsedFields</a> are
--   empty
dropEmptyAttributes :: Dropper s

-- | Data which is bound to an address and must be revealed in order to
--   spend lovelace belonging to this address.
data AddrSpendingData

-- | Funds can be spent by revealing a <a>VerificationKey</a> and providing
--   a valid signature
VerKeyASD :: !VerificationKey -> AddrSpendingData

-- | Funds can be spent by revealing a <a>RedeemVerificationKey</a> and
--   providing a valid signature
RedeemASD :: !RedeemVerificationKey -> AddrSpendingData

-- | Type of an address. It corresponds to constructors of
--   <a>AddrSpendingData</a>. It's separated, because <tt>Address</tt>
--   doesn't store <a>AddrSpendingData</a>, but we want to know its type.
data AddrType
ATVerKey :: AddrType
ATRedeem :: AddrType

-- | Convert <a>AddrSpendingData</a> to the corresponding <a>AddrType</a>
addrSpendingDataToType :: AddrSpendingData -> AddrType

-- | Hash used to identify address.
type AddressHash = AbstractHash Blake2b_224
addressHash :: ToCBOR a => a -> AddressHash a
unsafeAddressHash :: ToCBOR a => a -> AddressHash b

-- | <a>Address</a> is where you can send Lovelace
data Address
Address :: !AddressHash Address' -> !Attributes AddrAttributes -> !AddrType -> Address

-- | Root of imaginary pseudo Merkle tree stored in this address.
[addrRoot] :: Address -> !AddressHash Address'

-- | Attributes associated with this address.
[addrAttributes] :: Address -> !Attributes AddrAttributes

-- | The type of this address. Should correspond to
--   <a>AddrSpendingData</a>, but it can't be checked statically, because
--   spending data is hashed.
[addrType] :: Address -> !AddrType

-- | Hash of this data is stored in <a>Address</a>. This type exists mostly
--   for internal usage.
newtype Address'
Address' :: (AddrType, AddrSpendingData, Attributes AddrAttributes) -> Address'
[unAddress'] :: Address' -> (AddrType, AddrSpendingData, Attributes AddrAttributes)

-- | Specialized formatter for <a>Address</a>
addressF :: Format r (Address -> r)

-- | A formatter showing guts of an <a>Address</a>
addressDetailedF :: Format r (Address -> r)

-- | A function which decodes base58-encoded <a>Address</a>

-- | <i>Deprecated: Use decodeAddressBase58 instead</i>
fromCBORTextAddress :: Text -> Either DecoderError Address

-- | Check whether given <a>AddrSpendingData</a> corresponds to given
--   <a>Address</a>
checkAddrSpendingData :: AddrSpendingData -> Address -> Bool

-- | Check if given <a>Address</a> is created from given
--   <a>VerificationKey</a>
checkVerKeyAddress :: VerificationKey -> Address -> Bool

-- | Check if given <a>Address</a> is created from given
--   <a>RedeemVerificationKey</a>
checkRedeemAddress :: RedeemVerificationKey -> Address -> Bool
addrToBase58 :: Address -> ByteString
toCBORAddr :: Address -> Encoding
toCBORAddrCRC32 :: Address -> Encoding

-- | Decode an address from Base58 encoded Text.
decodeAddressBase58 :: Text -> Either DecoderError Address

-- | Encode an address to Text. `decodeAddressBase58 (encodeAddressBase58
--   x) === Right x`
encodeAddressBase58 :: Address -> Text

-- | Get <a>AddrAttributes</a> from <a>Address</a>
addrAttributesUnwrapped :: Address -> AddrAttributes

-- | Get <a>NetworkMagic</a> from <a>Address</a>
addrNetworkMagic :: Address -> NetworkMagic

-- | Check whether an <a>Address</a> is redeem address
isRedeemAddress :: Address -> Bool

-- | Make an <a>Address</a> from spending data and attributes.
makeAddress :: AddrSpendingData -> AddrAttributes -> Address

-- | A function for making an address from <a>VerificationKey</a>
makeVerKeyAddress :: NetworkMagic -> VerificationKey -> Address

-- | A function for making an HDW address
makeVerKeyHdwAddress :: NetworkMagic -> HDAddressPayload -> VerificationKey -> Address

-- | A function for making an address from <a>RedeemVerificationKey</a>
makeRedeemAddress :: NetworkMagic -> RedeemVerificationKey -> Address

-- | Additional information stored along with address. It's intended to be
--   put into <a>Attributes</a> data type to make it extensible with
--   softfork.
data AddrAttributes
AddrAttributes :: !Maybe HDAddressPayload -> !NetworkMagic -> AddrAttributes
[aaVKDerivationPath] :: AddrAttributes -> !Maybe HDAddressPayload
[aaNetworkMagic] :: AddrAttributes -> !NetworkMagic

-- | HDAddressPayload is a specific address attribute that was used by the
--   Cardano wallet at mainnet launch, prior to moving to a BIP-44 style
--   scheme.
--   
--   It consisted of
--   
--   <ul>
--   <li>serialiazed and encrypted using HDPassphrase derivation path from
--   the root key to given descendant key (using ChaChaPoly1305
--   algorithm)</li>
--   <li>cryptographic tag</li>
--   </ul>
--   
--   It is still distinguished as an attribute, but not used by the ledger,
--   because the attributes size limits treat this attribute specially.
newtype HDAddressPayload
HDAddressPayload :: ByteString -> HDAddressPayload
[getHDAddressPayload] :: HDAddressPayload -> ByteString


-- | Non-configurable constants For configurable constants, see
--   Cardano.Genesis.Configuration.
module Cardano.Chain.Constants

-- | Length of shared seed.
sharedSeedLength :: Integral a => a


-- | Constants derived from security parameter
--   
--   TODO: Find a better home for these
module Cardano.Chain.ProtocolConstants

-- | Security parameter expressed in number of slots. It uses chain quality
--   property. It's basically <tt>blkSecurityParam /
--   chainQualityThreshold</tt>.
kSlotSecurityParam :: BlockCount -> SlotCount

-- | Update stability parameter expressed in number of slots. This is the
--   time between an protocol version update receiving its final
--   endorsement and being accepted, and is set to double the security
--   param.
--   
--   This extra safety margin is required because an update in the protocol
--   version may trigger a hard fork, which can change "era"-level
--   parameters such as slot length and the number of slots per epoch. As
--   such, the consensus layer wishes to always have a margin between such
--   an update being _certain to happen_ and it actually happening.
--   
--   For full details, you can see
--   <a>https://github.com/input-output-hk/cardano-ledger-specs/issues/1288</a>
kUpdateStabilityParam :: BlockCount -> SlotCount

-- | Minimal chain quality (number of blocks divided by number of slots)
--   necessary for security of the system.
kChainQualityThreshold :: Fractional f => BlockCount -> f

-- | Number of slots inside one epoch
kEpochSlots :: BlockCount -> EpochSlots

module Cardano.Chain.Slotting

-- | <a>SlotNumber</a> is an absolute slot number from the beginning of
--   time
--   
--   <a>SlotNumber</a> is held in a <a>Word64</a>. Assuming a slot every 20
--   seconds, <a>Word64</a> is sufficient for slot indices for 10^13 years.
newtype SlotNumber
SlotNumber :: Word64 -> SlotNumber
[unSlotNumber] :: SlotNumber -> Word64

-- | Increase a <a>SlotNumber</a> by <a>SlotCount</a>
addSlotCount :: SlotCount -> SlotNumber -> SlotNumber

-- | Decrease a <a>SlotNumber</a> by <a>SlotCount</a>, going no lower than
--   0
subSlotCount :: SlotCount -> SlotNumber -> SlotNumber

-- | A number of slots
newtype SlotCount
SlotCount :: Word64 -> SlotCount
[unSlotCount] :: SlotCount -> Word64

-- | The number of slots per epoch.
newtype EpochSlots
EpochSlots :: Word64 -> EpochSlots
[unEpochSlots] :: EpochSlots -> Word64

-- | Data with an accompanying slots per epoch context.
data WithEpochSlots a
WithEpochSlots :: EpochSlots -> a -> WithEpochSlots a
[epochSlots] :: WithEpochSlots a -> EpochSlots
[unWithEpochSlots] :: WithEpochSlots a -> a

-- | Calculate the first slot in an epoch.
--   
--   Note that this function will give an undetermined result if Byron is
--   not the first and only era - a more robust method should use
--   <tt>EpochInfo</tt> from cardano-slotting.
epochFirstSlot :: EpochSlots -> EpochNumber -> SlotNumber

-- | Index of epoch.
newtype EpochNumber
EpochNumber :: Word64 -> EpochNumber
[getEpochNumber] :: EpochNumber -> Word64

-- | Bootstrap era is ongoing until stakes are unlocked. The reward era
--   starts from the epoch specified as the epoch that unlocks stakes:
--   
--   <pre>
--                       [unlock stake epoch]
--                               /
--   Epoch: ...  E-3  E-2  E-1   E+0  E+1  E+2  E+3  ...
--          ------------------ | -----------------------
--               Bootstrap era   Reward era
--   
--   </pre>
isBootstrapEra :: EpochNumber -> EpochNumber -> Bool

-- | <a>EpochAndSlotCount</a> identifies a slot by its <a>EpochNumber</a>
--   and the number of slots into the epoch that it sits
data EpochAndSlotCount
EpochAndSlotCount :: !EpochNumber -> !SlotCount -> EpochAndSlotCount
[epochNo] :: EpochAndSlotCount -> !EpochNumber
[slotCount] :: EpochAndSlotCount -> !SlotCount

-- | Flatten <a>EpochAndSlotCount</a> into a single absolute
--   <a>SlotNumber</a>
toSlotNumber :: EpochSlots -> EpochAndSlotCount -> SlotNumber

-- | Construct a <a>EpochAndSlotCount</a> from a <a>SlotNumber</a>, using a
--   given <a>EpochSlots</a>
fromSlotNumber :: EpochSlots -> SlotNumber -> EpochAndSlotCount
slotNumberEpoch :: EpochSlots -> SlotNumber -> EpochNumber

module Cardano.Chain.Delegation.Validation.Scheduling
data Environment
Environment :: !Annotated ProtocolMagicId ByteString -> !Set KeyHash -> !EpochNumber -> !SlotNumber -> !BlockCount -> Environment
[protocolMagic] :: Environment -> !Annotated ProtocolMagicId ByteString
[allowedDelegators] :: Environment -> !Set KeyHash
[currentEpoch] :: Environment -> !EpochNumber
[currentSlot] :: Environment -> !SlotNumber
[k] :: Environment -> !BlockCount
data State
State :: !Seq ScheduledDelegation -> !Set (EpochNumber, KeyHash) -> State
[scheduledDelegations] :: State -> !Seq ScheduledDelegation
[keyEpochDelegations] :: State -> !Set (EpochNumber, KeyHash)
data Error

-- | The delegation certificate has an invalid signature
InvalidCertificate :: Error

-- | This delegator has already delegated for the given epoch
MultipleDelegationsForEpoch :: EpochNumber -> KeyHash -> Error

-- | This delegator has already delgated in this slot
MultipleDelegationsForSlot :: SlotNumber -> KeyHash -> Error

-- | This delegator is not one of the allowed genesis keys
NonGenesisDelegator :: KeyHash -> Error

-- | This delegation is for a past or for a too future epoch
WrongEpoch :: EpochNumber -> EpochNumber -> Error
data ScheduledDelegation
ScheduledDelegation :: !SlotNumber -> !KeyHash -> !KeyHash -> ScheduledDelegation
[sdSlot] :: ScheduledDelegation -> !SlotNumber
[sdDelegator] :: ScheduledDelegation -> !KeyHash
[sdDelegate] :: ScheduledDelegation -> !KeyHash

-- | Update the delegation <a>State</a> with a <tt>Certificate</tt> if it
--   passes all the validation rules. This is an implementation of the
--   delegation scheduling inference rule from the ledger specification.
scheduleCertificate :: MonadError Error m => Environment -> State -> ACertificate ByteString -> m State
instance Control.DeepSeq.NFData Cardano.Chain.Delegation.Validation.Scheduling.Environment
instance GHC.Generics.Generic Cardano.Chain.Delegation.Validation.Scheduling.Environment
instance GHC.Show.Show Cardano.Chain.Delegation.Validation.Scheduling.Environment
instance GHC.Classes.Eq Cardano.Chain.Delegation.Validation.Scheduling.Environment
instance NoThunks.Class.NoThunks Cardano.Chain.Delegation.Validation.Scheduling.ScheduledDelegation
instance Control.DeepSeq.NFData Cardano.Chain.Delegation.Validation.Scheduling.ScheduledDelegation
instance GHC.Generics.Generic Cardano.Chain.Delegation.Validation.Scheduling.ScheduledDelegation
instance GHC.Show.Show Cardano.Chain.Delegation.Validation.Scheduling.ScheduledDelegation
instance GHC.Classes.Eq Cardano.Chain.Delegation.Validation.Scheduling.ScheduledDelegation
instance NoThunks.Class.NoThunks Cardano.Chain.Delegation.Validation.Scheduling.State
instance Control.DeepSeq.NFData Cardano.Chain.Delegation.Validation.Scheduling.State
instance GHC.Generics.Generic Cardano.Chain.Delegation.Validation.Scheduling.State
instance GHC.Show.Show Cardano.Chain.Delegation.Validation.Scheduling.State
instance GHC.Classes.Eq Cardano.Chain.Delegation.Validation.Scheduling.State
instance GHC.Show.Show Cardano.Chain.Delegation.Validation.Scheduling.Error
instance GHC.Classes.Eq Cardano.Chain.Delegation.Validation.Scheduling.Error
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Delegation.Validation.Scheduling.Error
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Delegation.Validation.Scheduling.Error
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Delegation.Validation.Scheduling.State
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Delegation.Validation.Scheduling.State
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Delegation.Validation.Scheduling.ScheduledDelegation
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Delegation.Validation.Scheduling.ScheduledDelegation

module Cardano.Chain.Delegation

-- | The delegation <a>Payload</a> contains a list of delegation
--   <tt>Certificate</tt>s
data APayload a
UnsafeAPayload :: [ACertificate a] -> a -> APayload a
[getPayload] :: APayload a -> [ACertificate a]
[getAnnotation] :: APayload a -> a
type Payload = APayload ()
unsafePayload :: [Certificate] -> Payload
newtype Map
Map :: Bimap KeyHash KeyHash -> Map
[unMap] :: Map -> Bimap KeyHash KeyHash
memberR :: KeyHash -> Map -> Bool
notMemberR :: KeyHash -> Map -> Bool
pairMember :: (KeyHash, KeyHash) -> Map -> Bool
lookupR :: KeyHash -> Map -> Maybe KeyHash
insert :: KeyHash -> KeyHash -> Map -> Map
fromList :: [(KeyHash, KeyHash)] -> Map
keysSet :: Map -> Set KeyHash
type Certificate = ACertificate ()

-- | Delegation certificate allowing the <tt>delegateVK</tt> to sign blocks
--   on behalf of <tt>issuerVK</tt>
--   
--   Each delegator can publish at most one <a>Certificate</a> per
--   <a>EpochNumber</a>, and that <a>EpochNumber</a> must correspond to the
--   current or next <a>EpochNumber</a> at the time of publishing
data ACertificate a
UnsafeACertificate :: !Annotated EpochNumber a -> !VerificationKey -> !VerificationKey -> !Signature EpochNumber -> !a -> ACertificate a

-- | The epoch from which the delegation is valid
[aEpoch] :: ACertificate a -> !Annotated EpochNumber a

-- | The issuer of the certificate, who delegates their right to sign
--   blocks
[issuerVK] :: ACertificate a -> !VerificationKey

-- | The delegate, who gains the right to sign blocks
[delegateVK] :: ACertificate a -> !VerificationKey

-- | The signature that proves the certificate was issued by
--   <tt>issuerVK</tt>
[signature] :: ACertificate a -> !Signature EpochNumber
[annotation] :: ACertificate a -> !a

-- | A delegation certificate identifier (the <a>Hash</a> of a
--   <a>Certificate</a>).
type CertificateId = Hash Certificate

-- | Create a <a>Certificate</a>, signing it with the provided safe signer.
signCertificate :: ProtocolMagicId -> VerificationKey -> EpochNumber -> SafeSigner -> Certificate

-- | Create a certificate using the provided signature.
unsafeCertificate :: EpochNumber -> VerificationKey -> VerificationKey -> Signature EpochNumber -> Certificate
epoch :: ACertificate a -> EpochNumber
recoverCertificateId :: ACertificate ByteString -> CertificateId

-- | A <a>Certificate</a> is valid if the <a>Signature</a> is valid
isValid :: Annotated ProtocolMagicId ByteString -> ACertificate ByteString -> Bool

module Cardano.Chain.Delegation.Validation.Activation

-- | Maps containing, for each delegator, the active delegation and the
--   slot it became active in.
data State
State :: !Map -> !Map KeyHash SlotNumber -> State
[delegationMap] :: State -> !Map
[delegationSlots] :: State -> !Map KeyHash SlotNumber

-- | Activate a <a>ScheduledDelegation</a> if its activation slot is less
--   than the previous delegation slot for this delegate, otherwise discard
--   it. This is an implementation of the delegation activation rule in the
--   ledger specification.
activateDelegation :: State -> ScheduledDelegation -> State
instance NoThunks.Class.NoThunks Cardano.Chain.Delegation.Validation.Activation.State
instance Control.DeepSeq.NFData Cardano.Chain.Delegation.Validation.Activation.State
instance GHC.Generics.Generic Cardano.Chain.Delegation.Validation.Activation.State
instance GHC.Show.Show Cardano.Chain.Delegation.Validation.Activation.State
instance GHC.Classes.Eq Cardano.Chain.Delegation.Validation.Activation.State
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Delegation.Validation.Activation.State
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Delegation.Validation.Activation.State

module Cardano.Chain.Ssc
data SscPayload
SscPayload :: SscPayload
dropSscPayload :: Dropper s
data SscProof
SscProof :: SscProof
dropSscProof :: Dropper s
dropCommitmentsMap :: Dropper s
dropSignedCommitment :: Dropper s
dropCommitment :: Dropper s
dropOpeningsMap :: Dropper s
dropSharesMap :: Dropper s
dropInnerSharesMap :: Dropper s
dropVssCertificatesMap :: Dropper s
dropVssCertificate :: Dropper s
instance Control.DeepSeq.NFData Cardano.Chain.Ssc.SscPayload
instance GHC.Generics.Generic Cardano.Chain.Ssc.SscPayload
instance GHC.Show.Show Cardano.Chain.Ssc.SscPayload
instance GHC.Classes.Eq Cardano.Chain.Ssc.SscPayload
instance NoThunks.Class.NoThunks Cardano.Chain.Ssc.SscProof
instance Control.DeepSeq.NFData Cardano.Chain.Ssc.SscProof
instance GHC.Generics.Generic Cardano.Chain.Ssc.SscProof
instance GHC.Show.Show Cardano.Chain.Ssc.SscProof
instance GHC.Classes.Eq Cardano.Chain.Ssc.SscProof
instance Data.Aeson.Types.ToJSON.ToJSON Cardano.Chain.Ssc.SscProof
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Ssc.SscProof
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Ssc.SscProof
instance Data.Aeson.Types.ToJSON.ToJSON Cardano.Chain.Ssc.SscPayload
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Ssc.SscPayload
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Ssc.SscPayload

module Cardano.Chain.UTxO.UTxO
newtype UTxO
UTxO :: Map CompactTxIn CompactTxOut -> UTxO
[unUTxO] :: UTxO -> Map CompactTxIn CompactTxOut
data UTxOError
UTxOMissingInput :: TxIn -> UTxOError
UTxOOverlappingUnion :: UTxOError
empty :: UTxO
fromList :: [(TxIn, TxOut)] -> UTxO

-- | Create a <a>UTxO</a> from a list of initial balances
fromBalances :: [(Address, Lovelace)] -> UTxO

-- | Construct a UTxO from a TxOut. This UTxO is a singleton with a TxIn
--   that references an address constructed by hashing the TxOut address.
--   This means it is not guaranteed (or likely) to be a real address.
fromTxOut :: TxOut -> UTxO
toList :: UTxO -> [(TxIn, TxOut)]
member :: TxIn -> UTxO -> Bool
lookup :: TxIn -> UTxO -> Maybe TxOut
lookupCompact :: CompactTxIn -> UTxO -> Maybe CompactTxOut
lookupAddress :: TxIn -> UTxO -> Either UTxOError Address
union :: MonadError UTxOError m => UTxO -> UTxO -> m UTxO
concat :: MonadError UTxOError m => [UTxO] -> m UTxO
balance :: UTxO -> Either LovelaceError Lovelace
(<|) :: Set TxIn -> UTxO -> UTxO
(</|) :: Set TxIn -> UTxO -> UTxO
txOutputUTxO :: Tx -> UTxO
isRedeemUTxO :: UTxO -> Bool
instance NoThunks.Class.NoThunks Cardano.Chain.UTxO.UTxO.UTxO
instance Control.DeepSeq.NFData Cardano.Chain.UTxO.UTxO.UTxO
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.UTxO.UTxO.UTxO
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.UTxO.UTxO.UTxO
instance Cardano.Prelude.HeapWords.HeapWords Cardano.Chain.UTxO.UTxO.UTxO
instance GHC.Generics.Generic Cardano.Chain.UTxO.UTxO.UTxO
instance GHC.Show.Show Cardano.Chain.UTxO.UTxO.UTxO
instance GHC.Classes.Eq Cardano.Chain.UTxO.UTxO.UTxO
instance GHC.Show.Show Cardano.Chain.UTxO.UTxO.UTxOError
instance GHC.Classes.Eq Cardano.Chain.UTxO.UTxO.UTxOError
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.UTxO.UTxO.UTxOError
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.UTxO.UTxO.UTxOError

module Cardano.Chain.Update.Proposal

-- | Proposal for software update
data AProposal a
AProposal :: !Annotated ProposalBody a -> !VerificationKey -> !Signature ProposalBody -> !a -> AProposal a
[$sel:aBody:AProposal] :: AProposal a -> !Annotated ProposalBody a

-- | Who proposed this UP.
[$sel:issuer:AProposal] :: AProposal a -> !VerificationKey
[$sel:signature:AProposal] :: AProposal a -> !Signature ProposalBody
[$sel:annotation:AProposal] :: AProposal a -> !a
type Proposal = AProposal ()

-- | ID of software update proposal
type UpId = Hash Proposal

-- | Create an update <a>Proposal</a> using the provided signature.
unsafeProposal :: ProposalBody -> VerificationKey -> Signature ProposalBody -> Proposal

-- | Create an update <a>Proposal</a>, signing it with the provided safe
--   signer.
signProposal :: ProtocolMagicId -> ProposalBody -> SafeSigner -> Proposal
signatureForProposal :: ProtocolMagicId -> ProposalBody -> SafeSigner -> Signature ProposalBody
body :: AProposal a -> ProposalBody
recoverUpId :: AProposal ByteString -> UpId
formatMaybeProposal :: Maybe Proposal -> Builder
data ProposalBody
ProposalBody :: !ProtocolVersion -> !ProtocolParametersUpdate -> !SoftwareVersion -> !Map SystemTag InstallerHash -> ProposalBody
[$sel:protocolVersion:ProposalBody] :: ProposalBody -> !ProtocolVersion
[$sel:protocolParametersUpdate:ProposalBody] :: ProposalBody -> !ProtocolParametersUpdate
[$sel:softwareVersion:ProposalBody] :: ProposalBody -> !SoftwareVersion

-- | InstallerHash for each system which this update affects
[$sel:metadata:ProposalBody] :: ProposalBody -> !Map SystemTag InstallerHash

-- | Prepend byte corresponding to `encodeListLen 5`, which was used during
--   signing
recoverProposalSignedBytes :: Annotated ProposalBody ByteString -> Annotated ProposalBody ByteString
instance Control.DeepSeq.NFData Cardano.Chain.Update.Proposal.ProposalBody
instance GHC.Generics.Generic Cardano.Chain.Update.Proposal.ProposalBody
instance GHC.Show.Show Cardano.Chain.Update.Proposal.ProposalBody
instance GHC.Classes.Eq Cardano.Chain.Update.Proposal.ProposalBody
instance Control.DeepSeq.NFData a => Control.DeepSeq.NFData (Cardano.Chain.Update.Proposal.AProposal a)
instance GHC.Base.Functor Cardano.Chain.Update.Proposal.AProposal
instance GHC.Generics.Generic (Cardano.Chain.Update.Proposal.AProposal a)
instance GHC.Show.Show a => GHC.Show.Show (Cardano.Chain.Update.Proposal.AProposal a)
instance GHC.Classes.Eq a => GHC.Classes.Eq (Cardano.Chain.Update.Proposal.AProposal a)
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Update.Proposal.Proposal
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Update.Proposal.Proposal
instance Cardano.Binary.Annotated.Decoded (Cardano.Chain.Update.Proposal.AProposal Data.ByteString.Internal.ByteString)
instance Data.Aeson.Types.ToJSON.ToJSON a => Data.Aeson.Types.ToJSON.ToJSON (Cardano.Chain.Update.Proposal.AProposal a)
instance Cardano.Binary.FromCBOR.FromCBOR (Cardano.Chain.Update.Proposal.AProposal Cardano.Binary.Annotated.ByteSpan)
instance Formatting.Buildable.Buildable (Cardano.Chain.Update.Proposal.AProposal ())
instance Data.Aeson.Types.ToJSON.ToJSON Cardano.Chain.Update.Proposal.ProposalBody
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Update.Proposal.ProposalBody
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Update.Proposal.ProposalBody


-- | Validation rules for registering updates
--   
--   This is an implementation of the rules defined in the Byron ledger
--   specification
module Cardano.Chain.Update.Validation.Registration

-- | Error captures the ways in which registration could fail
data Error
DuplicateProtocolVersion :: ProtocolVersion -> Error
DuplicateSoftwareVersion :: SoftwareVersion -> Error
InvalidProposer :: KeyHash -> Error
InvalidProtocolVersion :: ProtocolVersion -> Adopted -> Error
InvalidScriptVersion :: Word16 -> Word16 -> Error
InvalidSignature :: Error
InvalidSoftwareVersion :: ApplicationVersions -> SoftwareVersion -> Error
MaxBlockSizeTooLarge :: TooLarge Natural -> Error
MaxTxSizeTooLarge :: TooLarge Natural -> Error
ProposalAttributesUnknown :: Error
ProposalTooLarge :: TooLarge Natural -> Error
SoftwareVersionError :: SoftwareVersionError -> Error
SystemTagError :: SystemTagError -> Error

-- | The update proposal proposes neither a bump in the protocol or
--   application versions.
NullUpdateProposal :: Error
data Environment
Environment :: !Annotated ProtocolMagicId ByteString -> !SlotNumber -> !ProtocolVersion -> !ProtocolParameters -> !ApplicationVersions -> !Map -> Environment
[protocolMagic] :: Environment -> !Annotated ProtocolMagicId ByteString
[currentSlot] :: Environment -> !SlotNumber
[adoptedProtocolVersion] :: Environment -> !ProtocolVersion
[adoptedProtocolParameters] :: Environment -> !ProtocolParameters
[appVersions] :: Environment -> !ApplicationVersions
[delegationMap] :: Environment -> !Map

-- | State keeps track of registered protocol and software update proposals
data State
State :: !ProtocolUpdateProposals -> !SoftwareUpdateProposals -> State
[rsProtocolUpdateProposals] :: State -> !ProtocolUpdateProposals
[rsSoftwareUpdateProposals] :: State -> !SoftwareUpdateProposals
data ApplicationVersion
ApplicationVersion :: !NumSoftwareVersion -> !SlotNumber -> !Metadata -> ApplicationVersion
[avNumSoftwareVersion] :: ApplicationVersion -> !NumSoftwareVersion
[avSlotNumber] :: ApplicationVersion -> !SlotNumber
[avMetadata] :: ApplicationVersion -> !Metadata
type ApplicationVersions = Map ApplicationName ApplicationVersion
type Metadata = Map SystemTag InstallerHash
data ProtocolUpdateProposal
ProtocolUpdateProposal :: !ProtocolVersion -> !ProtocolParameters -> ProtocolUpdateProposal
[pupProtocolVersion] :: ProtocolUpdateProposal -> !ProtocolVersion
[pupProtocolParameters] :: ProtocolUpdateProposal -> !ProtocolParameters
type ProtocolUpdateProposals = Map UpId ProtocolUpdateProposal
data SoftwareUpdateProposal
SoftwareUpdateProposal :: !SoftwareVersion -> !Metadata -> SoftwareUpdateProposal
[supSoftwareVersion] :: SoftwareUpdateProposal -> !SoftwareVersion
[supSoftwareMetadata] :: SoftwareUpdateProposal -> !Metadata
type SoftwareUpdateProposals = Map UpId SoftwareUpdateProposal

-- | Register an update proposal after verifying its signature and
--   validating its contents. This corresponds to the <tt>UPREG</tt> rules
--   in the spec.
registerProposal :: MonadError Error m => Environment -> State -> AProposal ByteString -> m State
data TooLarge n
TooLarge :: n -> n -> TooLarge n
[tlActual] :: TooLarge n -> n
[tlMaxBound] :: TooLarge n -> n
newtype Adopted
Adopted :: ProtocolVersion -> Adopted
instance NoThunks.Class.NoThunks Cardano.Chain.Update.Validation.Registration.ApplicationVersion
instance Control.DeepSeq.NFData Cardano.Chain.Update.Validation.Registration.ApplicationVersion
instance GHC.Generics.Generic Cardano.Chain.Update.Validation.Registration.ApplicationVersion
instance GHC.Show.Show Cardano.Chain.Update.Validation.Registration.ApplicationVersion
instance GHC.Classes.Eq Cardano.Chain.Update.Validation.Registration.ApplicationVersion
instance NoThunks.Class.NoThunks Cardano.Chain.Update.Validation.Registration.ProtocolUpdateProposal
instance Control.DeepSeq.NFData Cardano.Chain.Update.Validation.Registration.ProtocolUpdateProposal
instance GHC.Generics.Generic Cardano.Chain.Update.Validation.Registration.ProtocolUpdateProposal
instance GHC.Show.Show Cardano.Chain.Update.Validation.Registration.ProtocolUpdateProposal
instance GHC.Classes.Eq Cardano.Chain.Update.Validation.Registration.ProtocolUpdateProposal
instance NoThunks.Class.NoThunks Cardano.Chain.Update.Validation.Registration.SoftwareUpdateProposal
instance Control.DeepSeq.NFData Cardano.Chain.Update.Validation.Registration.SoftwareUpdateProposal
instance GHC.Generics.Generic Cardano.Chain.Update.Validation.Registration.SoftwareUpdateProposal
instance GHC.Show.Show Cardano.Chain.Update.Validation.Registration.SoftwareUpdateProposal
instance GHC.Classes.Eq Cardano.Chain.Update.Validation.Registration.SoftwareUpdateProposal
instance GHC.Show.Show n => GHC.Show.Show (Cardano.Chain.Update.Validation.Registration.TooLarge n)
instance GHC.Classes.Eq n => GHC.Classes.Eq (Cardano.Chain.Update.Validation.Registration.TooLarge n)
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Update.Validation.Registration.Adopted
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Update.Validation.Registration.Adopted
instance GHC.Show.Show Cardano.Chain.Update.Validation.Registration.Adopted
instance GHC.Classes.Eq Cardano.Chain.Update.Validation.Registration.Adopted
instance GHC.Show.Show Cardano.Chain.Update.Validation.Registration.Error
instance GHC.Classes.Eq Cardano.Chain.Update.Validation.Registration.Error
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Update.Validation.Registration.Error
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Update.Validation.Registration.Error
instance Cardano.Binary.ToCBOR.ToCBOR n => Cardano.Binary.ToCBOR.ToCBOR (Cardano.Chain.Update.Validation.Registration.TooLarge n)
instance Cardano.Binary.FromCBOR.FromCBOR n => Cardano.Binary.FromCBOR.FromCBOR (Cardano.Chain.Update.Validation.Registration.TooLarge n)
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Update.Validation.Registration.SoftwareUpdateProposal
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Update.Validation.Registration.SoftwareUpdateProposal
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Update.Validation.Registration.ProtocolUpdateProposal
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Update.Validation.Registration.ProtocolUpdateProposal
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Update.Validation.Registration.ApplicationVersion
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Update.Validation.Registration.ApplicationVersion

module Cardano.Chain.Update.Validation.Endorsement
data Environment
Environment :: !BlockCount -> !SlotNumber -> !Int -> !Map -> !Map UpId SlotNumber -> !ProtocolUpdateProposals -> Environment

-- | Chain stability parameter.
[k] :: Environment -> !BlockCount
[currentSlot] :: Environment -> !SlotNumber
[adoptionThreshold] :: Environment -> !Int
[delegationMap] :: Environment -> !Map
[confirmedProposals] :: Environment -> !Map UpId SlotNumber
[registeredProtocolUpdateProposals] :: Environment -> !ProtocolUpdateProposals
data State
State :: ![CandidateProtocolUpdate] -> !Set Endorsement -> State
[candidateProtocolVersions] :: State -> ![CandidateProtocolUpdate]
[registeredEndorsements] :: State -> !Set Endorsement
data Endorsement
Endorsement :: !ProtocolVersion -> !KeyHash -> Endorsement
[endorsementProtocolVersion] :: Endorsement -> !ProtocolVersion
[endorsementKeyHash] :: Endorsement -> !KeyHash
data CandidateProtocolUpdate
CandidateProtocolUpdate :: !SlotNumber -> !ProtocolVersion -> !ProtocolParameters -> CandidateProtocolUpdate

-- | Slot at which this protocol version and parameters gathered enough
--   endorsements and became a candidate. This is used to check which
--   versions became candidates 2k slots before the end of an epoch (and
--   only those can be adopted at that epoch). Versions that became
--   candidates later than 2k slots before the end of an epoch can be
--   adopted in following epochs.
[cpuSlot] :: CandidateProtocolUpdate -> !SlotNumber
[cpuProtocolVersion] :: CandidateProtocolUpdate -> !ProtocolVersion
[cpuProtocolParameters] :: CandidateProtocolUpdate -> !ProtocolParameters

-- | Register an endorsement.
--   
--   This corresponds to the <tt>UPEND</tt> rule.
register :: MonadError Error m => Environment -> State -> Endorsement -> m State
data Error

-- | Multiple proposals were found, which propose an update to the same
--   protocol version.
MultipleProposalsForProtocolVersion :: ProtocolVersion -> Error
instance NoThunks.Class.NoThunks Cardano.Chain.Update.Validation.Endorsement.CandidateProtocolUpdate
instance Control.DeepSeq.NFData Cardano.Chain.Update.Validation.Endorsement.CandidateProtocolUpdate
instance GHC.Generics.Generic Cardano.Chain.Update.Validation.Endorsement.CandidateProtocolUpdate
instance GHC.Show.Show Cardano.Chain.Update.Validation.Endorsement.CandidateProtocolUpdate
instance GHC.Classes.Eq Cardano.Chain.Update.Validation.Endorsement.CandidateProtocolUpdate
instance NoThunks.Class.NoThunks Cardano.Chain.Update.Validation.Endorsement.Endorsement
instance Control.DeepSeq.NFData Cardano.Chain.Update.Validation.Endorsement.Endorsement
instance GHC.Generics.Generic Cardano.Chain.Update.Validation.Endorsement.Endorsement
instance GHC.Classes.Ord Cardano.Chain.Update.Validation.Endorsement.Endorsement
instance GHC.Show.Show Cardano.Chain.Update.Validation.Endorsement.Endorsement
instance GHC.Classes.Eq Cardano.Chain.Update.Validation.Endorsement.Endorsement
instance GHC.Show.Show Cardano.Chain.Update.Validation.Endorsement.Error
instance GHC.Classes.Eq Cardano.Chain.Update.Validation.Endorsement.Error
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Update.Validation.Endorsement.Error
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Update.Validation.Endorsement.Error
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Update.Validation.Endorsement.Endorsement
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Update.Validation.Endorsement.Endorsement
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Update.Validation.Endorsement.CandidateProtocolUpdate
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Update.Validation.Endorsement.CandidateProtocolUpdate

module Cardano.Chain.Update.Vote

-- | Vote for update proposal
--   
--   Invariant: The signature is valid.
data AVote a
UnsafeVote :: !VerificationKey -> !Annotated UpId a -> !Signature (UpId, Bool) -> !a -> AVote a

-- | Verification key casting the vote
[voterVK] :: AVote a -> !VerificationKey

-- | Proposal to which this vote applies
[aProposalId] :: AVote a -> !Annotated UpId a

-- | Signature of (Update proposal, Approval/rejection bit)
[signature] :: AVote a -> !Signature (UpId, Bool)
[annotation] :: AVote a -> !a
type Vote = AVote ()

-- | An update proposal vote identifier (the <a>Hash</a> of a <a>Vote</a>).
type VoteId = Hash Vote

-- | A safe constructor for <a>UnsafeVote</a>
mkVote :: ProtocolMagicId -> SigningKey -> UpId -> Bool -> Vote

-- | Create a vote for the given update proposal id, signing it with the
--   provided safe signer.
signVote :: ProtocolMagicId -> UpId -> Bool -> SafeSigner -> Vote
signatureForVote :: ProtocolMagicId -> UpId -> Bool -> SafeSigner -> Signature (UpId, Bool)

-- | Create a vote for the given update proposal id using the provided
--   signature.
--   
--   For the meaning of the parameters see <a>signVote</a>.
unsafeVote :: VerificationKey -> UpId -> Signature (UpId, Bool) -> Vote
proposalId :: AVote a -> UpId
recoverVoteId :: AVote ByteString -> VoteId
recoverSignedBytes :: AVote ByteString -> Annotated (UpId, Bool) ByteString

-- | Format <a>Vote</a> compactly
formatVoteShort :: Vote -> Builder

-- | Formatter for <a>Vote</a> which displays it compactly
shortVoteF :: Format r (Vote -> r)
instance Control.DeepSeq.NFData a => Control.DeepSeq.NFData (Cardano.Chain.Update.Vote.AVote a)
instance GHC.Base.Functor Cardano.Chain.Update.Vote.AVote
instance GHC.Generics.Generic (Cardano.Chain.Update.Vote.AVote a)
instance GHC.Show.Show a => GHC.Show.Show (Cardano.Chain.Update.Vote.AVote a)
instance GHC.Classes.Eq a => GHC.Classes.Eq (Cardano.Chain.Update.Vote.AVote a)
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Update.Vote.Vote
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Update.Vote.Vote
instance Cardano.Binary.Annotated.Decoded (Cardano.Chain.Update.Vote.AVote Data.ByteString.Internal.ByteString)
instance Formatting.Buildable.Buildable (Cardano.Chain.Update.Proposal.Proposal, [Cardano.Chain.Update.Vote.Vote])
instance Data.Aeson.Types.ToJSON.ToJSON a => Data.Aeson.Types.ToJSON.ToJSON (Cardano.Chain.Update.Vote.AVote a)
instance Cardano.Binary.FromCBOR.FromCBOR (Cardano.Chain.Update.Vote.AVote Cardano.Binary.Annotated.ByteSpan)
instance Formatting.Buildable.Buildable (Cardano.Chain.Update.Vote.AVote a)


-- | Validation rules for registering votes and confirming proposals
--   
--   This is an implementation of the rules defined in the Byron ledger
--   specification
module Cardano.Chain.Update.Validation.Voting

-- | Environment used to register votes and confirm proposals
data Environment
Environment :: SlotNumber -> Int -> RegistrationEnvironment -> Environment
[veCurrentSlot] :: Environment -> SlotNumber
[veConfirmationThreshold] :: Environment -> Int
[veVotingRegistrationEnvironment] :: Environment -> RegistrationEnvironment

-- | Environment required to validate and register a vote
data RegistrationEnvironment
RegistrationEnvironment :: !Set UpId -> !Map -> RegistrationEnvironment
[vreRegisteredUpdateProposal] :: RegistrationEnvironment -> !Set UpId
[vreDelegationMap] :: RegistrationEnvironment -> !Map

-- | State keeps track of registered votes and confirmed proposals
data State
State :: !RegisteredVotes -> !Map UpId SlotNumber -> State
[vsVotes] :: State -> !RegisteredVotes
[vsConfirmedProposals] :: State -> !Map UpId SlotNumber

-- | Error captures the ways in which vote registration could fail
data Error
VotingInvalidSignature :: Error
VotingProposalNotRegistered :: UpId -> Error
VotingVoterNotDelegate :: KeyHash -> Error
VotingVoteAlreadyCast :: KeyHash -> Error

-- | Register a vote and confirm the corresponding proposal if it passes
--   the voting threshold. This corresponds to the <tt>UPVOTE</tt> rules in
--   the spec.
registerVoteWithConfirmation :: MonadError Error m => Annotated ProtocolMagicId ByteString -> Environment -> State -> AVote ByteString -> m State
instance Control.DeepSeq.NFData Cardano.Chain.Update.Validation.Voting.RegistrationEnvironment
instance GHC.Generics.Generic Cardano.Chain.Update.Validation.Voting.RegistrationEnvironment
instance GHC.Show.Show Cardano.Chain.Update.Validation.Voting.RegistrationEnvironment
instance GHC.Classes.Eq Cardano.Chain.Update.Validation.Voting.RegistrationEnvironment
instance Control.DeepSeq.NFData Cardano.Chain.Update.Validation.Voting.Environment
instance GHC.Generics.Generic Cardano.Chain.Update.Validation.Voting.Environment
instance GHC.Show.Show Cardano.Chain.Update.Validation.Voting.Environment
instance GHC.Classes.Eq Cardano.Chain.Update.Validation.Voting.Environment
instance GHC.Show.Show Cardano.Chain.Update.Validation.Voting.Error
instance GHC.Classes.Eq Cardano.Chain.Update.Validation.Voting.Error
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Update.Validation.Voting.Error
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Update.Validation.Voting.Error

module Cardano.Chain.Epoch.File

-- | Slots per epoch used in mainnet
--   
--   This number has been fixed throughout the Byron era.
mainnetEpochSlots :: EpochSlots
parseEpochFileWithBoundary :: EpochSlots -> FilePath -> Stream (Of (ABlockOrBoundary ByteString)) (ExceptT ParseError ResIO) ()
parseEpochFilesWithBoundary :: EpochSlots -> [FilePath] -> Stream (Of (ABlockOrBoundary ByteString)) (ExceptT ParseError ResIO) ()
data ParseError

-- | The CBOR is invalid
ParseErrorDecoder :: !DecoderError -> ParseError
ParseErrorBinary :: !FilePath -> !ByteOffset -> !Text -> ParseError
ParseErrorMissingHeader :: !FilePath -> ParseError
instance GHC.Show.Show Cardano.Chain.Epoch.File.ParseError
instance GHC.Classes.Eq Cardano.Chain.Epoch.File.ParseError

module Cardano.Chain.Update

-- | Tag of system for which update data is purposed, e.g. win64, mac32
newtype SystemTag
SystemTag :: Text -> SystemTag
[getSystemTag] :: SystemTag -> Text
data SystemTagError
SystemTagNotAscii :: Text -> SystemTagError
SystemTagTooLong :: Text -> SystemTagError
checkSystemTag :: MonadError SystemTagError m => SystemTag -> m ()
systemTagMaxLength :: Integral i => i

-- | Helper to turn an <tt>OS</tt> into a <tt>Text</tt> compatible with the
--   <tt>systemTag</tt> previously used in 'configuration.yaml'
osHelper :: OS -> Text

-- | Helper to turn an <tt>Arch</tt> into a <tt>Text</tt> compatible with
--   the <tt>systemTag</tt> previously used in 'configuration.yaml'
archHelper :: Arch -> Text

-- | Software version
data SoftwareVersion
SoftwareVersion :: !ApplicationName -> !NumSoftwareVersion -> SoftwareVersion
[svAppName] :: SoftwareVersion -> !ApplicationName
[svNumber] :: SoftwareVersion -> !NumSoftwareVersion
data SoftwareVersionError
SoftwareVersionApplicationNameError :: ApplicationNameError -> SoftwareVersionError

-- | Numeric software version associated with <a>ApplicationName</a>
type NumSoftwareVersion = Word32

-- | A software version is valid iff its application name is valid
checkSoftwareVersion :: MonadError SoftwareVersionError m => SoftwareVersion -> m ()

-- | Values defining softfork resolution rule
--   
--   If a proposal is confirmed at the <tt>s</tt>-th epoch, softfork
--   resolution threshold at the <tt>t</tt>-th epoch will be 'max spMinThd
--   (spInitThd - (t - s) * spThdDecrement)'.
--   
--   Softfork resolution threshold is the portion of total stake such that
--   if total stake of issuers of blocks with some block version is greater
--   than this portion, this block version becomes adopted.
data SoftforkRule
SoftforkRule :: !LovelacePortion -> !LovelacePortion -> !LovelacePortion -> SoftforkRule

-- | Initial threshold (right after proposal is confirmed).
[srInitThd] :: SoftforkRule -> !LovelacePortion

-- | Minimal threshold (i. e. threshold can't become less than this one).
[srMinThd] :: SoftforkRule -> !LovelacePortion

-- | Theshold will be decreased by this value after each epoch.
[srThdDecrement] :: SoftforkRule -> !LovelacePortion

-- | Communication protocol version
data ProtocolVersion
ProtocolVersion :: !Word16 -> !Word16 -> !Word8 -> ProtocolVersion
[pvMajor] :: ProtocolVersion -> !Word16
[pvMinor] :: ProtocolVersion -> !Word16
[pvAlt] :: ProtocolVersion -> !Word8

-- | Data which represents modifications of block (aka protocol) version
data ProtocolParametersUpdate
ProtocolParametersUpdate :: !Maybe Word16 -> !Maybe Natural -> !Maybe Natural -> !Maybe Natural -> !Maybe Natural -> !Maybe Natural -> !Maybe LovelacePortion -> !Maybe LovelacePortion -> !Maybe LovelacePortion -> !Maybe LovelacePortion -> !Maybe SlotNumber -> !Maybe SoftforkRule -> !Maybe TxFeePolicy -> !Maybe EpochNumber -> ProtocolParametersUpdate
[ppuScriptVersion] :: ProtocolParametersUpdate -> !Maybe Word16
[ppuSlotDuration] :: ProtocolParametersUpdate -> !Maybe Natural
[ppuMaxBlockSize] :: ProtocolParametersUpdate -> !Maybe Natural
[ppuMaxHeaderSize] :: ProtocolParametersUpdate -> !Maybe Natural
[ppuMaxTxSize] :: ProtocolParametersUpdate -> !Maybe Natural
[ppuMaxProposalSize] :: ProtocolParametersUpdate -> !Maybe Natural
[ppuMpcThd] :: ProtocolParametersUpdate -> !Maybe LovelacePortion
[ppuHeavyDelThd] :: ProtocolParametersUpdate -> !Maybe LovelacePortion
[ppuUpdateVoteThd] :: ProtocolParametersUpdate -> !Maybe LovelacePortion
[ppuUpdateProposalThd] :: ProtocolParametersUpdate -> !Maybe LovelacePortion
[ppuUpdateProposalTTL] :: ProtocolParametersUpdate -> !Maybe SlotNumber
[ppuSoftforkRule] :: ProtocolParametersUpdate -> !Maybe SoftforkRule
[ppuTxFeePolicy] :: ProtocolParametersUpdate -> !Maybe TxFeePolicy
[ppuUnlockStakeEpoch] :: ProtocolParametersUpdate -> !Maybe EpochNumber
isEmpty :: ProtocolParametersUpdate -> Bool

-- | Apply <a>ProtocolParametersUpdate</a> to <a>ProtocolParameters</a>
apply :: ProtocolParametersUpdate -> ProtocolParameters -> ProtocolParameters

-- | Data which is associated with <tt>BlockVersion</tt>
data ProtocolParameters
ProtocolParameters :: !Word16 -> !Natural -> !Natural -> !Natural -> !Natural -> !Natural -> !LovelacePortion -> !LovelacePortion -> !LovelacePortion -> !LovelacePortion -> !SlotNumber -> !SoftforkRule -> !TxFeePolicy -> !EpochNumber -> ProtocolParameters
[ppScriptVersion] :: ProtocolParameters -> !Word16

-- | Milliseconds.
[ppSlotDuration] :: ProtocolParameters -> !Natural
[ppMaxBlockSize] :: ProtocolParameters -> !Natural
[ppMaxHeaderSize] :: ProtocolParameters -> !Natural
[ppMaxTxSize] :: ProtocolParameters -> !Natural
[ppMaxProposalSize] :: ProtocolParameters -> !Natural
[ppMpcThd] :: ProtocolParameters -> !LovelacePortion
[ppHeavyDelThd] :: ProtocolParameters -> !LovelacePortion
[ppUpdateVoteThd] :: ProtocolParameters -> !LovelacePortion
[ppUpdateProposalThd] :: ProtocolParameters -> !LovelacePortion

-- | Time to live for a protocol update proposal. This used to be the
--   number of slots after which the system made a decision regarding an
--   update proposal confirmation, when a majority of votes was not reached
--   in the given number of slots. If there were more positive than
--   negative votes the proposal became confirmed, otherwise it was
--   rejected. Since in the Byron-Shelley bridge we do not have negative
--   votes, and we aim at simplifying the update mechanism,
--   <a>ppUpdateProposalTTL</a> is re-interpreted as the number of slots a
--   proposal has to gather a majority of votes. If a majority of votes has
--   not been reached before this period, then the proposal is rejected.
--   
--   <ul>
--   <li>- TODO: it seems this should be a slot count.</li>
--   </ul>
[ppUpdateProposalTTL] :: ProtocolParameters -> !SlotNumber
[ppSoftforkRule] :: ProtocolParameters -> !SoftforkRule
[ppTxFeePolicy] :: ProtocolParameters -> !TxFeePolicy
[ppUnlockStakeEpoch] :: ProtocolParameters -> !EpochNumber

-- | In Byron we do not have a <tt>upAdptThd</tt> protocol parameter, so we
--   have to use the existing ones.
--   
--   <tt>lovelacePortionToRational . srMinThd . ppSoftforkRule</tt> will
--   give us the ratio (in the interval <tt>[0, 1]</tt>) of the total stake
--   that has to endorse a protocol version to become adopted. In genesis
--   configuration, this ratio will evaluate to <tt>0.6</tt>, so if we have
--   7 genesis keys, <tt>upAdptThd = 4</tt>.
upAdptThd :: Word8 -> ProtocolParameters -> Int

-- | Version of <a>isBootstrapEra</a> which takes <a>ProtocolParameters</a>
--   instead of unlock stake epoch
isBootstrapEraPP :: ProtocolParameters -> EpochNumber -> Bool

-- | Proof that body of update message contains <a>Payload</a>
type Proof = Hash Payload
mkProof :: Payload -> Proof
recoverProof :: APayload ByteString -> Proof

-- | Update System payload
data APayload a
APayload :: !Maybe (AProposal a) -> ![AVote a] -> a -> APayload a
[payloadProposal] :: APayload a -> !Maybe (AProposal a)
[payloadVotes] :: APayload a -> ![AVote a]
[payloadAnnotation] :: APayload a -> a
type Payload = APayload ()
payload :: Maybe Proposal -> [Vote] -> Payload

-- | The hash of the installer of the new application
newtype InstallerHash
InstallerHash :: Hash Raw -> InstallerHash
[unInstallerHash] :: InstallerHash -> Hash Raw
newtype ApplicationName
ApplicationName :: Text -> ApplicationName
[unApplicationName] :: ApplicationName -> Text
applicationNameMaxLength :: Integral i => i
data ApplicationNameError
ApplicationNameTooLong :: Text -> ApplicationNameError
ApplicationNameNotAscii :: Text -> ApplicationNameError

-- | Smart constructor of <a>ApplicationName</a>
checkApplicationName :: MonadError ApplicationNameError m => ApplicationName -> m ()

module Cardano.Chain.Genesis

-- | The set of genesis keys, who are able to produce blocks and submit
--   votes and proposals in the Byron era
newtype GenesisKeyHashes
GenesisKeyHashes :: Set KeyHash -> GenesisKeyHashes
[unGenesisKeyHashes] :: GenesisKeyHashes -> Set KeyHash

-- | Specification how to generate full <tt>GenesisData</tt>
data GenesisSpec
UnsafeGenesisSpec :: !GenesisAvvmBalances -> !GenesisDelegation -> !ProtocolParameters -> !BlockCount -> !ProtocolMagic -> !GenesisInitializer -> GenesisSpec

-- | Genesis data describes avvm utxo
[gsAvvmDistr] :: GenesisSpec -> !GenesisAvvmBalances

-- | Genesis state of heavyweight delegation. Will be concatenated with
--   delegation genesis keyHashes if <tt>tiUseHeavyDlg</tt> is <a>True</a>
[gsHeavyDelegation] :: GenesisSpec -> !GenesisDelegation

-- | Genesis <a>ProtocolParameters</a>
[gsProtocolParameters] :: GenesisSpec -> !ProtocolParameters

-- | The security parameter of the Ouroboros protocol
[gsK] :: GenesisSpec -> !BlockCount

-- | The magic number unique to any instance of Cardano
[gsProtocolMagic] :: GenesisSpec -> !ProtocolMagic

-- | Other data which depend on genesis type
[gsInitializer] :: GenesisSpec -> !GenesisInitializer

-- | Safe constructor for <a>GenesisSpec</a>. Throws error if something
--   goes wrong.
mkGenesisSpec :: GenesisAvvmBalances -> GenesisDelegation -> ProtocolParameters -> BlockCount -> ProtocolMagic -> GenesisInitializer -> Either Text GenesisSpec

-- | Predefined balances of non avvm entries.
newtype GenesisNonAvvmBalances
GenesisNonAvvmBalances :: Map Address Lovelace -> GenesisNonAvvmBalances
[unGenesisNonAvvmBalances] :: GenesisNonAvvmBalances -> Map Address Lovelace

-- | Generate genesis address distribution out of avvm parameters. Txdistr
--   of the utxo is all empty. Redelegate it in calling function.
convertNonAvvmDataToBalances :: forall m. MonadError NonAvvmBalancesError m => Map Text Integer -> m GenesisNonAvvmBalances

-- | Options determining generated genesis stakes, balances, and delegation
data GenesisInitializer
GenesisInitializer :: !TestnetBalanceOptions -> !FakeAvvmOptions -> !Rational -> !Bool -> GenesisInitializer
[giTestBalance] :: GenesisInitializer -> !TestnetBalanceOptions
[giFakeAvvmBalance] :: GenesisInitializer -> !FakeAvvmOptions

-- | Avvm balances will be multiplied by this factor
[giAvvmBalanceFactor] :: GenesisInitializer -> !Rational

-- | Whether to use heavyweight delegation for genesis keys
[giUseHeavyDlg] :: GenesisInitializer -> !Bool

-- | These options determine balances of nodes specific for testnet
data TestnetBalanceOptions
TestnetBalanceOptions :: !Word -> !Word -> !Lovelace -> !Rational -> TestnetBalanceOptions

-- | Number of poor nodes (with small balance).
[tboPoors] :: TestnetBalanceOptions -> !Word

-- | Number of rich nodes (with huge balance).
[tboRichmen] :: TestnetBalanceOptions -> !Word

-- | Total balance owned by these nodes.
[tboTotalBalance] :: TestnetBalanceOptions -> !Lovelace

-- | Portion of stake owned by all richmen together.
[tboRichmenShare] :: TestnetBalanceOptions -> !Rational

-- | These options determines balances of fake AVVM nodes which didn't
--   really go through vending, but pretend they did
data FakeAvvmOptions
FakeAvvmOptions :: !Word -> !Lovelace -> FakeAvvmOptions
[faoCount] :: FakeAvvmOptions -> !Word
[faoOneBalance] :: FakeAvvmOptions -> !Lovelace
newtype GenesisHash
GenesisHash :: Hash Raw -> GenesisHash
[unGenesisHash] :: GenesisHash -> Hash Raw

-- | Valuable secrets which can unlock genesis data.
data GeneratedSecrets
GeneratedSecrets :: ![SigningKey] -> ![SigningKey] -> ![PoorSecret] -> ![RedeemSigningKey] -> GeneratedSecrets

-- | Secret keys which issued heavyweight delegation certificates in
--   genesis data. If genesis heavyweight delegation isn't used, this list
--   is empty.
[gsDlgIssuersSecrets] :: GeneratedSecrets -> ![SigningKey]

-- | All secrets of rich nodes.
[gsRichSecrets] :: GeneratedSecrets -> ![SigningKey]

-- | Keys for HD addresses of poor nodes.
[gsPoorSecrets] :: GeneratedSecrets -> ![PoorSecret]

-- | Fake avvm secrets.
[gsFakeAvvmSecrets] :: GeneratedSecrets -> ![RedeemSigningKey]
gsSigningKeys :: GeneratedSecrets -> [SigningKey]
gsSigningKeysPoor :: GeneratedSecrets -> [SigningKey]

-- | Poor node secret
newtype PoorSecret
PoorSecret :: SigningKey -> PoorSecret
[poorSecretToKey] :: PoorSecret -> SigningKey

-- | Generate a genesis <a>GenesisData</a> and <a>GeneratedSecrets</a> from
--   a <a>GenesisSpec</a>. This is used only for tests blockhains. For a
--   real blockcain you must use the external key generation tool so that
--   each stakeholder can generate their keys privately.
generateGenesisData :: UTCTime -> GenesisSpec -> ExceptT GenesisDataGenerationError IO (GenesisData, GeneratedSecrets)

-- | A version of <a>generateGenesisData</a> parametrised over
--   <a>MonadRandom</a>. For testing purposes this allows using a
--   completely pure deterministic entropy source, rather than a
--   cryptographically secure entropy source.
generateGenesisDataWithEntropy :: MonadRandom m => UTCTime -> GenesisSpec -> ExceptT GenesisDataGenerationError m (GenesisData, GeneratedSecrets)

-- | Generate a genesis <a>Config</a> from a <a>GenesisSpec</a>. This is
--   used only for tests. For the real node we always generate an external
--   JSON genesis file.
generateGenesisConfig :: UTCTime -> GenesisSpec -> ExceptT GenesisDataGenerationError IO (Config, GeneratedSecrets)

-- | A version of <a>generateGenesisConfig</a> parametrised over
--   <a>MonadRandom</a>. For testing purposes this allows using a
--   completely pure deterministic entropy source, rather than a
--   cryptographically secure entropy source.
generateGenesisConfigWithEntropy :: MonadRandom m => UTCTime -> GenesisSpec -> ExceptT GenesisDataGenerationError m (Config, GeneratedSecrets)
data GenesisDataGenerationError
GenesisDataAddressBalanceMismatch :: Text -> Int -> Int -> GenesisDataGenerationError
GenesisDataGenerationDelegationError :: GenesisDelegationError -> GenesisDataGenerationError
GenesisDataGenerationDistributionMismatch :: Lovelace -> Lovelace -> GenesisDataGenerationError
GenesisDataGenerationLovelaceError :: LovelaceError -> GenesisDataGenerationError
GenesisDataGenerationPassPhraseMismatch :: GenesisDataGenerationError
GenesisDataGenerationRedeemKeyGen :: GenesisDataGenerationError

-- | This type contains genesis state of heavyweight delegation. It wraps a
--   map where keys are issuers and values are delegation certificates.
--   There are some invariants:
--   
--   <ol>
--   <li>In each pair delegate must differ from issuer, i. e. no
--   revocations.</li>
--   <li>PSKs must be consistent with keys in the map, i. e. issuer's ID
--   must be equal to the key in the map.</li>
--   <li>Delegates can't be issuers, i. e. transitive delegation is not
--   supported. It's not needed in genesis, it can always be reduced.</li>
--   </ol>
newtype GenesisDelegation
UnsafeGenesisDelegation :: Map KeyHash Certificate -> GenesisDelegation
[unGenesisDelegation] :: GenesisDelegation -> Map KeyHash Certificate
data GenesisDelegationError

-- | Safe constructor of <a>GenesisDelegation</a> from a list of
--   <a>Certificate</a>s
mkGenesisDelegation :: MonadError GenesisDelegationError m => [Certificate] -> m GenesisDelegation

-- | Genesis data contains all data which determines consensus rules. It
--   must be same for all nodes. It's used to initialize global state,
--   slotting, etc.
data GenesisData
GenesisData :: !GenesisKeyHashes -> !GenesisDelegation -> !UTCTime -> !GenesisNonAvvmBalances -> !ProtocolParameters -> !BlockCount -> !ProtocolMagicId -> !GenesisAvvmBalances -> GenesisData
[gdGenesisKeyHashes] :: GenesisData -> !GenesisKeyHashes
[gdHeavyDelegation] :: GenesisData -> !GenesisDelegation
[gdStartTime] :: GenesisData -> !UTCTime
[gdNonAvvmBalances] :: GenesisData -> !GenesisNonAvvmBalances
[gdProtocolParameters] :: GenesisData -> !ProtocolParameters
[gdK] :: GenesisData -> !BlockCount
[gdProtocolMagicId] :: GenesisData -> !ProtocolMagicId
[gdAvvmDistr] :: GenesisData -> !GenesisAvvmBalances
data GenesisDataError
GenesisDataParseError :: Text -> GenesisDataError
GenesisDataSchemaError :: SchemaError -> GenesisDataError
GenesisDataIOError :: IOException -> GenesisDataError
mainnetProtocolMagicId :: ProtocolMagicId

-- | Parse <tt>GenesisData</tt> from a JSON file and annotate with
--   Canonical JSON hash
readGenesisData :: (MonadError GenesisDataError m, MonadIO m) => FilePath -> m (GenesisData, GenesisHash)
data Config
Config :: !GenesisData -> !GenesisHash -> !RequiresNetworkMagic -> !UTxOConfiguration -> Config

-- | The data needed at genesis
[configGenesisData] :: Config -> !GenesisData

-- | The hash of the canonical JSON representation of the
--   <a>GenesisData</a>
[configGenesisHash] :: Config -> !GenesisHash

-- | Differentiates between Testnet and Mainet/Staging
[configReqNetMagic] :: Config -> !RequiresNetworkMagic

-- | Extra local data used in UTxO validation rules
[configUTxOConfiguration] :: Config -> !UTxOConfiguration
data ConfigurationError

-- | An error in constructing <a>GenesisData</a>
ConfigurationGenesisDataError :: GenesisDataError -> ConfigurationError

-- | The GenesisData canonical JSON hash is different than expected
GenesisHashMismatch :: GenesisHash -> Hash Raw -> ConfigurationError

-- | An error occured while decoding the genesis hash.
GenesisHashDecodeError :: Text -> ConfigurationError
configGenesisHeaderHash :: Config -> HeaderHash
configK :: Config -> BlockCount
configSlotSecurityParam :: Config -> SlotCount
configChainQualityThreshold :: Fractional f => Config -> f
configEpochSlots :: Config -> EpochSlots

-- | There isn't a full <tt>ProtocolMagic</tt> in <tt>Config</tt>, but the
--   requisite <tt>ProtocolMagicId</tt> and <tt>RequiresNetworkMagic</tt>
--   are stored separately. We use them to construct and return a
--   <tt>ProtocolMagic</tt>.
configProtocolMagic :: Config -> ProtocolMagic
configProtocolMagicId :: Config -> ProtocolMagicId
configGenesisKeyHashes :: Config -> GenesisKeyHashes
configHeavyDelegation :: Config -> GenesisDelegation
configStartTime :: Config -> UTCTime
configNonAvvmBalances :: Config -> GenesisNonAvvmBalances
configProtocolParameters :: Config -> ProtocolParameters
configAvvmDistr :: Config -> GenesisAvvmBalances

-- | Construct a <a>Config</a> from an external genesis file.
--   
--   The <a>FilePath</a> refers to a canonical JSON file. It will be hashed
--   and checked against the expected hash, which should be known from
--   config.
mkConfigFromFile :: (MonadError ConfigurationError m, MonadIO m) => RequiresNetworkMagic -> FilePath -> Hash Raw -> m Config

-- | Predefined balances of AVVM (Ada Voucher Vending Machine) entries.
--   People who purchased Ada at a pre-sale were issued a certificate
--   during the pre-sale period. These certificates allow customers to
--   redeem ADA.
newtype GenesisAvvmBalances
GenesisAvvmBalances :: Map CompactRedeemVerificationKey Lovelace -> GenesisAvvmBalances
[unGenesisAvvmBalances] :: GenesisAvvmBalances -> Map CompactRedeemVerificationKey Lovelace


-- | Blockchain interface validation rules.
module Cardano.Chain.Update.Validation.Interface
data Environment
Environment :: !Annotated ProtocolMagicId ByteString -> !BlockCount -> !SlotNumber -> !Word8 -> !Map -> Environment
[protocolMagic] :: Environment -> !Annotated ProtocolMagicId ByteString

-- | TODO: this is the chain security parameter, a.k.a.
--   <tt>stableAfter</tt>, it is not part of our protocol parameters, so it
--   seems that we need to pass it in the environment. However we need to
--   double-check this with others.
[k] :: Environment -> !BlockCount
[currentSlot] :: Environment -> !SlotNumber

-- | Number of genesis keys. This is used to calculate the proportion of
--   genesis keys that need to endorse a new protocol version for it to be
--   considered for adoption. See
--   <tt>Cardano.Chain.Update.Validation.Endorsement.Environment</tt>.
[numGenKeys] :: Environment -> !Word8
[delegationMap] :: Environment -> !Map

-- | Update interface state.
data State
State :: !EpochNumber -> !ProtocolVersion -> !ProtocolParameters -> ![CandidateProtocolUpdate] -> !ApplicationVersions -> !ProtocolUpdateProposals -> !SoftwareUpdateProposals -> !Map UpId SlotNumber -> !Map UpId (Set KeyHash) -> !Set Endorsement -> !Map UpId SlotNumber -> State

-- | Current epoch
[currentEpoch] :: State -> !EpochNumber
[adoptedProtocolVersion] :: State -> !ProtocolVersion

-- | Adopted protocol parameters
[adoptedProtocolParameters] :: State -> !ProtocolParameters

-- | Candidate protocol versions
[candidateProtocolUpdates] :: State -> ![CandidateProtocolUpdate]

-- | Current application versions
[appVersions] :: State -> !ApplicationVersions

-- | Registered protocol update proposals
[registeredProtocolUpdateProposals] :: State -> !ProtocolUpdateProposals

-- | Registered software update proposals
[registeredSoftwareUpdateProposals] :: State -> !SoftwareUpdateProposals

-- | Confirmed update proposals
[confirmedProposals] :: State -> !Map UpId SlotNumber

-- | Update proposals votes
[proposalVotes] :: State -> !Map UpId (Set KeyHash)

-- | Update proposals endorsements
[registeredEndorsements] :: State -> !Set Endorsement

-- | Slot at which an update proposal was registered
[proposalRegistrationSlot] :: State -> !Map UpId SlotNumber

-- | Initial update interface state
initialState :: Config -> State

-- | Signal combining signals from various rules
data Signal
Signal :: !Maybe (AProposal ByteString) -> ![AVote ByteString] -> !Endorsement -> Signal
[proposal] :: Signal -> !Maybe (AProposal ByteString)
[votes] :: Signal -> ![AVote ByteString]
[endorsement] :: Signal -> !Endorsement
data Error
Registration :: Error -> Error
Voting :: Error -> Error
Endorsement :: Error -> Error
NumberOfGenesisKeysTooLarge :: TooLarge Int -> Error

-- | Group together the other registration rules in a single rule
--   
--   This corresponds to the <tt>BUPI</tt> rule in the Byron chain
--   specification.
registerUpdate :: MonadError Error m => Environment -> State -> Signal -> m State

-- | Register an update proposal.
--   
--   This corresponds to the <tt>UPIREG</tt> rule in the Byron ledger
--   specification.
registerProposal :: MonadError Error m => Environment -> State -> AProposal ByteString -> m State

-- | Register a vote for the given proposal.
--   
--   This corresponds to the <tt>UPIVOTE</tt> rule in the Byron ledger
registerVote :: MonadError Error m => Environment -> State -> AVote ByteString -> m State

-- | Register an endorsement.
--   
--   An endorsement represents the fact that a genesis key is ready to
--   start using the protocol version being endorsed. In the decentralized
--   era only genesis key holders can endorse protocol versions.
--   
--   This corresponds to the <tt>UPIEND</tt> rule in the Byron ledger
--   specification.
registerEndorsement :: MonadError Error m => Environment -> State -> Endorsement -> m State

-- | Register an epoch. Whenever an epoch number is seen on a block this
--   epoch number should be passed to this function so that on epoch change
--   the protocol parameters can be updated, provided that there is an
--   update candidate that was accepted and endorsed by a majority of the
--   genesis keys.
--   
--   This corresponds to the <tt>UPIEC</tt> rules in the Byron ledger
--   specification.
registerEpoch :: Environment -> State -> EpochNumber -> State
instance NoThunks.Class.NoThunks Cardano.Chain.Update.Validation.Interface.State
instance Control.DeepSeq.NFData Cardano.Chain.Update.Validation.Interface.State
instance GHC.Generics.Generic Cardano.Chain.Update.Validation.Interface.State
instance GHC.Show.Show Cardano.Chain.Update.Validation.Interface.State
instance GHC.Classes.Eq Cardano.Chain.Update.Validation.Interface.State
instance GHC.Show.Show Cardano.Chain.Update.Validation.Interface.Error
instance GHC.Classes.Eq Cardano.Chain.Update.Validation.Interface.Error
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Update.Validation.Interface.Error
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Update.Validation.Interface.Error
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Update.Validation.Interface.State
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Update.Validation.Interface.State

module Cardano.Chain.Delegation.Validation.Interface
data Environment
Environment :: !Annotated ProtocolMagicId ByteString -> !Set KeyHash -> !BlockCount -> !EpochNumber -> !SlotNumber -> Environment
[protocolMagic] :: Environment -> !Annotated ProtocolMagicId ByteString
[allowedDelegators] :: Environment -> !Set KeyHash
[k] :: Environment -> !BlockCount
[currentEpoch] :: Environment -> !EpochNumber
[currentSlot] :: Environment -> !SlotNumber

-- | State shared between the blockchain and the ledger
data State
State :: !State -> !State -> State
[schedulingState] :: State -> !State
[activationState] :: State -> !State

-- | Activate certificates up to this slot
activateDelegations :: SlotNumber -> State -> State

-- | Check whether a delegation is valid in the <a>State</a>
delegates :: State -> VerificationKey -> VerificationKey -> Bool
delegationMap :: State -> Map

-- | The initial state maps each genesis key to itself and overrides this
--   using certificates from the genesis block.
initialState :: MonadError Error m => Environment -> GenesisDelegation -> m State

-- | Perform delegation update without adding certificates
tickDelegation :: EpochNumber -> SlotNumber -> State -> State

-- | Update the <a>State</a> with a list of new <a>Certificate</a>s
--   
--   This corresponds to the <tt>DELEG</tt> rule from the Byron ledger
--   specification
updateDelegation :: MonadError Error m => Environment -> State -> [ACertificate ByteString] -> m State
instance Control.DeepSeq.NFData Cardano.Chain.Delegation.Validation.Interface.Environment
instance GHC.Generics.Generic Cardano.Chain.Delegation.Validation.Interface.Environment
instance GHC.Show.Show Cardano.Chain.Delegation.Validation.Interface.Environment
instance GHC.Classes.Eq Cardano.Chain.Delegation.Validation.Interface.Environment
instance NoThunks.Class.NoThunks Cardano.Chain.Delegation.Validation.Interface.State
instance Control.DeepSeq.NFData Cardano.Chain.Delegation.Validation.Interface.State
instance GHC.Generics.Generic Cardano.Chain.Delegation.Validation.Interface.State
instance GHC.Show.Show Cardano.Chain.Delegation.Validation.Interface.State
instance GHC.Classes.Eq Cardano.Chain.Delegation.Validation.Interface.State
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.Delegation.Validation.Interface.State
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.Delegation.Validation.Interface.State

module Cardano.Chain.ValidationMode
data ValidationMode
ValidationMode :: !BlockValidationMode -> !TxValidationMode -> ValidationMode
[blockValidationMode] :: ValidationMode -> !BlockValidationMode
[txValidationMode] :: ValidationMode -> !TxValidationMode

-- | Helper function which accepts a <a>BlockValidationMode</a>, constructs
--   a sensible <a>TxValidationMode</a> based on that, and constructs a
--   <a>ValidationMode</a>
fromBlockValidationMode :: BlockValidationMode -> ValidationMode
orThrowErrorInBlockValidationMode :: (MonadError e m, MonadReader ValidationMode m) => Bool -> e -> m ()
infix 1 `orThrowErrorInBlockValidationMode`
askBlockValidationMode :: MonadReader ValidationMode m => m BlockValidationMode
askTxValidationMode :: MonadReader ValidationMode m => m TxValidationMode

-- | Perform an action only when in the <a>BlockValidation</a> mode.
--   Otherwise, do nothing.
whenBlockValidation :: (MonadError err m, MonadReader ValidationMode m) => m () -> m ()

-- | Perform an action only when in the <a>TxValidation</a> mode.
--   Otherwise, do nothing.
whenTxValidation :: (MonadError err m, MonadReader ValidationMode m) => m () -> m ()

-- | Perform an action unless in the <a>NoTxValidation</a> mode.
unlessNoTxValidation :: (MonadError err m, MonadReader ValidationMode m) => m () -> m ()
wrapErrorWithValidationMode :: (MonadError e' m, MonadReader ValidationMode m) => ReaderT ValidationMode (Either e) a -> (e -> e') -> m a
infix 1 `wrapErrorWithValidationMode`
instance GHC.Show.Show Cardano.Chain.ValidationMode.ValidationMode

module Cardano.Chain.UTxO.Validation

-- | Validate that:
--   
--   <ol>
--   <li>All <tt>TxIn</tt>s are in domain of <tt>Utxo</tt></li>
--   </ol>
--   
--   These are the conditions of the UTxO inference rule in the spec.
validateTx :: MonadError TxValidationError m => Environment -> UTxO -> Annotated Tx ByteString -> m ()

-- | Validate that:
--   
--   <ol>
--   <li>The fee for a transaction is not less than the minimum fee.</li>
--   <li>The size of the transaction is below the maximum size.</li>
--   <li>Output balance + fee = input balance</li>
--   </ol>
--   
--   The transaction size must be calculated _including the witnesses_. As
--   such this cannot be part of <a>validateTx</a>. We actually assume 3 by
--   calculating the fee as output balance - input balance.
validateTxAux :: MonadError TxValidationError m => Environment -> UTxO -> ATxAux ByteString -> m ()

-- | Update UTxO with a list of transactions
updateUTxO :: (MonadError UTxOValidationError m, MonadReader ValidationMode m) => Environment -> UTxO -> [ATxAux ByteString] -> m UTxO

-- | Validate a transaction with a witness and use it to update the
--   <a>UTxO</a>
updateUTxOTxWitness :: (MonadError UTxOValidationError m, MonadReader ValidationMode m) => Environment -> UTxO -> ATxAux ByteString -> m UTxO

-- | Validate a transaction and use it to update the <a>UTxO</a>
updateUTxOTx :: (MonadError UTxOValidationError m, MonadReader ValidationMode m) => Environment -> UTxO -> Annotated Tx ByteString -> m UTxO

-- | A representation of all the ways a transaction might be invalid
data TxValidationError
TxValidationLovelaceError :: Text -> LovelaceError -> TxValidationError
TxValidationFeeTooSmall :: Tx -> Lovelace -> Lovelace -> TxValidationError
TxValidationWitnessWrongSignature :: TxInWitness -> ProtocolMagicId -> TxSigData -> TxValidationError
TxValidationWitnessWrongKey :: TxInWitness -> Address -> TxValidationError
TxValidationMissingInput :: TxIn -> TxValidationError

-- | Fields are <a>expected</a> <a>actual</a>
TxValidationNetworkMagicMismatch :: NetworkMagic -> NetworkMagic -> TxValidationError
TxValidationTxTooLarge :: Natural -> Natural -> TxValidationError
TxValidationUnknownAddressAttributes :: TxValidationError
TxValidationUnknownAttributes :: TxValidationError
data Environment
Environment :: !AProtocolMagic ByteString -> !ProtocolParameters -> !UTxOConfiguration -> Environment
[protocolMagic] :: Environment -> !AProtocolMagic ByteString
[protocolParameters] :: Environment -> !ProtocolParameters
[utxoConfiguration] :: Environment -> !UTxOConfiguration
data UTxOValidationError
UTxOValidationTxValidationError :: TxValidationError -> UTxOValidationError
UTxOValidationUTxOError :: UTxOError -> UTxOValidationError
instance GHC.Show.Show Cardano.Chain.UTxO.Validation.TxValidationError
instance GHC.Classes.Eq Cardano.Chain.UTxO.Validation.TxValidationError
instance GHC.Show.Show Cardano.Chain.UTxO.Validation.Environment
instance GHC.Classes.Eq Cardano.Chain.UTxO.Validation.Environment
instance GHC.Show.Show Cardano.Chain.UTxO.Validation.UTxOValidationError
instance GHC.Classes.Eq Cardano.Chain.UTxO.Validation.UTxOValidationError
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.UTxO.Validation.UTxOValidationError
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.UTxO.Validation.UTxOValidationError
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.UTxO.Validation.TxValidationError
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.UTxO.Validation.TxValidationError

module Cardano.Chain.UTxO

-- | Indicates what sort of transaction validation should be performed.
data TxValidationMode

-- | Perform all transaction validations.
TxValidation :: TxValidationMode

-- | Because we've already validated this transaction against some ledger
--   state, we know that cryptographic validation has passed. However, we
--   should still perform all of the other non-cryptographic checks since
--   we're validating against a potentially dfferent ledger state.
TxValidationNoCrypto :: TxValidationMode

-- | No validations should be performed as we have already validated this
--   transaction against this very same ledger state.
NoTxValidation :: TxValidationMode

-- | A witness is a proof that a transaction is allowed to spend the funds
--   it spends (by providing signatures, redeeming scripts, etc). A
--   separate proof is provided for each input.
type TxWitness = Vector TxInWitness

-- | A witness for a single input
data TxInWitness

-- | VKWitness twKey twSig
VKWitness :: !VerificationKey -> !TxSig -> TxInWitness

-- | RedeemWitness twRedeemKey twRedeemSig
RedeemWitness :: !RedeemVerificationKey -> !RedeemSignature TxSigData -> TxInWitness

-- | Data that is being signed when creating a TxSig
newtype TxSigData
TxSigData :: Hash Tx -> TxSigData
[txSigTxHash] :: TxSigData -> Hash Tx

-- | <a>Signature</a> of addrId
type TxSig = Signature TxSigData
recoverSigData :: Annotated Tx ByteString -> Annotated TxSigData ByteString
data TxProof
TxProof :: !Word32 -> !MerkleRoot Tx -> !Hash [TxWitness] -> TxProof
[txpNumber] :: TxProof -> !Word32
[txpRoot] :: TxProof -> !MerkleRoot Tx
[txpWitnessesHash] :: TxProof -> !Hash [TxWitness]

-- | Construct <a>TxProof</a> which proves given <a>TxPayload</a>
--   
--   This will construct a Merkle tree, which can be very expensive. Use
--   with care.
mkTxProof :: TxPayload -> TxProof
recoverTxProof :: ATxPayload ByteString -> TxProof

-- | Additional configuration for ledger validation.
data UTxOConfiguration
UTxOConfiguration :: !Set CompactAddress -> UTxOConfiguration

-- | Set of source address which are asset-locked. Transactions which use
--   these addresses as transaction inputs will be deemed invalid.
[tcAssetLockedSrcAddrs] :: UTxOConfiguration -> !Set CompactAddress
defaultUTxOConfiguration :: UTxOConfiguration
mkUTxOConfiguration :: [Address] -> UTxOConfiguration

-- | Payload of UTxO component which is part of the block body
type TxPayload = ATxPayload ()
newtype ATxPayload a
ATxPayload :: [ATxAux a] -> ATxPayload a
[aUnTxPayload] :: ATxPayload a -> [ATxAux a]
mkTxPayload :: [TxAux] -> TxPayload
recoverHashedBytes :: ATxPayload ByteString -> Annotated [TxWitness] ByteString
txpAnnotatedTxs :: ATxPayload a -> [Annotated Tx a]
txpTxs :: ATxPayload a -> [Tx]
txpWitnesses :: TxPayload -> [TxWitness]
unTxPayload :: ATxPayload a -> [TxAux]

-- | Transaction + auxiliary data
type TxAux = ATxAux ()
data ATxAux a
ATxAux :: !Annotated Tx a -> !Annotated TxWitness a -> !a -> ATxAux a
[aTaTx] :: ATxAux a -> !Annotated Tx a
[aTaWitness] :: ATxAux a -> !Annotated TxWitness a
[aTaAnnotation] :: ATxAux a -> !a
mkTxAux :: Tx -> TxWitness -> TxAux
annotateTxAux :: TxAux -> ATxAux ByteString
taTx :: ATxAux a -> Tx
taWitness :: ATxAux a -> TxWitness

-- | Specialized formatter for <a>TxAux</a>
txaF :: Format r (TxAux -> r)

-- | Transaction
--   
--   NB: transaction witnesses are stored separately
data Tx
UnsafeTx :: !NonEmpty TxIn -> !NonEmpty TxOut -> !TxAttributes -> Tx

-- | Inputs of transaction.
[txInputs] :: Tx -> !NonEmpty TxIn

-- | Outputs of transaction.
[txOutputs] :: Tx -> !NonEmpty TxOut

-- | Attributes of transaction
[txAttributes] :: Tx -> !TxAttributes

-- | Specialized formatter for <a>Tx</a>
txF :: Format r (Tx -> r)

-- | Represents transaction identifier as <a>Hash</a> of <a>Tx</a>
type TxId = Hash Tx

-- | Represents transaction attributes: map from 1-byte integer to
--   arbitrary-type value. To be used for extending transaction with new
--   fields via softfork.
type TxAttributes = Attributes ()

-- | Transaction arbitrary input
data TxIn

-- | TxId = Which transaction's output is used | Word32 = Index of the
--   output in transaction's outputs
TxInUtxo :: TxId -> Word32 -> TxIn

-- | Transaction output
data TxOut
TxOut :: !Address -> !Lovelace -> TxOut
[txOutAddress] :: TxOut -> !Address
[txOutValue] :: TxOut -> !Lovelace

-- | Create initial <a>UTxO</a> from balances defined in the genesis config
genesisUtxo :: Config -> UTxO

-- | A compact in-memory representation for a <a>TxIn</a>.
--   
--   Convert using <a>toCompactTxIn</a> and <a>fromCompactTxIn</a>.
data CompactTxIn
CompactTxInUtxo :: {-# UNPACK #-} !CompactTxId -> {-# UNPACK #-} !Word32 -> CompactTxIn
toCompactTxIn :: TxIn -> CompactTxIn
fromCompactTxIn :: CompactTxIn -> TxIn

-- | A compact in-memory representation for a <a>TxId</a>.
--   
--   Convert using <a>toCompactTxId</a> and <a>fromCompactTxId</a>.
--   
--   Compared to a normal <a>TxId</a>, this takes 5 heap words rather than
--   12.
data CompactTxId
toCompactTxId :: TxId -> CompactTxId
fromCompactTxId :: CompactTxId -> TxId

-- | A compact in-memory representation for a <a>TxOut</a>.
--   
--   Convert using <a>toCompactTxOut</a> and <a>fromCompactTxOut</a>.
data CompactTxOut
CompactTxOut :: {-# UNPACK #-} !CompactAddress -> {-# UNPACK #-} !Lovelace -> CompactTxOut
toCompactTxOut :: TxOut -> CompactTxOut
fromCompactTxOut :: CompactTxOut -> TxOut

module Cardano.Chain.MempoolPayload

-- | A payload which can be submitted into or between mempools via the
--   transaction submission protocol.
type MempoolPayload = AMempoolPayload ()

-- | A payload which can be submitted into or between mempools via the
--   transaction submission protocol.
data AMempoolPayload a

-- | A transaction payload (transaction and witness).
MempoolTx :: !ATxAux a -> AMempoolPayload a

-- | A delegation certificate payload.
MempoolDlg :: !ACertificate a -> AMempoolPayload a

-- | An update proposal payload.
MempoolUpdateProposal :: !AProposal a -> AMempoolPayload a

-- | An update vote payload.
MempoolUpdateVote :: !AVote a -> AMempoolPayload a
instance GHC.Base.Functor Cardano.Chain.MempoolPayload.AMempoolPayload
instance GHC.Show.Show a => GHC.Show.Show (Cardano.Chain.MempoolPayload.AMempoolPayload a)
instance GHC.Classes.Eq a => GHC.Classes.Eq (Cardano.Chain.MempoolPayload.AMempoolPayload a)
instance Cardano.Binary.ToCBOR.ToCBOR Cardano.Chain.MempoolPayload.MempoolPayload
instance Cardano.Binary.FromCBOR.FromCBOR Cardano.Chain.MempoolPayload.MempoolPayload
instance Cardano.Binary.ToCBOR.ToCBOR (Cardano.Chain.MempoolPayload.AMempoolPayload Data.ByteString.Internal.ByteString)
instance Cardano.Binary.FromCBOR.FromCBOR (Cardano.Chain.MempoolPayload.AMempoolPayload Cardano.Binary.Annotated.ByteSpan)

module Cardano.Chain.Block

-- | Indicates what sort of block validation should be performed.
data BlockValidationMode

-- | Perform all block validations.
BlockValidation :: BlockValidationMode

-- | Perform no block validations.
NoBlockValidation :: BlockValidationMode

-- | Translate a <a>BlockValidationMode</a> to an appropriate
--   <a>TxValidationMode</a>.
toTxValidationMode :: BlockValidationMode -> TxValidationMode

-- | Adopted protocol parameters
adoptedProtocolParameters :: State -> ProtocolParameters

-- | This is an implementation of the BBODY rule as per the chain
--   specification.
--   
--   Compared to <tt>updateChain</tt>, this does not validate any header
--   level checks, nor does it carry out anything which might be considered
--   part of the protocol.
updateBody :: (MonadError ChainValidationError m, MonadReader ValidationMode m) => BodyEnvironment -> BodyState -> ABlock ByteString -> m BodyState
updateChainBlockOrBoundary :: (MonadError ChainValidationError m, MonadReader ValidationMode m) => Config -> ChainValidationState -> ABlockOrBoundary ByteString -> m ChainValidationState
updateChainBoundary :: MonadError ChainValidationError m => ChainValidationState -> ABoundaryBlock ByteString -> m ChainValidationState

-- | Perform epoch transition if we have moved across the epoch boundary
--   
--   We pass through to the update interface UPIEC rule, which adopts any
--   confirmed proposals and cleans up the state. This corresponds to the
--   EPOCH rules from the Byron chain specification.
epochTransition :: EpochEnvironment -> State -> SlotNumber -> State

-- | This is an implementation of the headerIsValid function from the Byron
--   chain specification
headerIsValid :: (MonadError ChainValidationError m, MonadReader ValidationMode m) => State -> AHeader ByteString -> m ()
validateHeaderMatchesBody :: MonadError ProofValidationError m => AHeader ByteString -> ABody ByteString -> m ()

-- | This represents the CHAIN rule. It is intended more for use in tests
--   than in a real implementation, which will want to invoke its
--   constituent rules directly.
--   
--   Note that this also updates the previous block hash, which would
--   usually be done as part of the PBFT rule.
updateBlock :: (MonadError ChainValidationError m, MonadReader ValidationMode m) => Config -> ChainValidationState -> ABlock ByteString -> m ChainValidationState
data BodyState
BodyState :: !UTxO -> !State -> !State -> BodyState
[$sel:utxo:BodyState] :: BodyState -> !UTxO
[$sel:updateState:BodyState] :: BodyState -> !State
[$sel:delegationState:BodyState] :: BodyState -> !State
data BodyEnvironment
BodyEnvironment :: !AProtocolMagic ByteString -> !UTxOConfiguration -> !BlockCount -> !Set KeyHash -> !ProtocolParameters -> !EpochNumber -> BodyEnvironment
[$sel:protocolMagic:BodyEnvironment] :: BodyEnvironment -> !AProtocolMagic ByteString
[$sel:utxoConfiguration:BodyEnvironment] :: BodyEnvironment -> !UTxOConfiguration
[$sel:k:BodyEnvironment] :: BodyEnvironment -> !BlockCount
[$sel:allowedDelegators:BodyEnvironment] :: BodyEnvironment -> !Set KeyHash
[$sel:protocolParameters:BodyEnvironment] :: BodyEnvironment -> !ProtocolParameters
[$sel:currentEpoch:BodyEnvironment] :: BodyEnvironment -> !EpochNumber
data EpochEnvironment
EpochEnvironment :: !Annotated ProtocolMagicId ByteString -> !BlockCount -> !Set KeyHash -> !Map -> !EpochNumber -> EpochEnvironment
[$sel:protocolMagic:EpochEnvironment] :: EpochEnvironment -> !Annotated ProtocolMagicId ByteString
[$sel:k:EpochEnvironment] :: EpochEnvironment -> !BlockCount
[$sel:allowedDelegators:EpochEnvironment] :: EpochEnvironment -> !Set KeyHash
[$sel:delegationMap:EpochEnvironment] :: EpochEnvironment -> !Map
[$sel:currentEpoch:EpochEnvironment] :: EpochEnvironment -> !EpochNumber
data ChainValidationState
ChainValidationState :: !SlotNumber -> !Either GenesisHash HeaderHash -> !UTxO -> !State -> !State -> ChainValidationState
[$sel:cvsLastSlot:ChainValidationState] :: ChainValidationState -> !SlotNumber

-- | GenesisHash for the previous hash of the zeroth boundary block and
--   HeaderHash for all others.
[$sel:cvsPreviousHash:ChainValidationState] :: ChainValidationState -> !Either GenesisHash HeaderHash
[$sel:cvsUtxo:ChainValidationState] :: ChainValidationState -> !UTxO
[$sel:cvsUpdateState:ChainValidationState] :: ChainValidationState -> !State
[$sel:cvsDelegationState:ChainValidationState] :: ChainValidationState -> !State

-- | Create the state needed to validate the zeroth epoch of the chain. The
--   zeroth epoch starts with a boundary block where the previous hash is
--   the genesis hash.
initialChainValidationState :: MonadError Error m => Config -> m ChainValidationState
data ChainValidationError

-- | The size of an epoch boundary block exceeds the limit
ChainValidationBoundaryTooLarge :: ChainValidationError

-- | The size of a block's attributes is non-zero
ChainValidationBlockAttributesTooLarge :: ChainValidationError

-- | The size of a regular block exceeds the limit
ChainValidationBlockTooLarge :: Natural -> Natural -> ChainValidationError

-- | The size of a block header's attributes is non-zero
ChainValidationHeaderAttributesTooLarge :: ChainValidationError

-- | The size of a block header exceeds the limit
ChainValidationHeaderTooLarge :: Natural -> Natural -> ChainValidationError

-- | There is a problem with the delegation payload signature
ChainValidationDelegationPayloadError :: Text -> ChainValidationError

-- | The delegation used in the signature is not valid according to the
--   ledger
ChainValidationInvalidDelegation :: VerificationKey -> VerificationKey -> ChainValidationError

-- | Genesis hash mismatch
ChainValidationGenesisHashMismatch :: GenesisHash -> GenesisHash -> ChainValidationError

-- | Expected GenesisHash but got HeaderHash
ChainValidationExpectedGenesisHash :: GenesisHash -> HeaderHash -> ChainValidationError

-- | Expected HeaderHash but GenesisHash
ChainValidationExpectedHeaderHash :: HeaderHash -> GenesisHash -> ChainValidationError

-- | The hash of the previous block does not match the value in the header
ChainValidationInvalidHash :: HeaderHash -> HeaderHash -> ChainValidationError

-- | The hash of the previous block is missing and should be given hash.
ChainValidationMissingHash :: HeaderHash -> ChainValidationError

-- | There should not be a hash of the previous but there is.
ChainValidationUnexpectedGenesisHash :: HeaderHash -> ChainValidationError

-- | The signature of the block is invalid
ChainValidationInvalidSignature :: BlockSignature -> ChainValidationError

-- | A delegation certificate failed validation in the ledger layer
ChainValidationDelegationSchedulingError :: Error -> ChainValidationError

-- | The <tt>ProtocolMagic</tt> in the block doesn't match the configured
--   one
ChainValidationProtocolMagicMismatch :: ProtocolMagicId -> ProtocolMagicId -> ChainValidationError

-- | A block is using unsupported lightweight delegation
ChainValidationSignatureLight :: ChainValidationError

-- | The delegator for this block has delegated in too many recent blocks
ChainValidationTooManyDelegations :: VerificationKey -> ChainValidationError

-- | Something failed to register in the update interface
ChainValidationUpdateError :: SlotNumber -> Error -> ChainValidationError

-- | A transaction failed validation in the ledger layer
ChainValidationUTxOValidationError :: UTxOValidationError -> ChainValidationError

-- | A payload proof did not match.
ChainValidationProofValidationError :: ProofValidationError -> ChainValidationError

-- | Size of a heap value, in words
newtype HeapSize a
HeapSize :: Int -> HeapSize a
[$sel:unHeapSize:HeapSize] :: HeapSize a -> Int

-- | Number of entries in the UTxO
newtype UTxOSize
UTxOSize :: Int -> UTxOSize
[$sel:unUTxOSize:UTxOSize] :: UTxOSize -> Int
calcUTxOSize :: UTxO -> (HeapSize UTxO, UTxOSize)

-- | Fold transaction validation over a <a>Stream</a> of <tt>Block</tt>s
foldUTxO :: Environment -> UTxO -> Stream (Of (ABlock ByteString)) (ExceptT ParseError ResIO) () -> ExceptT Error (ReaderT ValidationMode ResIO) UTxO

-- | Fold <tt>updateUTxO</tt> over the transactions in a single
--   <tt>Block</tt>
foldUTxOBlock :: Environment -> UTxO -> ABlock ByteString -> ExceptT Error (ReaderT ValidationMode ResIO) UTxO

-- | Proof of everything contained in the payload
data Proof
Proof :: !TxProof -> !SscProof -> !Hash Payload -> !Proof -> Proof
[proofUTxO] :: Proof -> !TxProof
[proofSsc] :: Proof -> !SscProof
[proofDelegation] :: Proof -> !Hash Payload
[proofUpdate] :: Proof -> !Proof

-- | Error which can result from attempting to validate an invalid payload
--   proof.
data ProofValidationError

-- | The delegation payload proof did not match
DelegationProofValidationError :: ProofValidationError

-- | The UTxO payload proof did not match
UTxOProofValidationError :: ProofValidationError

-- | The update payload proof did not match
UpdateProofValidationError :: ProofValidationError
mkProof :: Body -> Proof
recoverProof :: ABody ByteString -> Proof
type Header = AHeader ()
data AHeader a
AHeader :: !Annotated ProtocolMagicId a -> !Annotated HeaderHash a -> !Annotated SlotNumber a -> !Annotated ChainDifficulty a -> !ProtocolVersion -> !SoftwareVersion -> !Annotated Proof a -> !VerificationKey -> !ABlockSignature a -> !a -> !a -> AHeader a
[aHeaderProtocolMagicId] :: AHeader a -> !Annotated ProtocolMagicId a

-- | Pointer to the header of the previous block
[aHeaderPrevHash] :: AHeader a -> !Annotated HeaderHash a

-- | The slot number this block was published for
[aHeaderSlot] :: AHeader a -> !Annotated SlotNumber a

-- | The chain difficulty up to this block
[aHeaderDifficulty] :: AHeader a -> !Annotated ChainDifficulty a

-- | The version of the protocol parameters this block is using
[headerProtocolVersion] :: AHeader a -> !ProtocolVersion

-- | The software version this block was published from
[headerSoftwareVersion] :: AHeader a -> !SoftwareVersion

-- | Proof of body
[aHeaderProof] :: AHeader a -> !Annotated Proof a

-- | The genesis key that is delegating to publish this block
[headerGenesisKey] :: AHeader a -> !VerificationKey

-- | The signature of the block, which contains the delegation certificate
[headerSignature] :: AHeader a -> !ABlockSignature a

-- | An annotation that captures the full header bytes
[headerAnnotation] :: AHeader a -> !a

-- | An annotation that captures the bytes from the deprecated
--   ExtraHeaderData
[headerExtraAnnotation] :: AHeader a -> !a

-- | Smart constructor for <a>Header</a>
mkHeader :: ProtocolMagicId -> Either GenesisHash Header -> EpochSlots -> SlotNumber -> SigningKey -> Certificate -> Body -> ProtocolVersion -> SoftwareVersion -> Header

-- | Make a <a>Header</a> for a given slot, with a given body, parent hash,
--   and difficulty. This takes care of some signing and consensus data.
mkHeaderExplicit :: ProtocolMagicId -> HeaderHash -> ChainDifficulty -> EpochSlots -> SlotNumber -> SigningKey -> Certificate -> Body -> ProtocolVersion -> SoftwareVersion -> Header
headerProtocolMagicId :: AHeader a -> ProtocolMagicId
headerPrevHash :: AHeader a -> HeaderHash
headerProof :: AHeader a -> Proof
headerSlot :: AHeader a -> SlotNumber
headerIssuer :: AHeader a -> VerificationKey
headerLength :: AHeader ByteString -> Natural
headerDifficulty :: AHeader a -> ChainDifficulty
headerToSign :: EpochSlots -> AHeader a -> ToSign

-- | Encode a header, without taking in to account deprecated epoch
--   boundary blocks.
toCBORHeader :: EpochSlots -> Header -> Encoding
toCBORHeaderSize :: Proxy EpochSlots -> Proxy (AHeader a) -> Size

-- | Encode a <a>Header</a> accounting for deprecated epoch boundary blocks
--   
--   This encoding is only used when hashing the header for backwards
--   compatibility, but should not be used when serializing a header within
--   a block
toCBORHeaderToHash :: EpochSlots -> Header -> Encoding
fromCBORAHeader :: EpochSlots -> Decoder s (AHeader ByteSpan)
fromCBORHeader :: EpochSlots -> Decoder s Header
fromCBORHeaderToHash :: EpochSlots -> Decoder s (Maybe Header)

-- | These bytes must be prepended when hashing raw boundary header data
--   
--   In the Byron release, hashes were taken over a data type that was
--   never directly serialized to the blockchain, so these magic bytes
--   cannot be determined from the raw header data.
--   
--   These bytes are from `encodeListLen 2 &lt;&gt; toCBOR (1 :: Word8)`
wrapHeaderBytes :: ByteString -> ByteString
toCBORBlockVersions :: ProtocolVersion -> SoftwareVersion -> Encoding
toCBORBlockVersionsSize :: Proxy ProtocolVersion -> Proxy SoftwareVersion -> Size
renderHeader :: EpochSlots -> Header -> Builder
data ABoundaryHeader a
UnsafeABoundaryHeader :: !Either GenesisHash HeaderHash -> !Word64 -> !ChainDifficulty -> !a -> ABoundaryHeader a
[boundaryPrevHash] :: ABoundaryHeader a -> !Either GenesisHash HeaderHash
[boundaryEpoch] :: ABoundaryHeader a -> !Word64
[boundaryDifficulty] :: ABoundaryHeader a -> !ChainDifficulty
[boundaryHeaderAnnotation] :: ABoundaryHeader a -> !a

-- | Smart constructor for <a>ABoundaryHeader</a>
--   
--   Makes sure that the hash is forced.
mkABoundaryHeader :: Either GenesisHash HeaderHash -> Word64 -> ChainDifficulty -> a -> ABoundaryHeader a

-- | Encode from a boundary header with any annotation. This does not
--   necessarily invert <tt>fromCBORBoundaryHeader</tt>, because that
--   decoder drops information that this encoder replaces, such as the body
--   proof (assumes the body is empty) and the extra header data (sets it
--   to empty map).
toCBORABoundaryHeader :: ProtocolMagicId -> ABoundaryHeader a -> Encoding
toCBORABoundaryHeaderSize :: Proxy ProtocolMagicId -> Proxy (ABoundaryHeader a) -> Size
fromCBORABoundaryHeader :: Decoder s (ABoundaryHeader ByteSpan)

-- | Compute the hash of a boundary block header from its annotation. It
--   uses <a>wrapBoundaryBytes</a>, for the hash must be computed on the
--   header bytes tagged with the CBOR list length and tag discriminator,
--   which is the encoding chosen by cardano-sl.
boundaryHeaderHashAnnotated :: ABoundaryHeader ByteString -> HeaderHash

-- | These bytes must be prepended when hashing raw boundary header data
--   
--   In the Byron release, hashes were taken over a data type that was
--   never directly serialized to the blockchain, so these magic bytes
--   cannot be determined from the raw header data.
wrapBoundaryBytes :: ByteString -> ByteString

-- | <a>Hash</a> of block header
type HeaderHash = Hash Header

-- | Specialized formatter for <a>HeaderHash</a>
headerHashF :: Format r (HeaderHash -> r)

-- | Hash the serialised representation of a <a>Header</a>
--   
--   For backwards compatibility we have to take the hash of the header
--   serialised with <a>toCBORHeaderToHash</a>
hashHeader :: EpochSlots -> Header -> HeaderHash
headerHashAnnotated :: AHeader ByteString -> HeaderHash

-- | Extract the genesis hash and cast it into a header hash.
genesisHeaderHash :: GenesisHash -> HeaderHash
type BlockSignature = ABlockSignature ()

-- | Signature of the <tt>Block</tt>
--   
--   We use a heavyweight delegation scheme, so the signature has two
--   parts:
--   
--   <ol>
--   <li>A delegation certificate from a genesis key to the block
--   signer</li>
--   <li>The actual signature over <a>ToSign</a></li>
--   </ol>
data ABlockSignature a
ABlockSignature :: !ACertificate a -> !Signature ToSign -> ABlockSignature a
[delegationCertificate] :: ABlockSignature a -> !ACertificate a
[signature] :: ABlockSignature a -> !Signature ToSign

-- | Data to be signed in <tt>Block</tt>
data ToSign
ToSign :: !HeaderHash -> !Proof -> !EpochAndSlotCount -> !ChainDifficulty -> !ProtocolVersion -> !SoftwareVersion -> ToSign

-- | Hash of previous header in the chain
[tsHeaderHash] :: ToSign -> !HeaderHash
[tsBodyProof] :: ToSign -> !Proof
[tsSlot] :: ToSign -> !EpochAndSlotCount
[tsDifficulty] :: ToSign -> !ChainDifficulty
[tsProtocolVersion] :: ToSign -> !ProtocolVersion
[tsSoftwareVersion] :: ToSign -> !SoftwareVersion

-- | Produces the ByteString that was signed in the block
recoverSignedBytes :: EpochSlots -> AHeader ByteString -> Annotated ToSign ByteString
fromCBORBoundaryConsensusData :: Decoder s (Word64, ChainDifficulty)
dropBoundaryExtraHeaderData :: Dropper s

-- | When starting a new chain in ourorobos-consensus, we often start from
--   a non-zero epoch. This is done in order to ensure synchronisation
--   between nodes - we assume that the chain started at some fixed point
--   in the past (e.g. midnight) which all nodes can agree on despite
--   different node start times. However, the standard deserialisation
--   assumes that the genesis EBB is precisely that in epoch zero.
--   
--   In order to successfully round-trip a genesis EBB in a non-zero epoch,
--   then, we add a "magic" tag which indicates the presense of the genesis
--   hash. The choice of 255 and the word <a>Genesis</a> is completely
--   arbitrary, and only done to correspond with the matching encoder. This
--   encoding will only ever be seen when processing blocks from a demo.
dropBoundaryExtraHeaderDataRetainGenesisTag :: Decoder s Bool
dropBoundaryBody :: Dropper s
dropBoundaryExtraBodyData :: Dropper s

-- | <a>Body</a> consists of payloads of all block components
type Body = ABody ()

-- | Constructor for <a>Body</a>
pattern Body :: TxPayload -> SscPayload -> Payload -> Payload -> Body

-- | <a>Body</a> consists of payloads of all block components
data ABody a
ABody :: !ATxPayload a -> !SscPayload -> !APayload a -> !APayload a -> ABody a

-- | UTxO payload
[bodyTxPayload] :: ABody a -> !ATxPayload a

-- | Ssc payload
[bodySscPayload] :: ABody a -> !SscPayload

-- | Heavyweight delegation payload (no-ttl certificates)
[bodyDlgPayload] :: ABody a -> !APayload a

-- | Additional update information for the update system
[bodyUpdatePayload] :: ABody a -> !APayload a
bodyTxs :: Body -> [Tx]
bodyWitnesses :: Body -> [TxWitness]
type Block = ABlock ()
data ABlock a
ABlock :: AHeader a -> ABody a -> a -> ABlock a
[blockHeader] :: ABlock a -> AHeader a
[blockBody] :: ABlock a -> ABody a
[blockAnnotation] :: ABlock a -> a

-- | Smart constructor for <a>Block</a>
mkBlock :: ProtocolMagicId -> ProtocolVersion -> SoftwareVersion -> Either GenesisHash Header -> EpochSlots -> SlotNumber -> SigningKey -> Certificate -> Body -> Block

-- | Smart constructor for <a>Block</a>, without requiring the entire
--   previous <a>Header</a>. Instead, you give its hash and the difficulty
--   of this block. These are derived from the previous header in
--   <a>mkBlock</a> so if you have the previous header, consider using that
--   one.
mkBlockExplicit :: ProtocolMagicId -> ProtocolVersion -> SoftwareVersion -> HeaderHash -> ChainDifficulty -> EpochSlots -> SlotNumber -> SigningKey -> Certificate -> Body -> Block
blockHash :: EpochSlots -> Block -> HeaderHash
blockHashAnnotated :: ABlock ByteString -> HeaderHash
blockAProtocolMagicId :: ABlock a -> Annotated ProtocolMagicId a
blockProtocolMagicId :: ABlock a -> ProtocolMagicId
blockPrevHash :: ABlock a -> HeaderHash
blockProof :: ABlock a -> Proof
blockSlot :: ABlock a -> SlotNumber
blockGenesisKey :: ABlock a -> VerificationKey
blockIssuer :: ABlock a -> VerificationKey
blockDifficulty :: ABlock a -> ChainDifficulty
blockToSign :: EpochSlots -> ABlock a -> ToSign
blockSignature :: ABlock a -> ABlockSignature a
blockProtocolVersion :: ABlock a -> ProtocolVersion
blockSoftwareVersion :: ABlock a -> SoftwareVersion
blockTxPayload :: ABlock a -> ATxPayload a
blockSscPayload :: ABlock a -> SscPayload
blockDlgPayload :: ABlock a -> APayload a
blockUpdatePayload :: ABlock a -> APayload a
blockLength :: ABlock ByteString -> Natural

-- | Encode a block, given a number of slots-per-epoch.
--   
--   Unlike <a>toCBORABOBBlock</a>, this function does not take the
--   deprecated epoch boundary blocks into account.
toCBORBlock :: EpochSlots -> Block -> Encoding
fromCBORABlock :: EpochSlots -> Decoder s (ABlock ByteSpan)
renderBlock :: EpochSlots -> Block -> Builder
data ABlockOrBoundary a
ABOBBlock :: ABlock a -> ABlockOrBoundary a
ABOBBoundary :: ABoundaryBlock a -> ABlockOrBoundary a

-- | Encode a <a>Block</a> accounting for deprecated epoch boundary blocks
toCBORABOBBlock :: EpochSlots -> ABlock a -> Encoding

-- | Decode a <a>Block</a> accounting for deprecated epoch boundary blocks
fromCBORABOBBlock :: EpochSlots -> Decoder s (Maybe Block)

-- | Decode a <a>Block</a> accounting for deprecated epoch boundary blocks
--   
--   Previous versions of Cardano had an explicit boundary block between
--   epochs. A <a>Block</a> was then represented as 'Either BoundaryBlock
--   MainBlock'. We have now deprecated these explicit boundary blocks, but
--   we still need to decode blocks in the old format. In the case that we
--   find a boundary block, we drop it using <tt>dropBoundaryBlock</tt> and
--   return a <a>Nothing</a>.
fromCBORABlockOrBoundary :: EpochSlots -> Decoder s (ABlockOrBoundary ByteSpan)
toCBORABlockOrBoundary :: ProtocolMagicId -> EpochSlots -> ABlockOrBoundary a -> Encoding

-- | For a boundary block, we keep the header, body, and an annotation for
--   the whole thing (commonly the bytes from which it was decoded).
data ABoundaryBlock a
ABoundaryBlock :: !Int64 -> !ABoundaryHeader a -> !ABoundaryBody a -> !a -> ABoundaryBlock a

-- | Needed for validation.
[boundaryBlockLength] :: ABoundaryBlock a -> !Int64
[boundaryHeader] :: ABoundaryBlock a -> !ABoundaryHeader a
[boundaryBody] :: ABoundaryBlock a -> !ABoundaryBody a
[boundaryAnnotation] :: ABoundaryBlock a -> !a

-- | Extract the hash of a boundary block from its annotation.
boundaryHashAnnotated :: ABoundaryBlock ByteString -> HeaderHash
fromCBORABoundaryBlock :: Decoder s (ABoundaryBlock ByteSpan)

-- | See note on <a>toCBORABoundaryHeader</a>. This as well does not
--   necessarily invert the decoder <a>fromCBORABoundaryBlock</a>.
toCBORABoundaryBlock :: ProtocolMagicId -> ABoundaryBlock a -> Encoding

-- | toCBORABoundaryBlock but with the list length and tag discriminator
--   bytes.
toCBORABOBBoundary :: ProtocolMagicId -> ABoundaryBlock a -> Encoding

-- | Compute the slot number assigned to a boundary block
boundaryBlockSlot :: EpochSlots -> Word64 -> SlotNumber

-- | For boundary body data, we only keep an annotation. It's the body and
--   extra body data.
data ABoundaryBody a
ABoundaryBody :: !a -> ABoundaryBody a
[boundaryBodyAnnotation] :: ABoundaryBody a -> !a
data ABlockOrBoundaryHdr a
ABOBBlockHdr :: !AHeader a -> ABlockOrBoundaryHdr a
ABOBBoundaryHdr :: !ABoundaryHeader a -> ABlockOrBoundaryHdr a

-- | The analogue of <a>either</a>
aBlockOrBoundaryHdr :: (AHeader a -> b) -> (ABoundaryHeader a -> b) -> ABlockOrBoundaryHdr a -> b
fromCBORABlockOrBoundaryHdr :: EpochSlots -> Decoder s (ABlockOrBoundaryHdr ByteSpan)

-- | Encoder for <a>ABlockOrBoundaryHdr</a> which is using the annotation.
--   It is right inverse of <tt>fromCBORAblockOrBoundaryHdr</tt>.
--   
--   TODO: add a round trip test, e.g.
--   
--   <pre>
--   fromCBORABlockOrBoundaryHdr . toCBORABlockOrBoundaryHdr = id
--   </pre>
--   
--   which does not type check, but convey the meaning.
toCBORABlockOrBoundaryHdr :: ABlockOrBoundaryHdr ByteString -> Encoding

-- | The size computation is compatible with
--   <a>toCBORABlockOrBoundaryHdr</a>
toCBORABlockOrBoundaryHdrSize :: Proxy (ABlockOrBoundaryHdr a) -> Size
abobHdrFromBlock :: ABlockOrBoundary a -> ABlockOrBoundaryHdr a

-- | Slot number of the header
--   
--   NOTE: Epoch slot number calculation must match the one in
--   <tt>applyBoundary</tt>.
abobHdrSlotNo :: EpochSlots -> ABlockOrBoundaryHdr a -> SlotNumber
abobHdrChainDifficulty :: ABlockOrBoundaryHdr a -> ChainDifficulty
abobHdrHash :: ABlockOrBoundaryHdr ByteString -> HeaderHash
abobHdrPrevHash :: ABlockOrBoundaryHdr a -> Maybe HeaderHash

module Cardano.Chain.Epoch.Validation
data EpochError
EpochParseError :: ParseError -> EpochError
EpochChainValidationError :: Maybe EpochAndSlotCount -> ChainValidationError -> EpochError
Initial :: EpochError

-- | Check that a single epoch's <tt>Block</tt>s are valid by folding over
--   them TODO(KS): We should use contra-tracer here! tracing is orthogonal
--   to throwing errors; it does not change the program flow.
validateEpochFile :: forall m. MonadIO m => Tracer m EpochError -> ValidationMode -> Config -> ChainValidationState -> FilePath -> m ChainValidationState

-- | Check that a list of epochs <tt>Block</tt>s are valid.
validateEpochFiles :: ValidationMode -> Config -> ChainValidationState -> [FilePath] -> IO (Either EpochError ChainValidationState)
instance GHC.Show.Show Cardano.Chain.Epoch.Validation.EpochError
instance GHC.Classes.Eq Cardano.Chain.Epoch.Validation.EpochError


-- | Auxiliary definitions to make working with the Byron ledger easier
module Cardano.Chain.Byron.API
getDelegationMap :: ChainValidationState -> Map
getMaxBlockSize :: ChainValidationState -> Word32

-- | Apply chain tick
--   
--   This is the part of block processing that depends only on the slot
--   number of the block: We update
--   
--   <ul>
--   <li>The update state</li>
--   <li>The delegation state</li>
--   <li>The last applied slot number</li>
--   </ul>
--   
--   NOTE: The spec currently only updates the update state here; this is
--   not good enough. Fortunately, updating the delegation state and slot
--   number here (currently done in body processing) is at least
--   <i>conform</i> spec, as these updates are conform spec. See
--   
--   
--   <a>https://github.com/input-output-hk/cardano-ledger-specs/issues/1046</a>
--   <a>https://github.com/input-output-hk/ouroboros-network/issues/1291</a>
applyChainTick :: Config -> SlotNumber -> ChainValidationState -> ChainValidationState
validateBlock :: MonadError ChainValidationError m => Config -> ValidationMode -> ABlock ByteString -> HeaderHash -> ChainValidationState -> m ChainValidationState

-- | Apply a boundary block
--   
--   NOTE: The <tt>cvsLastSlot</tt> calculation must match the one in
--   <tt>abobHdrSlotNo</tt>.
validateBoundary :: MonadError ChainValidationError m => Config -> ABoundaryBlock ByteString -> ChainValidationState -> m ChainValidationState

-- | Errors that arise from applying an arbitrary mempool payload
--   
--   Although <tt>cardano-legder</tt> defines <tt>MempoolPayload</tt>, it
--   does not define a corresponding error type. We could
--   <tt>ChainValidationError</tt>, but it's too large, which is
--   problematic because we actually sent encoded versions of these errors
--   across the wire.
data ApplyMempoolPayloadErr
MempoolTxErr :: UTxOValidationError -> ApplyMempoolPayloadErr
MempoolDlgErr :: Error -> ApplyMempoolPayloadErr
MempoolUpdateProposalErr :: Error -> ApplyMempoolPayloadErr
MempoolUpdateVoteErr :: Error -> ApplyMempoolPayloadErr
applyMempoolPayload :: MonadError ApplyMempoolPayloadErr m => ValidationMode -> Config -> SlotNumber -> AMempoolPayload ByteString -> ChainValidationState -> m ChainValidationState

-- | The encoding of the mempool payload (without a
--   <tt>AMempoolPayload</tt> envelope)
mempoolPayloadRecoverBytes :: AMempoolPayload ByteString -> ByteString

-- | Re-encode the mempool payload (without any envelope)
mempoolPayloadReencode :: AMempoolPayload a -> ByteString

-- | Preview the delegation map at a slot assuming no new delegations are |
--   scheduled.
previewDelegationMap :: SlotNumber -> ChainValidationState -> Map
reAnnotateBlock :: EpochSlots -> ABlock () -> ABlock ByteString
reAnnotateBoundary :: ProtocolMagicId -> ABoundaryBlock () -> ABoundaryBlock ByteString

-- | Generalization of <a>reAnnotate</a>
reAnnotateUsing :: forall f a. Functor f => (f a -> Encoding) -> (forall s. Decoder s (f ByteSpan)) -> f a -> f ByteString

-- | Check if a block matches its header
--   
--   For EBBs, we're currently being more permissive here and not
--   performing any header-body validation but only checking whether an EBB
--   header and EBB block were provided. This seems to be fine as it won't
--   cause any loss of consensus with the old `cardano-sl` nodes.
abobMatchesBody :: ABlockOrBoundaryHdr ByteString -> ABlockOrBoundary ByteString -> Bool
