{-# LANGUAGE LambdaCase #-}

{- |
Module      : Singular.Registry.Address
Description : A registry's address: its state token as one bech32 word
License     : Apache-2.0

A registry has an address. It is the registry's state token written as one
bech32 word: the prefix names the network, and the body is the 28-byte policy
followed by the 32-byte asset name, nothing else. The policy is the version
of the on-chain code, and the name comes from the seed, so the word holds
what a command needs to find the registry and the network to look for it on.

The checksum is the original bech32 one, with no limit on the length of the
word. The word is written in lower case and read in lower case or in upper
case, never in a mixture.

An address is read in a fixed order and each refusal says which cause it is:
not a bech32 word, the checksum, the prefix, the length of the body. A word
that fails an earlier check is never told a later cause.

The fingerprint is the CIP-14 fingerprint of the same asset, the short name
that wallets and explorers print for it: the 160-bit blake2b of the policy
followed by the name, written in bech32 under the prefix @asset@.
-}
module Singular.Registry.Address
    ( -- * The networks that have an address
      addressPrefix
    , addressPrefixes

      -- * Writing an address
    , renderRegistryAddress

      -- * Reading an address
    , AddressRefusal (..)
    , parseRegistryAddress
    , renderAddressRefusal

      -- * The fingerprint
    , registryFingerprint
    ) where

import Codec.Binary.Bech32 qualified as Bech32
import Control.Monad (unless, when)
import Crypto.Hash (Blake2b_160 (..), hashWith)
import Data.Bifunctor (first)
import Data.ByteArray qualified as BA
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.ByteString.Base16 qualified as B16
import Data.ByteString.Short qualified as SBS
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Encoding qualified as TE
import Data.Word (Word32)

import Cardano.Ledger.Mary.Value (AssetName (..), PolicyID (..))

import Singular.Registry.LedgerProvider (Asset)
import Singular.Registry.StateToken (parseStateToken)
import Singular.Registry.TxBuilder.Internal (scriptHashBytes)

{- | The prefix of a network, for the four networks that have one: mainnet,
preprod, preview and the generated development network. Any other network
magic has no prefix, and so no address.
-}
addressPrefix :: Word32 -> Maybe Text
addressPrefix :: Word32 -> Maybe Text
addressPrefix Word32
magic = Word32 -> [(Word32, Text)] -> Maybe Text
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Word32
magic [(Word32
m, Text
p) | (Text
p, Word32
m) <- [(Text, Word32)]
addressPrefixes]

-- | The four prefixes with the network magic each names, in the order they are listed.
addressPrefixes :: [(Text, Word32)]
addressPrefixes :: [(Text, Word32)]
addressPrefixes =
    [ (Text
"singular", Word32
764_824_073)
    , (Text
"singular_preprod", Word32
1)
    , (Text
"singular_preview", Word32
2)
    , (Text
"singular_devnet", Word32
42)
    ]

{- | The address of a state token on a network, in lower case; nothing when
the network has no prefix.
-}
renderRegistryAddress :: Word32 -> Asset -> Maybe Text
renderRegistryAddress :: Word32 -> Asset -> Maybe Text
renderRegistryAddress Word32
magic Asset
token = do
    prefix <- Word32 -> Maybe Text
addressPrefix Word32
magic
    hrp <-
        either (const Nothing) Just (Bech32.humanReadablePartFromText prefix)
    pure
        (Bech32.encodeLenient hrp (Bech32.dataPartFromBytes (tokenBytes token)))

-- | Why a text is not the address of a registry, in the order the causes are checked.
data AddressRefusal
    = -- | Not a bech32 word, or upper and lower case mixed
      NotAnAddress
    | -- | The checksum does not match: a character is mistyped
      BadChecksum
    | -- | The prefix is none of the four
      UnknownPrefix Text
    | -- | The body is this many bytes, not 60
      BodyLength Int
    | -- | The body is not a whole number of bytes: this many characters
      BodyNotBytes Int
    deriving stock (AddressRefusal -> AddressRefusal -> Bool
(AddressRefusal -> AddressRefusal -> Bool)
-> (AddressRefusal -> AddressRefusal -> Bool) -> Eq AddressRefusal
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: AddressRefusal -> AddressRefusal -> Bool
== :: AddressRefusal -> AddressRefusal -> Bool
$c/= :: AddressRefusal -> AddressRefusal -> Bool
/= :: AddressRefusal -> AddressRefusal -> Bool
Eq, Int -> AddressRefusal -> ShowS
[AddressRefusal] -> ShowS
AddressRefusal -> [Char]
(Int -> AddressRefusal -> ShowS)
-> (AddressRefusal -> [Char])
-> ([AddressRefusal] -> ShowS)
-> Show AddressRefusal
forall a.
(Int -> a -> ShowS) -> (a -> [Char]) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> AddressRefusal -> ShowS
showsPrec :: Int -> AddressRefusal -> ShowS
$cshow :: AddressRefusal -> [Char]
show :: AddressRefusal -> [Char]
$cshowList :: [AddressRefusal] -> ShowS
showList :: [AddressRefusal] -> ShowS
Show)

{- | Read an address: the network magic its prefix names and the state token
its body spells. The causes are checked in a fixed order, and the first that
fails is the one reported.
-}
parseRegistryAddress :: Text -> Either AddressRefusal (Word32, Asset)
parseRegistryAddress :: Text -> Either AddressRefusal (Word32, Asset)
parseRegistryAddress Text
word = do
    Bool -> Either AddressRefusal () -> Either AddressRefusal ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Text -> Bool
wellFormed Text
word) (AddressRefusal -> Either AddressRefusal ()
forall a b. a -> Either a b
Left AddressRefusal
NotAnAddress)
    (hrp, dataPart) <-
        (DecodingError -> AddressRefusal)
