-- 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 #-}

-- | Standalone CBOR for native collection shapes. Association lists retain
-- explicit zero and repeated keys, unlike normalized asset bundles. All codecs
-- sort stably by encoded key byte length then lexicographic bytes. Equal keys
-- keep their relative order. These are semantic encodings, not original bytes.
--
-- @
-- import qualified Cometa.Encoding.Collections as Collections
--
-- emptyWithdrawals = Collections.encodeWithdrawalsCbor []
-- @
module Cometa.Encoding.Collections
  ( encodeAssetNamesCbor,
    decodeAssetNamesCbor,
    encodeWithdrawalsCbor,
    decodeWithdrawalsCbor,
    encodeHashesCbor,
    encodeHashesCborWith,
    decodeHashesCbor,
  )
where

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

import qualified Codec.CBOR.Decoding as D
import qualified Codec.CBOR.Encoding as E
import qualified Codec.CBOR.Term as T
import Cometa.Address.Reward (RewardAddress)
import qualified Cometa.Address.Reward as Reward
import Cometa.AssetName (AssetName)
import qualified Cometa.AssetName as Name
import Cometa.Crypto.Blake2b (Blake2bHash)
import qualified Cometa.Crypto.Blake2b as Hash
import Cometa.Encoding.Set (SetEncoding (..))
import Cometa.Error (Error (..))
import qualified Cometa.Internal.TransactionCbor as Cbor
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import Data.Int (Int64)
import Data.List (sortOn)
import Data.Word (Word64)

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

-- | Encode one policy's asset-name quantities. Zero and duplicate entries are
-- retained, including empty names. Quantities must fit signed 64 bits;
-- otherwise return 'InvalidValueQuantity'. Empty input encodes an empty map.
encodeAssetNamesCbor :: [(AssetName, Integer)] -> Either Error ByteString
encodeAssetNamesCbor :: [(AssetName, Integer)] -> Either Error ByteString
encodeAssetNamesCbor [(AssetName, Integer)]
pairs = do
  ((AssetName, Integer) -> Either Error ())
-> [(AssetName, Integer)] -> Either Error ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (AssetName, Integer) -> Either Error ()
forall {a}. (a, Integer) -> Either Error ()
validate [(AssetName, Integer)]
pairs
  ByteString -> Either Error ByteString
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((AssetName -> ByteString)
-> (Integer -> Encoding) -> [(AssetName, Integer)] -> ByteString
forall a b.
(a -> ByteString) -> (b -> Encoding) -> [(a, b)] -> ByteString
encodeMap AssetName -> ByteString
Name.toBytes Integer -> Encoding
E.encodeInteger [(AssetName, Integer)]
pairs)
  where
    validate :: (a, Integer) -> Either Error ()
validate (a
_, Integer
amount)
      | Integer
amount Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Int64
forall a. Bounded a => a
minBound :: Int64) Bool -> Bool -> Bool
|| Integer
amount Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Int64
forall a. Bounded a => a
maxBound :: Int64) = Error -> Either Error ()
forall a b. a -> Either a b
Left (Integer -> Error
InvalidValueQuantity Integer
amount)
      | Bool
otherwise = () -> Either Error ()
forall a b. b -> Either a b
Right ()

