packages feed

cometa-0.2.0.0: test/CompleteAddress.hs

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

-- | Complete address-family fixtures, boundaries and native reconstruction.
module CompleteAddress (tests) where

import qualified Cometa.Address as Address
import qualified Cometa.Address.Byron as Byron
import qualified Cometa.Address.Reward as Reward
import qualified Cometa.Address.Shelley as Shelley
import qualified Cometa.Credential as Credential
import Cometa.Error (Error (..))
import qualified Cometa.Internal.Hex as Hex
import Control.Monad (forM_, replicateM_)
import Data.Bits (xor)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Either (isLeft)
import Data.Int (Int64)
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import Data.Word (Word32, Word64, Word8)
import Foreign.C.Types (CInt (..), CSize (..), CUInt (..))
import Foreign.Ptr (Ptr, castPtr)
import Hedgehog (Property, evalEither, evalIO, forAll, property, (===))
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))
import Test.Tasty.Hedgehog (testProperty)

tests :: TestTree
tests =
  testGroup
    "Complete addresses"
    [ testCase "Byron types, payload64 and magicInt64 boundaries reconstruct natively" checkByron,
      testCase "pointer key/script networks and uint32 boundaries reconstruct natively" checkPointer,
      testCase "CIP19 Byron and pointer fixtures match typed public assembly" checkPinned,
      testCase "generic address family dispatch preserves exact bytes and text" checkGeneric,
      testCase "Byron nonminimal and indefinite framing retains exact bytes" checkExact,
      testCase "Byron CRC/CBOR/attributes/Base58 and pointer invalid forms reject" checkInvalid,
      testCase "repeated native getter reconstruction releases every owner" (replicateM_ 50 (checkByron >> checkPointer)),
      testCase "standalone credential CBOR checks kinds, lengths and framing" credentialCbor,
      testProperty "generated Byron attributes and kinds reconstruct natively" propByron,
      testProperty "generated pointer components reconstruct natively" propPointer
    ]

byron :: Word8 -> Byron.AddressType -> Maybe ByteString -> Maybe Word64 -> Either Error Byron.Address
byron seed kind payload magic = do
  root <- Byron.rootFromBytes (B.replicate 28 seed)
  attrs <- Byron.attributes payload magic
  pure (Byron.address root attrs kind)

pointer :: Word8 -> Integer -> Bool -> Word32 -> Word32 -> Word32 -> Either Error Shelley.Address
pointer seed network script slot tx cert = do
  net <- Shelley.mkNetworkId network
  credential <-
    if script
      then Credential.ScriptCredential <$> Credential.scriptHashFromBytes (B.replicate 28 seed)
      else Credential.KeyCredential <$> Credential.keyHashFromBytes (B.replicate 28 seed)
  pure (Shelley.pointer net credential (Shelley.StakePointer slot tx cert))

checkByron :: IO ()
checkByron = forM_ [minBound .. maxBound] $ \kind ->
  forM_ [Nothing, Just B.empty, Just (B.replicate 64 7)] $ \payload ->
    forM_ [Nothing, Just 0, Just 42, Just (fromIntegral (maxBound :: Int64))] $ \magic -> do
      value <- require (byron 3 kind payload magic)
      Byron.fromBytes (Byron.toBytes value) @?= Right value
      Byron.fromText (Byron.toText value) @?= Right value
      native 0 (Byron.toBytes value) (Byron.toText value) >>= assertBool "native Byron agrees"

checkPointer :: IO ()
checkPointer = forM_ [0 .. 15] $ \network ->
  forM_ [False, True] $ \script ->
    forM_ [0, 127, 128, 16383, 16384, maxBound] $ \component -> do
      value <- require (pointer 9 network script component component component)
      Shelley.fromBytes (Shelley.toBytes value) @?= Right value
      Shelley.fromText (Shelley.toText value) @?= Right value
      native 1 (Shelley.toBytes value) (Shelley.toText value) >>= assertBool "native pointer agrees"

