-- Copyright 2026 Biglup Labs
-- SPDX-License-Identifier: Apache-2.0
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--     https://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.

-- | Legacy genesis-authorized protocol update proposals. These envelopes are
-- distinct from Conway parameter-change governance actions. Validate input hashes
-- once, then collect changes with 'fromList' and assemble @UpdateProposal epoch changes@.
module Cometa.Protocol.ProposedUpdates
  ( ProposedUpdates,
    empty,
    fromList,
    toList,
    UpdateProposal (..),
    EncodedUpdates,
    encodeCbor,
    decodeCbor,
    toUpdates,
    toCbor,
    EncodedProposal,
    encodeProposal,
    decodeProposal,
    toProposal,
    proposalCbor,
  )
where

-- IMPORTS --------------------------------------------------------------------

import qualified Codec.CBOR.Decoding as D
import qualified Codec.CBOR.Encoding as E
import Cometa.Credential (Genesis, KeyHash)
import qualified Cometa.Credential as Credential
import Cometa.Error (Error (..))
import qualified Cometa.Internal.ProposalCbor as Cbor
import Cometa.Protocol.Parameters.Update (Update)
import qualified Cometa.Protocol.Parameters.Update as Update
import Data.ByteString (ByteString)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Word (Word64)

-- TYPES ----------------------------------------------------------------------

-- | Unique 28-byte genesis key hashes and their sparse parameter changes.
-- Equality is semantic; fresh encoding sorts by hash bytes.
newtype ProposedUpdates = ProposedUpdates (Map (KeyHash Genesis) Update) deriving (ProposedUpdates -> ProposedUpdates -> Bool
(ProposedUpdates -> ProposedUpdates -> Bool)
-> (ProposedUpdates -> ProposedUpdates -> Bool)
-> Eq ProposedUpdates
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ProposedUpdates -> ProposedUpdates -> Bool
== :: ProposedUpdates -> ProposedUpdates -> Bool
$c/= :: ProposedUpdates -> ProposedUpdates -> Bool
/= :: ProposedUpdates -> ProposedUpdates -> Bool
Eq, Int -> ProposedUpdates -> ShowS
[ProposedUpdates] -> ShowS
ProposedUpdates -> String
(Int -> ProposedUpdates -> ShowS)
-> (ProposedUpdates -> String)
-> ([ProposedUpdates] -> ShowS)
-> Show ProposedUpdates
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ProposedUpdates -> ShowS
showsPrec :: Int -> ProposedUpdates -> ShowS
$cshow :: ProposedUpdates -> String
show :: ProposedUpdates -> String
$cshowList :: [ProposedUpdates] -> ShowS
showList :: [ProposedUpdates] -> ShowS
Show)

-- | Proposed changes and their activation epoch (unsigned 64-bit).
-- Assembly does not establish era eligibility or authorization.
data UpdateProposal = UpdateProposal
  { -- | Epoch in which the proposal takes effect if accepted.
    UpdateProposal -> Word64
updateProposalEpoch :: !Word64,
    -- | Genesis-authorized sparse protocol parameter changes.
    UpdateProposal -> ProposedUpdates
updateProposalChanges :: !ProposedUpdates
  }
  deriving (UpdateProposal -> UpdateProposal -> Bool
(UpdateProposal -> UpdateProposal -> Bool)
-> (UpdateProposal -> UpdateProposal -> Bool) -> Eq UpdateProposal
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: UpdateProposal -> UpdateProposal -> Bool
== :: UpdateProposal -> UpdateProposal -> Bool
$c/= :: UpdateProposal -> UpdateProposal -> Bool
/= :: UpdateProposal -> UpdateProposal -> Bool
Eq, Int -> UpdateProposal -> ShowS
[UpdateProposal] -> ShowS
UpdateProposal -> String
(Int -> UpdateProposal -> ShowS)
-> (UpdateProposal -> String)
-> ([UpdateProposal] -> ShowS)
-> Show UpdateProposal
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> UpdateProposal -> ShowS
showsPrec :: Int -> UpdateProposal -> ShowS
$cshow :: UpdateProposal -> String
show :: UpdateProposal -> String
$cshowList :: [UpdateProposal] -> ShowS
showList :: [UpdateProposal] -> ShowS
Show)