-- | Decode a complete definite or indefinite asset-name map, retaining zero and
-- duplicate entries. Names must contain at most 32 bytes and quantities must fit
-- signed 64 bits. Malformed maps return 'InvalidValueCbor'.
decodeAssetNamesCbor :: ByteString -> Either Error [(AssetName, Integer)]
decodeAssetNamesCbor :: ByteString -> Either Error [(AssetName, Integer)]
decodeAssetNamesCbor = (Text -> Error)
-> (forall {s}. Decoder s [(AssetName, Integer)])
-> ByteString
-> Either Error [(AssetName, Integer)]
forall a.
(Text -> Error)
-> (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decodeAs Text -> Error
InvalidValueCbor ((forall {s}. Decoder s [(AssetName, Integer)])
 -> ByteString -> Either Error [(AssetName, Integer)])
-> (forall {s}. Decoder s [(AssetName, Integer)])
-> ByteString
-> Either Error [(AssetName, Integer)]
forall a b. (a -> b) -> a -> b
$ do
  [(AssetName, Integer)]
pairs <- Decoder s (AssetName, Integer) -> Decoder s [(AssetName, Integer)]
forall s a. Decoder s a -> Decoder s [a]
Cbor.entries ((,) (AssetName -> Integer -> (AssetName, Integer))
-> Decoder s AssetName
-> Decoder s (Integer -> (AssetName, Integer))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (ByteString -> Either Error AssetName) -> Decoder s AssetName
forall a s. (ByteString -> Either Error a) -> Decoder s a
checked ByteString -> Either Error AssetName
Name.fromBytes Decoder s (Integer -> (AssetName, Integer))
-> Decoder s Integer -> Decoder s (AssetName, Integer)
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
<*> (Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Int64 -> Integer) -> Decoder s Int64 -> Decoder s Integer
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s Int64
forall s. Decoder s Int64
D.decodeInt64))
  [(AssetName, Integer)] -> Decoder s [(AssetName, Integer)]
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (((AssetName, Integer) -> ByteString)
-> [(AssetName, Integer)] -> [(AssetName, Integer)]
forall a. (a -> ByteString) -> [a] -> [a]
ordered (AssetName -> ByteString
Name.toBytes (AssetName -> ByteString)
-> ((AssetName, Integer) -> AssetName)
-> (AssetName, Integer)
-> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (AssetName, Integer) -> AssetName
forall a b. (a, b) -> a
fst) [(AssetName, Integer)]
pairs)

-- | Encode reward accounts and unsigned lovelace amounts. Zero and duplicate
-- entries are retained; empty input is an empty map, not absent withdrawals.
-- Amounts span the full unsigned 64-bit range, independent of builder limits.
encodeWithdrawalsCbor :: [(RewardAddress, Word64)] -> ByteString
encodeWithdrawalsCbor :: [(RewardAddress, Word64)] -> ByteString
encodeWithdrawalsCbor = (RewardAddress -> ByteString)
-> (Word64 -> Encoding) -> [(RewardAddress, Word64)] -> ByteString
forall a b.
(a -> ByteString) -> (b -> Encoding) -> [(a, b)] -> ByteString
encodeMap RewardAddress -> ByteString
Reward.toBytes Word64 -> Encoding
E.encodeWord64

