-- 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.

-- | Staking reward accounts, distinct from payment addresses.
--
-- @
-- import qualified Cometa.Address.Reward as Reward
-- import qualified Cometa.Credential as Credential
-- import qualified Cometa.NetworkId as Network
--
-- rewardAccount :: Credential.Credential Credential.Stake -> Reward.RewardAddress
-- rewardAccount = Reward.fromCredential Network.testnet
-- @
module Cometa.Address.Reward
  ( RewardAddress,
    fromCredential,
    networkId,
    credential,
    fromBytes,
    toBytes,
    fromText,
    toText,
  )
where

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

import Cometa.Credential (Credential (..), Stake)
import qualified Cometa.Credential as Credential
import Cometa.Error (Error (..))
import qualified Cometa.Internal.AddressText as AddressText
import Cometa.NetworkId (NetworkId)
import qualified Cometa.NetworkId as Network
import Data.Bits (shiftL, shiftR, (.&.), (.|.))
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import Data.Text (Text)

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

-- | An immutable reward account. Equality and ordering compare network then
-- credential (key before script, then hash bytes); 'Show' is diagnostic.
data RewardAddress = RewardAddress !NetworkId !(Credential Stake)
  deriving (RewardAddress -> RewardAddress -> Bool
(RewardAddress -> RewardAddress -> Bool)
-> (RewardAddress -> RewardAddress -> Bool) -> Eq RewardAddress
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: RewardAddress -> RewardAddress -> Bool
== :: RewardAddress -> RewardAddress -> Bool
$c/= :: RewardAddress -> RewardAddress -> Bool
/= :: RewardAddress -> RewardAddress -> Bool
Eq, Eq RewardAddress
Eq RewardAddress =>
(RewardAddress -> RewardAddress -> Ordering)
-> (RewardAddress -> RewardAddress -> Bool)
-> (RewardAddress -> RewardAddress -> Bool)
-> (RewardAddress -> RewardAddress -> Bool)
-> (RewardAddress -> RewardAddress -> Bool)
-> (RewardAddress -> RewardAddress -> RewardAddress)
-> (RewardAddress -> RewardAddress -> RewardAddress)
-> Ord RewardAddress
RewardAddress -> RewardAddress -> Bool
RewardAddress -> RewardAddress -> Ordering
RewardAddress -> RewardAddress -> RewardAddress
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: RewardAddress -> RewardAddress -> Ordering
compare :: RewardAddress -> RewardAddress -> Ordering
$c< :: RewardAddress -> RewardAddress -> Bool
< :: RewardAddress -> RewardAddress -> Bool
$c<= :: RewardAddress -> RewardAddress -> Bool
<= :: RewardAddress -> RewardAddress -> Bool
$c> :: RewardAddress -> RewardAddress -> Bool
> :: RewardAddress -> RewardAddress -> Bool
$c>= :: RewardAddress -> RewardAddress -> Bool
>= :: RewardAddress -> RewardAddress -> Bool
$cmax :: RewardAddress -> RewardAddress -> RewardAddress
max :: RewardAddress -> RewardAddress -> RewardAddress
$cmin :: RewardAddress -> RewardAddress -> RewardAddress
min :: RewardAddress -> RewardAddress -> RewardAddress
Ord, Int -> RewardAddress -> ShowS
[RewardAddress] -> ShowS
RewardAddress -> String
(Int -> RewardAddress -> ShowS)
-> (RewardAddress -> String)
-> ([RewardAddress] -> ShowS)
-> Show RewardAddress
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> RewardAddress -> ShowS
showsPrec :: Int -> RewardAddress -> ShowS
$cshow :: RewardAddress -> String
show :: RewardAddress -> String
$cshowList :: [RewardAddress] -> ShowS
showList :: [RewardAddress] -> ShowS
Show)

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

-- | Assemble a reward account from its network and staking authority.
fromCredential :: NetworkId -> Credential Stake -> RewardAddress
fromCredential :: NetworkId -> Credential Stake -> RewardAddress
fromCredential = NetworkId -> Credential Stake -> RewardAddress
RewardAddress

-- | Four-bit network tag carried by the header.
networkId :: RewardAddress -> NetworkId
networkId :: RewardAddress -> NetworkId
networkId (RewardAddress NetworkId
network Credential Stake
_) = NetworkId
network

-- | Staking authority controlling the rewards.
credential :: RewardAddress -> Credential Stake
credential :: RewardAddress -> Credential Stake
credential (RewardAddress NetworkId
_ Credential Stake
value) = Credential Stake
value

-- | Exact 29-byte header and credential encoding.
toBytes :: RewardAddress -> ByteString
toBytes :: RewardAddress -> ByteString
toBytes (RewardAddress NetworkId
network Credential Stake
value) = case Credential Stake
value of
  KeyCredential KeyHash Stake