-- | Exact map bytes with semantic changes. Equality and ordering compare bytes.
data EncodedUpdates = EncodedUpdates !ByteString !ProposedUpdates deriving (Int -> EncodedUpdates -> ShowS
[EncodedUpdates] -> ShowS
EncodedUpdates -> String
(Int -> EncodedUpdates -> ShowS)
-> (EncodedUpdates -> String)
-> ([EncodedUpdates] -> ShowS)
-> Show EncodedUpdates
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> EncodedUpdates -> ShowS
showsPrec :: Int -> EncodedUpdates -> ShowS
$cshow :: EncodedUpdates -> String
show :: EncodedUpdates -> String
$cshowList :: [EncodedUpdates] -> ShowS
showList :: [EncodedUpdates] -> ShowS
Show)

instance Eq EncodedUpdates where
  EncodedUpdates
left == :: EncodedUpdates -> EncodedUpdates -> Bool
== EncodedUpdates
right = EncodedUpdates -> ByteString
toCbor EncodedUpdates
left ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== EncodedUpdates -> ByteString
toCbor EncodedUpdates
right

instance Ord EncodedUpdates where
  compare :: EncodedUpdates -> EncodedUpdates -> Ordering
compare EncodedUpdates
left EncodedUpdates
right = ByteString -> ByteString -> Ordering
forall a. Ord a => a -> a -> Ordering
compare (EncodedUpdates -> ByteString
toCbor EncodedUpdates
left) (EncodedUpdates -> ByteString
toCbor EncodedUpdates
right)

-- | Exact proposal bytes with semantic epoch and changes. Equality and ordering
-- compare encoded bytes, not semantic data.
data EncodedProposal = EncodedProposal !ByteString !UpdateProposal deriving (Int -> EncodedProposal -> ShowS
[EncodedProposal] -> ShowS
EncodedProposal -> String
(Int -> EncodedProposal -> ShowS)
-> (EncodedProposal -> String)
-> ([EncodedProposal] -> ShowS)
-> Show EncodedProposal
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> EncodedProposal -> ShowS
showsPrec :: Int -> EncodedProposal -> ShowS
$cshow :: EncodedProposal -> String
show :: EncodedProposal -> String
$cshowList :: [EncodedProposal] -> ShowS
showList :: [EncodedProposal] -> ShowS
Show)

instance Eq EncodedProposal where
  EncodedProposal
left == :: EncodedProposal -> EncodedProposal -> Bool
== EncodedProposal
right = EncodedProposal -> ByteString
proposalCbor EncodedProposal
left ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== EncodedProposal -> ByteString
proposalCbor EncodedProposal
right

instance Ord EncodedProposal where
  compare :: EncodedProposal -> EncodedProposal -> Ordering
compare EncodedProposal
left EncodedProposal
right = ByteString -> ByteString -> Ordering
forall a. Ord a => a -> a -> Ordering
compare (EncodedProposal -> ByteString
proposalCbor EncodedProposal
left) (EncodedProposal -> ByteString
proposalCbor EncodedProposal
right)

-- DEFINITIONS ----------------------------------------------------------------

-- | No proposed changes.
empty :: ProposedUpdates
empty :: ProposedUpdates
empty = Map (KeyHash Genesis) Update -> ProposedUpdates
ProposedUpdates Map (KeyHash Genesis) Update
forall k a. Map k a
Map.empty

-- | Validate unique genesis hashes. Repeated keys return 'DuplicateProtocolUpdate'
-- even when their updates agree, rather than silently discarding an instruction.
fromList :: [(KeyHash Genesis, Update)] -> Either Error ProposedUpdates
fromList :: [(KeyHash Genesis, Update)] -> Either Error ProposedUpdates
fromList [(KeyHash Genesis, Update)]
values = Map (KeyHash Genesis) Update -> ProposedUpdates
ProposedUpdates (Map (KeyHash Genesis) Update -> ProposedUpdates)
-> Either Error (Map (KeyHash Genesis) Update)
-> Either Error ProposedUpdates
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Error
-> [(KeyHash Genesis, Update)]
-> Either Error (Map (KeyHash Genesis) Update)
forall key value.
Ord key =>
Error -> [(key, value)] -> Either Error (Map key value)
Cbor.uniqueMap Error
DuplicateProtocolUpdate [(KeyHash Genesis, Update)]
values