checkPinned :: IO ()
checkPinned = do
  digest <- require (hexBytes "ba970ad36654d8dd8f74274b733452ddeab9a62a397746be3c42ccdd" >>= Byron.rootFromBytes)
  attrs <- require (Byron.attributes Nothing Nothing)
  let value = Byron.address digest attrs Byron.PublicKey
  Byron.toText value @?= "Ae2tdPwUPEZFRbyhz3cpfC2CumGzNkFBN2L42rcUc2yjQpEkxDbkPodpMAi"
  forM_ ["addr1gx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer5pnz75xxcrzqf96k", "addr128phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtupnz75xxcrtw79hu"] $ \text -> do
    decoded <- require (Shelley.fromText text)
    location <- case Shelley.pointerRef decoded of
      Nothing -> assertFailure "expected pointer" >> fail "unreachable"
      Just result -> pure result
    let rebuilt = Shelley.pointer (Shelley.networkId decoded) (Shelley.paymentCredential decoded) location
    Shelley.toText rebuilt @?= text
    native 1 (Shelley.toBytes rebuilt) text >>= assertBool "CIP19 pointer native reconstruction"

checkGeneric :: IO ()
checkGeneric = do
  bootstrap <- require (byron 1 Byron.Redeem Nothing (Just 42))
  payment <- require (pointer 2 15 True 128 0 maxBound)
  stake <- require (Credential.keyHashFromBytes (B.replicate 28 3))
  let reward = Reward.fromCredential Shelley.testnet (Credential.KeyCredential stake)
      values = [Address.ByronAddress bootstrap, Address.ShelleyAddress payment, Address.RewardAddress reward]
  forM_ values $ \value -> do
    Address.fromBytes (Address.toBytes value) @?= Right value
    Address.fromText (Address.toText value) @?= Right value

checkExact :: IO ()
checkExact = do
  value <- require (byron 1 Byron.PublicKey Nothing Nothing)
  let bytes = Byron.toBytes value
      nonminimal = B.pack [0x98, 2] <> B.drop 1 bytes
      indefinite = B.singleton 0x9f <> B.drop 1 bytes <> B.singleton 0xff
  forM_ [nonminimal, indefinite] $ \encoded -> do
    decoded <- require (Byron.fromBytes encoded)
    Byron.toBytes decoded @?= encoded
    Byron.root decoded @?= Byron.root value
    Byron.addressAttributes decoded @?= Byron.addressAttributes value
    Byron.fromText (Byron.toText decoded) @?= Right decoded

checkInvalid :: IO ()
checkInvalid = do
  forM_ malformedByron $ \hex -> do
    bytes <- require (hexBytes hex)
    assertBool "invalid Byron payload rejected" (isLeft (Byron.fromBytes bytes))
  value <- require (byron 0 Byron.PublicKey Nothing Nothing)
  let bytes = Byron.toBytes value
  assertBool "CRC mismatch" (isLeft (Byron.fromBytes (B.init bytes <> B.singleton (B.last bytes `xor` 1))))
  assertBool "trailing Byron bytes" (isLeft (Byron.fromBytes (bytes <> B.singleton 0)))
  forM_ ["", "0", "O", "I", "l", " Ae2td", Text.replicate 513 "1"] $ \text -> assertBool "invalid Base58" (isLeft (Byron.fromText text))
  assertBool "root length" (isLeft (Byron.rootFromBytes (B.replicate 27 0)))
  assertBool "path payload65" (isLeft (Byron.attributes (Just (B.replicate 65 0)) Nothing))
  assertBool "magic aboveInt64" (isLeft (Byron.attributes Nothing (Just maxBound)))
  let header = B.singleton 0x40 <> B.replicate 28 0
  forM_ [B.empty, B.pack [0, 0], B.pack [0, 0, 0, 0], B.pack [0x80, 0, 0, 0], B.pack [0x90, 0x80, 0x80, 0x80, 0, 0, 0], B.replicate 6 0xff] $ \payload ->
    assertBool "invalid/truncated/nonminimal/overflow pointer" (isLeft (Shelley.fromBytes (header <> payload)))
  forM_ [0, 1] $ \kind -> native kind (B.singleton 0) "" >>= (@?= False)