-> Either DecodingError (HumanReadablePart, DataPart)
-> Either AddressRefusal (HumanReadablePart, DataPart)
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first (AddressRefusal -> DecodingError -> AddressRefusal
forall a b. a -> b -> a
const AddressRefusal
BadChecksum) (Text -> Either DecodingError (HumanReadablePart, DataPart)
Bech32.decodeLenient (Text -> Text
T.toLower Text
word))
    let prefix = HumanReadablePart -> Text
Bech32.humanReadablePartToText HumanReadablePart
hrp
    magic <-
        maybe
            (Left (UnknownPrefix prefix))
            Right
            (lookup prefix addressPrefixes)
    body <-
        maybe
            (Left (BodyNotBytes (T.length (Bech32.dataPartToText dataPart))))
            Right
            (Bech32.dataPartToBytes dataPart)
    when (BS.length body /= 60) (Left (BodyLength (BS.length body)))
    -- sixty bytes always split into a policy of 28 and a name of 32
    token <-
        first
            (const (BodyLength (BS.length body)))
            (parseStateToken (spelling body))
    pure (magic, token)
  where
    spelling :: ByteString -> Text
spelling ByteString
body =
        ByteString -> Text
hexText (Int -> ByteString -> ByteString
BS.take Int
28 ByteString
body) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"." Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> ByteString -> Text
hexText (Int -> ByteString -> ByteString
BS.drop Int
28 ByteString
body)

{- | The word is a bech32 word of one case: a prefix of printable characters,
the separator, and a data part of the bech32 alphabet at least as long as a
checksum. This is the first cause; the package's own decoder reports a wrong
character and a wrong checksum the same way, so it is told apart here.
-}
wellFormed :: Text -> Bool
wellFormed :: Text -> Bool
wellFormed Text
word =
    Bool -> Bool
not Bool
mixedCase
        Bool -> Bool -> Bool
&& Bool -> Bool
not (Text -> Bool
T.null Text
separated)
        Bool -> Bool -> Bool
&& Bool
prefixOk
        Bool -> Bool -> Bool
&& (Char -> Bool) -> Text -> Bool
T.all (Char -> [Char] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Char]
Bech32.dataCharList) Text
payload
        Bool -> Bool -> Bool
&& Text -> Int
T.length Text
payload Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
6
  where
    lowered :: Text
lowered = Text -> Text
T.toLower Text
word
    mixedCase :: Bool
mixedCase = Text -> Text
T.toUpper Text
word Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
/= Text
word Bool -> Bool -> Bool
&& Text
lowered Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
/= Text
word
    (Text
separated, Text
payload) = HasCallStack => Text -> Text -> (Text, Text)
Text -> Text -> (Text, Text)
T.breakOnEnd (Char -> Text
T.singleton Char
Bech32.separatorChar) Text
lowered
    prefixOk :: Bool
prefixOk =
        (HumanReadablePartError -> Bool)
-> (HumanReadablePart -> Bool)
-> Either HumanReadablePartError HumanReadablePart
-> Bool
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Bool -> HumanReadablePartError -> Bool
forall a b. a -> b -> a
const Bool
False) (Bool -> HumanReadablePart -> Bool
forall a b. a -> b -> a
const Bool
True) (Either HumanReadablePartError HumanReadablePart -> Bool)
-> Either HumanReadablePartError HumanReadablePart -> Bool
forall a b. (a -> b) -> a -> b
$
            Text -> Either HumanReadablePartError HumanReadablePart