-- | Decode a complete definite or indefinite withdrawal map, including empty
-- maps, zero and duplicate entries. Keys must be exact reward-account bytes;
-- negative or oversized amounts and malformed keys return 'InvalidTransactionCbor'.
decodeWithdrawalsCbor :: ByteString -> Either Error [(RewardAddress, Word64)]
decodeWithdrawalsCbor :: ByteString -> Either Error [(RewardAddress, Word64)]
decodeWithdrawalsCbor = (Text -> Error)
-> (forall {s}. Decoder s [(RewardAddress, Word64)])
-> ByteString
-> Either Error [(RewardAddress, Word64)]
forall a.
(Text -> Error)
-> (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decodeAs Text -> Error
InvalidTransactionCbor ((forall {s}. Decoder s [(RewardAddress, Word64)])
 -> ByteString -> Either Error [(RewardAddress, Word64)])
-> (forall {s}. Decoder s [(RewardAddress, Word64)])
-> ByteString
-> Either Error [(RewardAddress, Word64)]
forall a b. (a -> b) -> a -> b
$ do
  [(RewardAddress, Word64)]
pairs <- Decoder s (RewardAddress, Word64)
-> Decoder s [(RewardAddress, Word64)]
forall s a. Decoder s a -> Decoder s [a]
Cbor.entries ((,) (RewardAddress -> Word64 -> (RewardAddress, Word64))
-> Decoder s RewardAddress
-> Decoder s (Word64 -> (RewardAddress, Word64))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (ByteString -> Either Error RewardAddress)
-> Decoder s RewardAddress
forall a s. (ByteString -> Either Error a) -> Decoder s a
checked ByteString -> Either Error RewardAddress
Reward.fromBytes Decoder s (Word64 -> (RewardAddress, Word64))
-> Decoder s Word64 -> Decoder s (RewardAddress, Word64)
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)
  [(RewardAddress, Word64)] -> Decoder s [(RewardAddress, Word64)]
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (((RewardAddress, Word64) -> ByteString)
-> [(RewardAddress, Word64)] -> [(RewardAddress, Word64)]
forall a. (a -> ByteString) -> [a] -> [a]
ordered (RewardAddress -> ByteString
Reward.toBytes (RewardAddress -> ByteString)
-> ((RewardAddress, Word64) -> RewardAddress)
-> (RewardAddress, Word64)
-> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (RewardAddress, Word64) -> RewardAddress
forall a b. (a, b) -> a
fst) [(RewardAddress, Word64)]
pairs)

-- | Encode variable-length nonempty digests as a tag-258 array. Despite the
-- native name “hash set”, duplicate digests are retained. Empty input is valid.
encodeHashesCbor :: [Blake2bHash] -> ByteString
encodeHashesCbor :: [Blake2bHash] -> ByteString
encodeHashesCbor = SetEncoding -> [Blake2bHash] -> ByteString
encodeHashesCborWith SetEncoding
TaggedSet

-- | Choose whether a freshly encoded digest array carries tag 258. Ordering
-- and duplicate retention match 'encodeHashesCbor'.
encodeHashesCborWith :: SetEncoding -> [Blake2bHash] -> ByteString
encodeHashesCborWith :: SetEncoding -> [Blake2bHash] -> ByteString
encodeHashesCborWith SetEncoding
style [Blake2bHash]
hashes =
  Encoding -> ByteString
Cbor.encode (Encoding -> ByteString) -> Encoding -> ByteString
forall a b. (a -> b) -> a -> b
$
    Encoding
tag
      Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Word -> Encoding
E.encodeListLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([Blake2bHash] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Blake2bHash]
hashes))
      Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> (Blake2bHash -> Encoding) -> [Blake2bHash] -> Encoding
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (ByteString -> Encoding
E.encodeBytes (ByteString -> Encoding)
-> (Blake2bHash -> ByteString) -> Blake2bHash -> Encoding
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Blake2bHash -> ByteString
Hash.toBytes) ((Blake2bHash -> ByteString) -> [Blake2bHash] -> [Blake2bHash]
forall a. (a -> ByteString) -> [a] -> [a]
ordered Blake2bHash -> ByteString
Hash.toBytes [Blake2bHash]
hashes)
  where
    tag :: Encoding
tag = case SetEncoding
style of
      SetEncoding
TaggedSet -> Word -> Encoding
E.encodeTag Word
258
      SetEncoding
UntaggedSet -> Encoding
forall a. Monoid a => a
mempty

-- | Decode a complete definite or indefinite digest array, optionally tagged
-- 258. Each digest must be a definite-length nonempty byte string, matching
-- the native hash reader; hash lengths may differ. Duplicate hashes
-- survive decoding. Wrong tags, empty hashes and malformed input return
-- 'InvalidHashCbor'. The tag is not retained by this semantic decoder.
decodeHashesCbor :: ByteString -> Either Error [Blake2bHash]
decodeHashesCbor :: ByteString -> Either Error [Blake2bHash]
decodeHashesCbor =
  (Text -> Error)
