-- 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.
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}

-- | Private complete CBOR decoding and nested semantic-codec composition.
-- No native objects or arbitrary effect boundaries are involved.
module Cometa.Internal.ProposalCbor
  ( encode,
    decode,
    raw,
    nested,
    array,
    finishArray,
    list,
    entries,
    optional,
    maybeEncoding,
    credentialEncoding,
    credentialDecoder,
    uniqueMap,
    setList,
  )
where

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

import qualified Codec.CBOR.Decoding as D
import qualified Codec.CBOR.Encoding as E
import qualified Codec.CBOR.Read as R
import qualified Codec.CBOR.Term as T
import qualified Codec.CBOR.Write as W
import qualified Cometa.Credential as C
import Cometa.Error (Error (..))
import Control.Monad (foldM, replicateM, unless)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as L
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import qualified Data.Text as Text

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

encode :: E.Encoding -> ByteString
encode :: Encoding -> ByteString
encode = Encoding -> ByteString
W.toStrictByteString

decode :: (forall s. D.Decoder s a) -> ByteString -> Either Error a
decode :: forall a. (forall s. Decoder s a) -> ByteString -> Either Error a
decode forall s. Decoder s a
parser ByteString
bytes = case (forall s. Decoder s a)
-> ByteString -> Either DeserialiseFailure (ByteString, a)
forall a.
(forall s. Decoder s a)
-> ByteString -> Either DeserialiseFailure (ByteString, a)
R.deserialiseFromBytes Decoder s a
forall s. Decoder s a
parser (ByteString -> ByteString
L.fromStrict ByteString
bytes) of
  Left DeserialiseFailure
failure -> Error -> Either Error a
forall a b. a -> Either a b
Left (Text -> Error
InvalidProposalCbor (String -> Text
Text.pack (DeserialiseFailure -> String
forall a. Show a => a -> String
show DeserialiseFailure
failure)))
  Right (ByteString
rest, a
value)
    | ByteString -> Bool
L.null ByteString
rest -> a -> Either Error a
forall a b. b -> Either a b
Right a
value
    | Bool
otherwise -> Error -> Either Error a
forall a b. a -> Either a b
Left (Text -> Error
InvalidProposalCbor Text
"Trailing proposal CBOR")

raw :: ByteString -> E.Encoding
raw :: ByteString -> Encoding
raw = ByteString -> Encoding
E.encodePreEncoded

nested :: (ByteString -> Either Error a) -> D.Decoder s a
nested :: forall a s. (ByteString -> Either Error a) -> Decoder s a
nested ByteString -> Either Error a
parser = do
  Term
term <- Decoder s Term
forall s. Decoder s Term
T.decodeTerm
  (Error -> Decoder s a)
-> (a -> Decoder s a) -> Either Error a -> Decoder s a
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> Decoder s a
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> Decoder s a)
-> (Error -> String) -> Error -> Decoder s a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Error -> String
forall a. Show a => a -> String
show) a -> Decoder s a
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ByteString -> Either Error a
parser (Encoding -> ByteString
encode (Term -> Encoding
T.encodeTerm Term
term)))

array :: Int -> D.Decoder s a -> D.Decoder s a
array :: forall s a. Int -> Decoder s a -> Decoder s a
array Int
count Decoder s a
parser = do
  Maybe Int
size <- Decoder s (Maybe Int)
forall s. Decoder s (Maybe Int)
D.decodeListLenOrIndef
  case Maybe Int
size of
    Just Int
actual -> Bool -> Decoder s () -> Decoder s ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Int
actual Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
count) (String -> Decoder s ()
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"Incorrect proposal array arity")
    Maybe Int
Nothing -> () -> Decoder s ()
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  a
value <- Decoder s a
parser
  Maybe Int -> Decoder s ()
forall s. Maybe Int -> Decoder s ()
finishArray Maybe Int
size
  a -> Decoder s a
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure a
value

finishArray :: Maybe Int -> D.Decoder s ()
finishArray :: forall s. Maybe Int -> Decoder s ()
finishArray Maybe Int
size = case Maybe Int
size of
  Just Int
_ -> () -> Decoder s ()
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  Maybe Int
Nothing -> do
    Bool
ended <- Decoder s Bool
forall s. Decoder s Bool
D.decodeBreakOr
    Bool -> Decoder s () -> Decoder s ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless Bool
ended (String -> Decoder s ()
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"Extra proposal array elements")