-- | Entries sorted by exact genesis hash bytes.
toList :: ProposedUpdates -> [(KeyHash Genesis, Update)]
toList :: ProposedUpdates -> [(KeyHash Genesis, Update)]
toList (ProposedUpdates Map (KeyHash Genesis) Update
values) = Map (KeyHash Genesis) Update -> [(KeyHash Genesis, Update)]
forall k a. Map k a -> [(k, a)]
Map.toAscList Map (KeyHash Genesis) Update
values

-- | Fresh definite map, with sorted hashes and fresh sparse update encodings.
encodeCbor :: ProposedUpdates -> ByteString
encodeCbor :: ProposedUpdates -> ByteString
encodeCbor ProposedUpdates
value =
  Encoding -> ByteString
Cbor.encode
    ( Word -> Encoding
E.encodeMapLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([(KeyHash Genesis, Update)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(KeyHash Genesis, Update)]
entries))
        Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ((KeyHash Genesis, Update) -> Encoding)
-> [(KeyHash Genesis, Update)] -> Encoding
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (\(KeyHash Genesis
key, Update
change) -> ByteString -> Encoding
E.encodeBytes (KeyHash Genesis -> ByteString
forall purpose. KeyHash purpose -> ByteString
Credential.keyHashBytes KeyHash Genesis
key) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ByteString -> Encoding
Cbor.raw (Update -> ByteString
Update.encodeCbor Update
change)) [(KeyHash Genesis, Update)]
entries
    )
  where
    entries :: [(KeyHash Genesis, Update)]
entries = ProposedUpdates -> [(KeyHash Genesis, Update)]
toList ProposedUpdates
value