hash -> Word8 -> ByteString -> ByteString
encode Word8
14 (KeyHash Stake -> ByteString
forall purpose. KeyHash purpose -> ByteString
Credential.keyHashBytes KeyHash Stake
hash)
  ScriptCredential ScriptHash
hash -> Word8 -> ByteString -> ByteString
encode Word8
15 (ScriptHash -> ByteString
Credential.scriptHashBytes ScriptHash
hash)
  where
    encode :: Word8 -> ByteString -> ByteString
encode Word8
tag = Word8 -> ByteString -> ByteString
ByteString.cons ((Word8
tag Word8 -> Int -> Word8
forall a. Bits a => a -> Int -> a
`shiftL` Int
4) Word8 -> Word8 -> Word8
forall a. Bits a => a -> a -> a
.|. NetworkId -> Word8
Network.networkIdValue NetworkId
network)

-- | Import exact reward-account bytes. Non-reward headers return
-- 'UnsupportedAddressType'; empty input or incorrect exact lengths return
-- 'InvalidShelleyAddress'. All four-bit network tags are retained.
fromBytes :: ByteString -> Either Error RewardAddress
fromBytes :: ByteString -> Either Error RewardAddress
fromBytes ByteString
bytes = case ByteString -> Maybe (Word8, ByteString)
ByteString.uncons ByteString
bytes of
  Maybe (Word8, ByteString)
Nothing -> Error -> Either Error RewardAddress
forall a b. a -> Either a b
Left Error
InvalidShelleyAddress
  Just (Word8
header, ByteString
payload) -> do
    let tag :: Word8
tag = Word8
header Word8 -> Int -> Word8
forall a. Bits a => a -> Int -> a
`shiftR` Int
4
    if Word8
tag Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
/= Word8
14 Bool -> Bool -> Bool
&& Word8
tag Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
/= Word8
15
      then Error -> Either Error RewardAddress
forall a b. a -> Either a b
Left (Word8 -> Error
UnsupportedAddressType Word8
tag)
      else
        if ByteString -> Int
ByteString.length ByteString
payload Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
28
          then Error -> Either Error RewardAddress
forall a b. a -> Either a b
Left Error
InvalidShelleyAddress
          else do
            NetworkId
network <- Integer -> Either Error NetworkId
Network.mkNetworkId (Word8 -> Integer
forall a. Integral a => a -> Integer
toInteger (Word8
header Word8 -> Word8 -> Word8
forall a. Bits a => a -> a -> a
.&. Word8
15))
            Credential Stake
authority <-
              if Word8
tag Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
== Word8
14
                then KeyHash Stake -> Credential Stake
forall purpose. KeyHash purpose -> Credential purpose
KeyCredential (KeyHash Stake -> Credential Stake)
-> Either Error (KeyHash Stake) -> Either Error (Credential Stake)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either Error (KeyHash Stake)
forall purpose. ByteString -> Either Error (KeyHash purpose)
Credential.keyHashFromBytes ByteString
payload
                else ScriptHash -> Credential Stake
forall purpose. ScriptHash -> Credential purpose
ScriptCredential (ScriptHash -> Credential Stake)
-> Either Error ScriptHash -> Either Error (Credential Stake)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either Error ScriptHash
Credential.scriptHashFromBytes ByteString
payload
            RewardAddress -> Either Error RewardAddress
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (NetworkId -> Credential Stake -> RewardAddress
RewardAddress NetworkId
network Credential Stake
authority)

-- | Encode canonical lowercase Bech32, with @stake@ for tag 1 and
-- @stake_test@ for other tags.
toText :: RewardAddress -> Text
toText :: RewardAddress -> Text
toText RewardAddress
address = Bool -> Bool -> ByteString -> Text
AddressText.toText Bool
True (RewardAddress -> NetworkId
networkId RewardAddress
address NetworkId -> NetworkId -> Bool
forall a. Eq a => a -> a -> Bool
== NetworkId
Network.mainnet) (RewardAddress -> ByteString
toBytes RewardAddress
address)

-- | Parse lowercase or all-uppercase Bech32. Mixed case, non-ASCII, empty,
-- overlong (more than 120 characters), or mismatched network/form prefixes
-- return 'InvalidShelleyAddressText'. Malformed encoding or checksum returns
-- 'InvalidShelleyAddressText'; non-reward headers return 'UnsupportedAddressType';
-- incorrect exact lengths return 'InvalidShelleyAddress'.
fromText :: Text -> Either Error RewardAddress
fromText :: Text -> Either Error RewardAddress
fromText = (ByteString -> Either Error RewardAddress)
-> (RewardAddress -> Text) -> Text -> Either Error RewardAddress
forall address.
(ByteString -> Either Error address)
-> (address -> Text) -> Text -> Either Error address
AddressText.fromText ByteString -> Either Error RewardAddress
fromBytes RewardAddress -> Text
toText