list :: D.Decoder s a -> D.Decoder s [a]
list :: forall s a. Decoder s a -> Decoder s [a]
list Decoder s a
parser = Decoder s (Maybe Int)
forall s. Decoder s (Maybe Int)
D.decodeListLenOrIndef Decoder s (Maybe Int)
-> (Maybe Int -> Decoder s [a]) -> Decoder s [a]
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
>>= Decoder s a -> Maybe Int -> Decoder s [a]
forall s a. Decoder s a -> Maybe Int -> Decoder s [a]
sequenceLength Decoder s a
parser

entries :: D.Decoder s a -> D.Decoder s [a]
entries :: forall s a. Decoder s a -> Decoder s [a]
entries Decoder s a
parser = Decoder s (Maybe Int)
forall s. Decoder s (Maybe Int)
D.decodeMapLenOrIndef Decoder s (Maybe Int)
-> (Maybe Int -> Decoder s [a]) -> Decoder s [a]
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
>>= Decoder s a -> Maybe Int -> Decoder s [a]
forall s a. Decoder s a -> Maybe Int -> Decoder s [a]
sequenceLength Decoder s a
parser

sequenceLength :: D.Decoder s a -> Maybe Int -> D.Decoder s [a]
sequenceLength :: forall s a. Decoder s a -> Maybe Int -> Decoder s [a]
sequenceLength Decoder s a
parser Maybe Int
size = case Maybe Int
size of
  Just Int
count -> Int -> Decoder s a -> Decoder s [a]
forall (m :: * -> *) a. Applicative m => Int -> m a -> m [a]
replicateM Int
count Decoder s a
parser
  Maybe Int
Nothing -> Decoder s [a]
go
  where
    go :: Decoder s [a]
go = do
      Bool
ended <- Decoder s Bool
forall s. Decoder s Bool
D.decodeBreakOr
      if Bool
ended then [a] -> Decoder s [a]
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure [] else (:) (a -> [a] -> [a]) -> Decoder s a -> Decoder s ([a] -> [a])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s a
parser Decoder s ([a] -> [a]) -> Decoder s [a] -> Decoder s [a]
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 [a]
go

optional :: D.Decoder s a -> D.Decoder s (Maybe a)
optional :: forall s a. Decoder s a -> Decoder s (Maybe a)
optional Decoder s a
parser = do
  TokenType
token <- Decoder s TokenType
forall s. Decoder s TokenType
D.peekTokenType
  if TokenType
token TokenType -> TokenType -> Bool
forall a. Eq a => a -> a -> Bool
== TokenType
D.TypeNull then Decoder s ()
forall s. Decoder s ()
D.decodeNull Decoder s () -> Decoder s (Maybe a) -> Decoder s (Maybe a)
forall a b. Decoder s a -> Decoder s b -> Decoder s b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Maybe a -> Decoder s (Maybe a)
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe a
forall a. Maybe a
Nothing else a -> Maybe a
forall a. a -> Maybe a
Just (a -> Maybe a) -> Decoder s a -> Decoder s (Maybe a)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s a
parser

maybeEncoding :: (a -> E.Encoding) -> Maybe a -> E.Encoding
maybeEncoding :: forall a. (a -> Encoding) -> Maybe a -> Encoding
maybeEncoding = Encoding -> (a -> Encoding) -> Maybe a -> Encoding
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Encoding
E.encodeNull

credentialEncoding :: C.Credential purpose -> E.Encoding
credentialEncoding :: forall purpose. Credential purpose -> Encoding
credentialEncoding Credential purpose
credential =
  Word -> Encoding
E.encodeListLen Word
2 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> case Credential purpose
credential of
    C.KeyCredential KeyHash purpose
hash -> Word -> Encoding
E.encodeWord Word
0 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ByteString -> Encoding
E.encodeBytes (KeyHash purpose -> ByteString
forall purpose. KeyHash purpose -> ByteString
C.keyHashBytes KeyHash purpose
hash)
    C.ScriptCredential ScriptHash
hash -> Word -> Encoding
E.encodeWord Word
1 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ByteString -> Encoding
E.encodeBytes (ScriptHash -> ByteString
C.scriptHashBytes ScriptHash
hash)

credentialDecoder :: D.Decoder s (C.Credential purpose)
credentialDecoder :: forall s purpose. Decoder s (Credential purpose)
credentialDecoder = Int
-> Decoder s (Credential purpose) -> Decoder s (Credential purpose)
forall s a. Int -> Decoder s a -> Decoder s a
array Int
2 (Decoder s (Credential purpose) -> Decoder s (Credential purpose))
-> Decoder s (Credential purpose) -> Decoder s (Credential purpose)
forall a b. (a -> b) -> a -> b
$ do
  Word