Bech32.humanReadablePartFromText (Int -> Text -> Text
T.dropEnd Int
1 Text
separated)

{- | What a refusal says, as the rest of a sentence about the value:
the cause, and nothing of any other cause.
-}
renderAddressRefusal :: AddressRefusal -> Text
renderAddressRefusal :: AddressRefusal -> Text
renderAddressRefusal = \case
    AddressRefusal
NotAnAddress ->
        Text
"is not an address: it is not one bech32 word, in lower case or in upper case"
    AddressRefusal
BadChecksum ->
        Text
"has a wrong checksum: a character of the address is mistyped"
    UnknownPrefix Text
prefix ->
        Text
"has an unknown prefix "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
prefix
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": the prefixes are "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> [Text] -> Text
T.intercalate Text
", " (((Text, Word32) -> Text) -> [(Text, Word32)] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text, Word32) -> Text
forall a b. (a, b) -> a
fst ([(Text, Word32)] -> [(Text, Word32)]
forall a. HasCallStack => [a] -> [a]
init [(Text, Word32)]
addressPrefixes))
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" and "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> (Text, Word32) -> Text
forall a b. (a, b) -> a
fst ([(Text, Word32)] -> (Text, Word32)
forall a. HasCallStack => [a] -> a
last [(Text, Word32)]
addressPrefixes)
    BodyLength Int
n ->
        Text
"has a body of " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> [Char] -> Text
T.pack (Int -> [Char]
forall a. Show a => a -> [Char]
show Int
n) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" bytes, not 60"
    BodyNotBytes Int
n ->
        Text
"has a body of "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> [Char] -> Text
T.pack (Int -> [Char]
forall a. Show a => a -> [Char]
show Int
n)
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" characters that is not whole bytes, not 60 bytes"

{- | The CIP-14 fingerprint of a state token: the 160-bit blake2b of its policy
followed by its name, in bech32 under the prefix @asset@.
-}
registryFingerprint :: Asset -> Text
registryFingerprint :: Asset -> Text
registryFingerprint Asset
token =
    HumanReadablePart -> DataPart -> Text
Bech32.encodeLenient
        HumanReadablePart
assetPrefix
        ( ByteString -> DataPart
Bech32.dataPartFromBytes
            (Digest Blake2b_160 -> ByteString
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
bin -> bout
BA.convert (Blake2b_160 -> ByteString -> Digest Blake2b_160
forall ba alg.
(ByteArrayAccess ba, HashAlgorithm alg) =>
alg -> ba -> Digest alg
hashWith Blake2b_160
Blake2b_160 (Asset -> ByteString
tokenBytes Asset
token)))
        )

-- | The prefix of a CIP-14 fingerprint.
assetPrefix :: Bech32.HumanReadablePart
assetPrefix :: HumanReadablePart
assetPrefix =
    (HumanReadablePartError -> HumanReadablePart)
-> (HumanReadablePart -> HumanReadablePart)
-> Either HumanReadablePartError HumanReadablePart
-> HumanReadablePart
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either
        ( \HumanReadablePartError
why ->
            [Char] -> HumanReadablePart
forall a. HasCallStack => [Char] -> a
error ([Char]
"Singular.Registry.Address: the prefix asset: " [Char] -> ShowS
forall a. Semigroup a => a -> a -> a
<> HumanReadablePartError -> [Char]
forall a. Show a => a -> [Char]
show HumanReadablePartError
why)
        )
        HumanReadablePart -> HumanReadablePart
forall a. a -> a
id
        (Text -> Either HumanReadablePartError HumanReadablePart
Bech32.humanReadablePartFromText Text
"asset")

-- | The 60 bytes a state token is: its policy, then its name.
tokenBytes :: Asset -> ByteString
tokenBytes :: Asset -> ByteString
tokenBytes (PolicyID ScriptHash
policy, AssetName ShortByteString
name) =
    ScriptHash -> ByteString
scriptHashBytes ScriptHash
policy ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ShortByteString -> ByteString
SBS.fromShort ShortByteString
name

hexText :: ByteString -> Text
hexText :: ByteString -> Text
hexText = ByteString -> Text
TE.decodeUtf8 (ByteString -> Text)
-> (ByteString -> ByteString) -> ByteString -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> ByteString
B16.encode