-- | Decode one complete map and retain original bytes. Duplicate hashes,
-- incorrect hash lengths, invalid updates and trailing bytes return
-- 'Cometa.Error.InvalidProposalCbor'.
decodeCbor :: ByteString -> Either Error EncodedUpdates
decodeCbor :: ByteString -> Either Error EncodedUpdates
decodeCbor ByteString
bytes = ByteString -> ProposedUpdates -> EncodedUpdates
EncodedUpdates ByteString
bytes (ProposedUpdates -> EncodedUpdates)
-> Either Error ProposedUpdates -> Either Error EncodedUpdates
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (forall s. Decoder s ProposedUpdates)
-> ByteString -> Either Error ProposedUpdates
forall a. (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decode Decoder s ProposedUpdates
forall s. Decoder s ProposedUpdates
updatesDecoder ByteString
bytes

-- | Inspect semantic changes without altering the exact encoding.
toUpdates :: EncodedUpdates -> ProposedUpdates
toUpdates :: EncodedUpdates -> ProposedUpdates
toUpdates (EncodedUpdates ByteString
_ ProposedUpdates
value) = ProposedUpdates
value

-- | Exact imported update-map CBOR.
toCbor :: EncodedUpdates -> ByteString
toCbor :: EncodedUpdates -> ByteString
toCbor (EncodedUpdates ByteString
bytes ProposedUpdates
_) = ByteString
bytes

-- | Fresh definite @[changes, epoch]@ array with shortest integers.
encodeProposal :: UpdateProposal -> ByteString
encodeProposal :: UpdateProposal -> ByteString
encodeProposal (UpdateProposal Word64
epoch ProposedUpdates
changes) =
  Encoding -> ByteString
Cbor.encode
    (Word -> Encoding
E.encodeListLen Word
2 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ByteString -> Encoding
Cbor.raw (ProposedUpdates -> ByteString
encodeCbor ProposedUpdates
changes) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Word64 -> Encoding
E.encodeWord64 Word64
epoch)

-- | Decode a complete legacy proposal and retain exact bytes. Invalid schema
-- or trailing bytes returns 'Cometa.Error.InvalidProposalCbor'.
decodeProposal :: ByteString -> Either Error EncodedProposal
decodeProposal :: ByteString -> Either Error EncodedProposal
decodeProposal ByteString
bytes =
  ByteString -> UpdateProposal -> EncodedProposal
EncodedProposal ByteString
bytes
    (UpdateProposal -> EncodedProposal)
-> Either Error UpdateProposal -> Either Error EncodedProposal
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (forall s. Decoder s UpdateProposal)
-> ByteString -> Either Error UpdateProposal
forall a. (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decode
      (Int -> Decoder s UpdateProposal -> Decoder s UpdateProposal
forall s a. Int -> Decoder s a -> Decoder s a
Cbor.array Int
2 ((Word64 -> ProposedUpdates -> UpdateProposal)
-> ProposedUpdates -> Word64 -> UpdateProposal
forall a b c. (a -> b -> c) -> b -> a -> c
flip Word64 -> ProposedUpdates -> UpdateProposal
UpdateProposal (ProposedUpdates -> Word64 -> UpdateProposal)
-> Decoder s ProposedUpdates
-> Decoder s (Word64 -> UpdateProposal)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s ProposedUpdates
forall s. Decoder s ProposedUpdates
updatesDecoder Decoder s (Word64 -> UpdateProposal)
-> Decoder s Word64 -> Decoder s UpdateProposal
forall a b. Decoder s (a -> b) -> Decoder s a -> Decoder s b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Decoder s Word64
forall s. Decoder s Word64
D.decodeWord64))
      ByteString
bytes

-- | Inspect activation epoch and changes without altering retained bytes.
toProposal :: EncodedProposal -> UpdateProposal
toProposal :: EncodedProposal -> UpdateProposal
toProposal (EncodedProposal ByteString
_ UpdateProposal
value) = UpdateProposal
value

-- | Exact imported legacy proposal CBOR.
proposalCbor :: EncodedProposal -> ByteString
proposalCbor :: EncodedProposal -> ByteString
proposalCbor (EncodedProposal ByteString
bytes UpdateProposal
_) = ByteString
bytes

updatesDecoder :: D.Decoder s ProposedUpdates
updatesDecoder :: forall s. Decoder s ProposedUpdates
updatesDecoder = do
  [(KeyHash Genesis, Update)]
entries <- Decoder s (KeyHash Genesis, Update)
-> Decoder s [(KeyHash Genesis, Update)]
forall s a. Decoder s a -> Decoder s [a]
Cbor.entries (Decoder s (KeyHash Genesis, Update)
 -> Decoder s [(KeyHash Genesis, Update)])
-> Decoder s (KeyHash Genesis, Update)
-> Decoder s [(KeyHash Genesis, Update)]
forall a b. (a -> b) -> a -> b
$ do
    KeyHash Genesis
key <- Decoder s ByteString
forall s. Decoder s ByteString
D.decodeBytes Decoder s ByteString
-> (ByteString -> Decoder s (KeyHash Genesis))
-> Decoder s (KeyHash Genesis)
forall a b. Decoder s a -> (a -> Decoder s b) -> Decoder s b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (Error -> Decoder s (KeyHash Genesis))
-> (KeyHash Genesis -> Decoder s (KeyHash Genesis))
-> Either Error (KeyHash Genesis)
-> Decoder s (KeyHash Genesis)
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> Decoder s (KeyHash Genesis)
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> Decoder s (KeyHash Genesis))
-> (Error -> String) -> Error -> Decoder s (KeyHash Genesis)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Error -> String
forall a. Show a => a -> String
show) KeyHash Genesis -> Decoder s (KeyHash Genesis)
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error (KeyHash Genesis) -> Decoder s (KeyHash Genesis))
-> (ByteString -> Either Error (KeyHash Genesis))
-> ByteString
-> Decoder s (KeyHash Genesis)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either Error (KeyHash Genesis)
forall purpose. ByteString -> Either Error (KeyHash purpose)
Credential.keyHashFromBytes
    Update
change <- EncodedUpdate -> Update
Update.toUpdate (EncodedUpdate -> Update)
-> Decoder s EncodedUpdate -> Decoder s Update
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (ByteString -> Either Error EncodedUpdate)
-> Decoder s EncodedUpdate
forall a s. (ByteString -> Either Error a) -> Decoder s a
Cbor.nested ByteString -> Either Error EncodedUpdate
Update.decodeCbor
    (KeyHash Genesis, Update) -> Decoder s (KeyHash Genesis, Update)
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (KeyHash Genesis
key, Update
change)
  (Error -> Decoder s ProposedUpdates)
-> (ProposedUpdates -> Decoder s ProposedUpdates)
-> Either Error ProposedUpdates
-> Decoder s ProposedUpdates
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> Decoder s ProposedUpdates
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> Decoder s ProposedUpdates)
-> (Error -> String) -> Error -> Decoder s ProposedUpdates
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Error -> String
forall a. Show a => a -> String
show) ProposedUpdates -> Decoder s ProposedUpdates
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([(KeyHash Genesis, Update)] -> Either Error ProposedUpdates
fromList [(KeyHash Genesis, Update)]
entries)