propByron :: Property
propByron = property $ do
  seed <- forAll (Gen.word8 Range.constantBounded)
  kind <- forAll Gen.enumBounded
  payload <- forAll (Gen.maybe (Gen.bytes (Range.linear 0 64)))
  magic <- forAll (Gen.maybe (Gen.word64 (Range.linear 0 (fromIntegral (maxBound :: Int64)))))
  value <- evalEither (byron seed kind payload magic)
  parsed <- evalEither (Byron.fromBytes (Byron.toBytes value))
  parsed === value
  agreement <- evalIO (native 0 (Byron.toBytes value) (Byron.toText value))
  agreement === True

propPointer :: Property
propPointer = property $ do
  seed <- forAll (Gen.word8 Range.constantBounded)
  network <- forAll (Gen.integral (Range.linear 0 15))
  script <- forAll Gen.bool
  slot <- forAll (Gen.word32 Range.constantBounded)
  tx <- forAll (Gen.word32 Range.constantBounded)
  cert <- forAll (Gen.word32 Range.constantBounded)
  value <- evalEither (pointer seed network script slot tx cert)
  parsed <- evalEither (Shelley.fromBytes (Shelley.toBytes value))
  parsed === value
  agreement <- evalIO (native 1 (Shelley.toBytes value) (Shelley.toText value))
  agreement === True

hexBytes :: Text -> Either Error ByteString
hexBytes = maybe (Left InvalidHex) Right . Hex.decodeHex

require :: Either Error a -> IO a
require value = case value of
  Left failure -> assertFailure (show failure) >> fail "unreachable"
  Right result -> pure result

native :: CUInt -> ByteString -> Text -> IO Bool
native kind bytes text = B.useAsCStringLen bytes $ \(input, size) ->
  B.useAsCStringLen (Text.encodeUtf8 text) $ \(rendered, textSize) ->
    (/= 0) <$> cAgree kind (castPtr input) (fromIntegral size) (castPtr rendered) (fromIntegral textSize)

foreign import ccall unsafe "cometa_test_complete_address_agree"
  cAgree :: CUInt -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> IO CInt

-- CIP19 constants above are imported from cardano-c pin
-- eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1,
-- lib/tests/address/cip19_test_vectors.h (Apache-2.0).
-- Invalid payload fixtures below were independently generated with Python zlib
-- CRC32, so failures reach inner semantic validation after a valid outer CRC.
malformedByron :: [Text]
malformedByron =
  [ "82d818582083581b000000000000000000000000000000000000000000000000000000a0001a0ebb62f2",
    "82d818582183581c00000000000000000000000000000000000000000000000000000000a0031a477eeddb",
    "82d818582483581c00000000000000000000000000000000000000000000000000000000a1034100001a6ec81c59",
    "82d818582783581c00000000000000000000000000000000000000000000000000000000a2024100024100001a1c4df8b7",
    "82d818586783581c00000000000000000000000000000000000000000000000000000000a101584358410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001a789e6cea",
    "82d818582c83581c00000000000000000000000000000000000000000000000000000000a102491b8000000000000000001accf143b1",
    "82d818582583581c00000000000000000000000000000000000000000000000000000000a102420000001aef0e489f",
    "82d818582283581c00000000000000000000000000000000000000000000000000000000a000001ae869c9ff"
  ]

credentialCbor :: IO ()
credentialCbor = do
  key <- require (Credential.keyHashFromBytes (B.replicate 28 7))
  script <- require (Credential.scriptHashFromBytes (B.replicate 28 8))
  forM_ [Credential.KeyCredential key, Credential.ScriptCredential script] $ \credential -> do
    let encoded = Credential.encodeCbor credential
    (Credential.decodeCbor encoded :: Either Error (Credential.Credential Credential.Payment)) @?= Right credential
    (Credential.decodeCbor (B.singleton 0x9f <> B.drop 1 encoded <> B.singleton 0xff) :: Either Error (Credential.Credential Credential.Payment)) @?= Right credential
  forM_ [B.empty, B.pack [0x82, 2, 0x58, 28] <> B.replicate 28 0, B.pack [0x82, 0, 0x41, 0], B.pack [0x82, 0, 0x58, 28] <> B.replicate 28 0 <> B.singleton 0] $ \bytes ->
    assertBool "invalid credential rejected" (isLeft (Credential.decodeCbor bytes :: Either Error (Credential.Credential Credential.Payment)))