-> (forall {s}. Decoder s [Blake2bHash])
-> ByteString
-> Either Error [Blake2bHash]
forall a.
(Text -> Error)
-> (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decodeAs Text -> Error
InvalidHashCbor ((forall {s}. Decoder s [Blake2bHash])
 -> ByteString -> Either Error [Blake2bHash])
-> (forall {s}. Decoder s [Blake2bHash])
-> ByteString
-> Either Error [Blake2bHash]
forall a b. (a -> b) -> a -> b
$
    (Blake2bHash -> ByteString) -> [Blake2bHash] -> [Blake2bHash]
forall a. (a -> ByteString) -> [a] -> [a]
ordered Blake2bHash -> ByteString
Hash.toBytes ([Blake2bHash] -> [Blake2bHash])
-> Decoder s [Blake2bHash] -> Decoder s [Blake2bHash]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s Blake2bHash -> Decoder s [Blake2bHash]
forall s a. Decoder s a -> Decoder s [a]
Cbor.setList (Decoder s ByteString
forall s. Decoder s ByteString
D.decodeBytes Decoder s ByteString
-> (ByteString -> Decoder s Blake2bHash) -> Decoder s Blake2bHash
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 Blake2bHash)
-> (Blake2bHash -> Decoder s Blake2bHash)
-> Either Error Blake2bHash
-> Decoder s Blake2bHash
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> Decoder s Blake2bHash
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> Decoder s Blake2bHash)
-> (Error -> String) -> Error -> Decoder s Blake2bHash
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Error -> String
forall a. Show a => a -> String
show) Blake2bHash -> Decoder s Blake2bHash
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error Blake2bHash -> Decoder s Blake2bHash)
-> (ByteString -> Either Error Blake2bHash)
-> ByteString
-> Decoder s Blake2bHash
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either Error Blake2bHash
Hash.fromBytes)

encodeMap :: (a -> ByteString) -> (b -> E.Encoding) -> [(a, b)] -> ByteString
encodeMap :: forall a b.
(a -> ByteString) -> (b -> Encoding) -> [(a, b)] -> ByteString
encodeMap a -> ByteString
key b -> Encoding
value [(a, b)]
pairs =
  Encoding -> ByteString
Cbor.encode (Encoding -> ByteString) -> Encoding -> ByteString
forall a b. (a -> b) -> a -> b
$
    Word -> Encoding
E.encodeMapLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([(a, b)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(a, b)]
pairs))
      Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ((a, b) -> Encoding) -> [(a, b)] -> Encoding
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (\(a
k, b
v) -> ByteString -> Encoding
E.encodeBytes (a -> ByteString
key a
k) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> b -> Encoding
value b
v) (((a, b) -> ByteString) -> [(a, b)] -> [(a, b)]
forall a. (a -> ByteString) -> [a] -> [a]
ordered (a -> ByteString
key (a -> ByteString) -> ((a, b) -> a) -> (a, b) -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (a, b) -> a
forall a b. (a, b) -> a
fst) [(a, b)]
pairs)

ordered :: (a -> ByteString) -> [a] -> [a]
ordered :: forall a. (a -> ByteString) -> [a] -> [a]
ordered a -> ByteString
bytes = (a -> (Int, ByteString)) -> [a] -> [a]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (\a
value -> let key :: ByteString
key = a -> ByteString
bytes a
value in (ByteString -> Int
B.length ByteString
key, ByteString
key))

checked :: (ByteString -> Either Error a) -> D.Decoder s a
checked :: forall a s. (ByteString -> Either Error a) -> Decoder s a
checked ByteString -> Either Error a
constructor = do
  Term
term <- Decoder s Term
forall s. Decoder s Term
T.decodeTerm
  ByteString
bytes <- case Term
term of
    T.TBytes ByteString
value -> ByteString -> Decoder s ByteString
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
value
    T.TBytesI ByteString
value -> ByteString -> Decoder s ByteString
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ByteString -> ByteString
L.toStrict ByteString
value)
    Term
_ -> String -> Decoder s ByteString
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"Expected byte string"
  (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
constructor ByteString
bytes)