kind <- Decoder s Word
forall s. Decoder s Word
D.decodeWord
  ByteString
bytes <- Decoder s ByteString
forall s. Decoder s ByteString
D.decodeBytes
  case Word
kind of
    Word
0 -> (Error -> Decoder s (Credential purpose))
-> (KeyHash purpose -> Decoder s (Credential purpose))
-> Either Error (KeyHash purpose)
-> Decoder s (Credential purpose)
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> Decoder s (Credential purpose)
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> Decoder s (Credential purpose))
-> (Error -> String) -> Error -> Decoder s (Credential purpose)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Error -> String
forall a. Show a => a -> String
show) (Credential purpose -> Decoder s (Credential purpose)
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Credential purpose -> Decoder s (Credential purpose))
-> (KeyHash purpose -> Credential purpose)
-> KeyHash purpose
-> Decoder s (Credential purpose)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. KeyHash purpose -> Credential purpose
forall purpose. KeyHash purpose -> Credential purpose
C.KeyCredential) (ByteString -> Either Error (KeyHash purpose)
forall purpose. ByteString -> Either Error (KeyHash purpose)
C.keyHashFromBytes ByteString
bytes)
    Word
1 -> (Error -> Decoder s (Credential purpose))
-> (ScriptHash -> Decoder s (Credential purpose))
-> Either Error ScriptHash
-> Decoder s (Credential purpose)
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> Decoder s (Credential purpose)
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> Decoder s (Credential purpose))
-> (Error -> String) -> Error -> Decoder s (Credential purpose)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Error -> String
forall a. Show a => a -> String
show) (Credential purpose -> Decoder s (Credential purpose)
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Credential purpose -> Decoder s (Credential purpose))
-> (ScriptHash -> Credential purpose)
-> ScriptHash
-> Decoder s (Credential purpose)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ScriptHash -> Credential purpose
forall purpose. ScriptHash -> Credential purpose
C.ScriptCredential) (ByteString -> Either Error ScriptHash
C.scriptHashFromBytes ByteString
bytes)
    Word
_ -> String -> Decoder s (Credential purpose)
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"Invalid credential kind"

uniqueMap :: (Ord key) => Error -> [(key, value)] -> Either Error (Map key value)
uniqueMap :: forall key value.
Ord key =>
Error -> [(key, value)] -> Either Error (Map key value)
uniqueMap Error
duplicate = (Map key value -> (key, value) -> Either Error (Map key value))
-> Map key value -> [(key, value)] -> Either Error (Map key value)
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM Map key value -> (key, value) -> Either Error (Map key value)
forall {k} {a}.
Ord k =>
Map k a -> (k, a) -> Either Error (Map k a)
insert Map key value
forall k a. Map k a
Map.empty
  where
    insert :: Map k a -> (k, a) -> Either Error (Map k a)
insert Map k a
values (k
key, a
value)
      | k -> Map k a -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.member k
key Map k a
values = Error -> Either Error (Map k a)
forall a b. a -> Either a b
Left Error
duplicate
      | Bool
otherwise = Map k a -> Either Error (Map k a)
forall a b. b -> Either a b
Right (k -> a -> Map k a -> Map k a
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert k
key a
value Map k a
values)

setList :: D.Decoder s a -> D.Decoder s [a]
setList :: forall s a. Decoder s a -> Decoder s [a]
setList Decoder s a
parser = do
  TokenType
token <- Decoder s TokenType
forall s. Decoder s TokenType
D.peekTokenType
  case TokenType
token of
    TokenType
D.TypeTag -> Decoder s ()
forall s. Decoder s ()
checkTag
    TokenType
D.TypeTag64 -> Decoder s ()
forall s. Decoder s ()
checkTag
    TokenType
_ -> () -> Decoder s ()
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  Decoder s a -> Decoder s [a]
forall s a. Decoder s a -> Decoder s [a]
list Decoder s a
parser
  where
    checkTag :: Decoder s ()
checkTag = do
      Word64
tag <- Decoder s Word64
forall s. Decoder s Word64
D.decodeTag64
      Bool -> Decoder s () -> Decoder s ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Word64
tag Word64 -> Word64 -> Bool
forall a. Eq a => a -> a -> Bool
== Word64
258) (String -> Decoder s ()
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"Invalid set tag")