-- | Peer ID derivation from public keys.
--
-- A Peer ID is a multihash of the serialized PublicKey protobuf message.
-- Ed25519 keys (36 bytes serialized) use identity multihash.
-- Larger keys (RSA) use SHA-256 multihash.
module LibP2P.Crypto.PeerId
  ( PeerId (..)
  , fromPublicKey
  , toBase58
  , fromBase58
  , peerIdBytes
  , parsePeerId
  , toCIDv1
  ) where

import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base58 as B58
import Data.ByteArray.Encoding (Base (Base32), convertFromBase, convertToBase)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.Word (Word8, Word64)
import LibP2P.Core.Multihash (HashFunction (..), encodeMultihash, validateMultihash)
import LibP2P.Core.Varint (encodeUvarint, decodeUvarint)
import LibP2P.Crypto.Key (PublicKey)
import LibP2P.Crypto.Protobuf (encodePublicKey)

-- | A Peer ID is a multihash of the serialized public key.
newtype PeerId = PeerId ByteString
  deriving (Int -> PeerId -> ShowS
[PeerId] -> ShowS
PeerId -> String
(Int -> PeerId -> ShowS)
-> (PeerId -> String) -> ([PeerId] -> ShowS) -> Show PeerId
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PeerId -> ShowS
showsPrec :: Int -> PeerId -> ShowS
$cshow :: PeerId -> String
show :: PeerId -> String
$cshowList :: [PeerId] -> ShowS
showList :: [PeerId] -> ShowS
Show, PeerId -> PeerId -> Bool
(PeerId -> PeerId -> Bool)
-> (PeerId -> PeerId -> Bool) -> Eq PeerId
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PeerId -> PeerId -> Bool
== :: PeerId -> PeerId -> Bool
$c/= :: PeerId -> PeerId -> Bool
/= :: PeerId -> PeerId -> Bool
Eq, Eq PeerId
Eq PeerId =>
(PeerId -> PeerId -> Ordering)
-> (PeerId -> PeerId -> Bool)
-> (PeerId -> PeerId -> Bool)
-> (PeerId -> PeerId -> Bool)
-> (PeerId -> PeerId -> Bool)
-> (PeerId -> PeerId -> PeerId)
-> (PeerId -> PeerId -> PeerId)
-> Ord PeerId
PeerId -> PeerId -> Bool
PeerId -> PeerId -> Ordering
PeerId -> PeerId -> PeerId
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 :: PeerId -> PeerId -> Ordering
compare :: PeerId -> PeerId -> Ordering
$c< :: PeerId -> PeerId -> Bool
< :: PeerId -> PeerId -> Bool
$c<= :: PeerId -> PeerId -> Bool
<= :: PeerId -> PeerId -> Bool
$c> :: PeerId -> PeerId -> Bool
> :: PeerId -> PeerId -> Bool
$c>= :: PeerId -> PeerId -> Bool
>= :: PeerId -> PeerId -> Bool
$cmax :: PeerId -> PeerId -> PeerId
max :: PeerId -> PeerId -> PeerId
$cmin :: PeerId -> PeerId -> PeerId
min :: PeerId -> PeerId -> PeerId
Ord)

-- | Maximum serialized size for identity multihash.
maxInlineKeyLength :: Int
maxInlineKeyLength :: Int
maxInlineKeyLength = Int
42

-- | Derive a Peer ID from a public key.
fromPublicKey :: PublicKey -> PeerId
fromPublicKey :: PublicKey -> PeerId
fromPublicKey PublicKey
pk =
  let serialized :: ByteString
serialized = PublicKey -> ByteString
encodePublicKey PublicKey
pk
      mh :: ByteString
mh =
        if ByteString -> Int
BS.length ByteString
serialized Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
maxInlineKeyLength
          then HashFunction -> ByteString -> ByteString
encodeMultihash HashFunction
Identity ByteString
serialized
          else HashFunction -> ByteString -> ByteString
encodeMultihash HashFunction
SHA256 ByteString
serialized
   in ByteString -> PeerId
PeerId ByteString
mh

-- | Encode a Peer ID as base58btc text.
toBase58 :: PeerId -> Text
toBase58 :: PeerId -> Text
toBase58 (PeerId ByteString
bs) = ByteString -> Text
TE.decodeUtf8 (ByteString -> ByteString
B58.encode ByteString
bs)

-- | Decode a Peer ID from base58btc text.
-- Validates that decoded bytes are a well-formed multihash.
fromBase58 :: Text -> Either String PeerId
fromBase58 :: Text -> Either String PeerId
fromBase58 Text
t = case ByteString -> Maybe ByteString
B58.decode (Text -> ByteString
TE.encodeUtf8 Text
t) of
  Maybe ByteString
Nothing -> String -> Either String PeerId
forall a b. a -> Either a b
Left String
"fromBase58: invalid base58 encoding"
  Just ByteString
bs -> do
    _ <- ByteString -> Either String (HashFunction, ByteString)
validateMultihash ByteString
bs
    Right (PeerId bs)

-- | Get the raw multihash bytes of a Peer ID.
peerIdBytes :: PeerId -> ByteString
peerIdBytes :: PeerId -> ByteString
peerIdBytes (PeerId ByteString
bs) = ByteString
bs

-- | Parse a Peer ID from either a legacy base58btc multihash or CIDv1.
-- Legacy strings start with @1@ or @Qm@. CIDv1 strings use a supported
-- multibase prefix: @b@ (base32lower), @B@ (base32upper), or @z@ (base58btc).
parsePeerId :: Text -> Either String PeerId
parsePeerId :: Text -> Either String PeerId
parsePeerId Text
t
  | Text -> Bool
T.null Text
t = String -> Either String PeerId
forall a b. a -> Either a b
Left String
"parsePeerId: empty input"
  | Text
"1" Text -> Text -> Bool
`T.isPrefixOf` Text
t Bool -> Bool -> Bool
|| Text
"Qm" Text -> Text -> Bool
`T.isPrefixOf` Text
t = Text -> Either String PeerId
fromBase58 Text
t
  | HasCallStack => Text -> Char
Text -> Char
T.head Text
t Char -> String -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Char
'b', Char
'B', Char
'z'] = Text -> Either String PeerId
fromCIDv1 Text
t
  | Bool
otherwise = String -> Either String PeerId
forall a b. a -> Either a b
Left String
"parsePeerId: unsupported peer ID representation"

-- | Encode a Peer ID as CIDv1 text (base32lower, no padding).
-- Format: 'b' + base32lower(varint(1) + varint(0x72) + multihash_bytes)
toCIDv1 :: PeerId -> Text
toCIDv1 :: PeerId -> Text
toCIDv1 (PeerId ByteString
mhBytes) =
  let cidVersion :: ByteString
cidVersion = Word64 -> ByteString
encodeUvarint (Word64
1 :: Word64)
      codec :: ByteString
codec = Word64 -> ByteString
encodeUvarint (Word64
0x72 :: Word64)  -- libp2p-key
      cidBytes :: ByteString
cidBytes = ByteString
cidVersion ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
codec ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
mhBytes
      base32Upper :: ByteString
base32Upper = Base -> ByteString -> ByteString
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
Base -> bin -> bout
convertToBase Base
Base32 ByteString
cidBytes :: ByteString
      -- Strip padding '=' and convert to lowercase
      base32NoPad :: ByteString
base32NoPad = (Word8 -> Bool) -> ByteString -> ByteString
BS.filter (Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
/= Word8
0x3D) ByteString
base32Upper  -- 0x3D = '='
      base32Lower :: ByteString
base32Lower = (Word8 -> Word8) -> ByteString -> ByteString
BS.map (\Word8
w -> if Word8
w Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word8
0x41 Bool -> Bool -> Bool
&& Word8
w Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
<= Word8
0x5A then Word8
w Word8 -> Word8 -> Word8
forall a. Num a => a -> a -> a
+ Word8
32 else Word8
w) ByteString
base32NoPad
  in Text
"b" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> ByteString -> Text
TE.decodeUtf8 ByteString
base32Lower

-- | Decode a multibase-encoded CIDv1 Peer ID.
fromCIDv1 :: Text -> Either String PeerId
fromCIDv1 :: Text -> Either String PeerId
fromCIDv1 Text
t = do
  cidBytes <- Text -> Either String ByteString
decodeMultibase Text
t
  (version, rest1) <- decodeUvarint cidBytes
  if version /= (1 :: Word64)
    then Left $ "fromCIDv1: expected CID version 1, got " <> show version
    else do
      (codec, multihash) <- decodeUvarint rest1
      if codec /= (0x72 :: Word64)
        then Left $ "fromCIDv1: expected libp2p-key codec 0x72, got 0x" <> showHexW64 codec
        else do
          _ <- validateMultihash multihash
          Right (PeerId multihash)

-- | Decode the multibase encodings recognized for Peer ID CIDs.
decodeMultibase :: Text -> Either String ByteString
decodeMultibase :: Text -> Either String ByteString
decodeMultibase Text
t
  | Text -> Bool
T.null Text
t = String -> Either String ByteString
forall a b. a -> Either a b
Left String
"decodeMultibase: empty input"
  | Text -> Bool
T.null Text
payload = String -> Either String ByteString
forall a b. a -> Either a b
Left String
"decodeMultibase: empty payload"
  | Char
prefix Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'b' = Bool -> ByteString -> Either String ByteString
decodeBase32 Bool
True ByteString
payloadBytes
  | Char
prefix Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'B' = Bool -> ByteString -> Either String ByteString
decodeBase32 Bool
False ByteString
payloadBytes
  | Char
prefix Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'z' = ByteString -> Either String ByteString
decodeBase58Btc ByteString
payloadBytes
  | Bool
otherwise = String -> Either String ByteString
forall a b. a -> Either a b
Left String
"decodeMultibase: unsupported prefix"
  where
    prefix :: Char
prefix = HasCallStack => Text -> Char
Text -> Char
T.head Text
t
    payload :: Text
payload = HasCallStack => Text -> Text
Text -> Text
T.tail Text
t
    payloadBytes :: ByteString
payloadBytes = Text -> ByteString
TE.encodeUtf8 Text
payload

-- | Decode unpadded RFC 4648 base32 and require its canonical letter case.
decodeBase32 :: Bool -> ByteString -> Either String ByteString
decodeBase32 :: Bool -> ByteString -> Either String ByteString
decodeBase32 Bool
lowercase ByteString
encoded = do
  let upper :: ByteString
upper = (Word8 -> Word8) -> ByteString -> ByteString
BS.map Word8 -> Word8
asciiToUpper ByteString
encoded
      paddingLength :: Int
paddingLength = (Int
8 Int -> Int -> Int
forall a. Num a => a -> a -> a
- ByteString -> Int
BS.length ByteString
upper Int -> Int -> Int
forall a. Integral a => a -> a -> a
`mod` Int
8) Int -> Int -> Int
forall a. Integral a => a -> a -> a
`mod` Int
8
      padded :: ByteString
padded = ByteString
upper ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Int -> Word8 -> ByteString
BS.replicate Int
paddingLength Word8
0x3d
  decoded <- case Base -> ByteString -> Either String ByteString
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
Base -> bin -> Either String bout
convertFromBase Base
Base32 ByteString
padded of
    Left String
_ -> String -> Either String ByteString
forall a b. a -> Either a b
Left String
"decodeMultibase: invalid base32 encoding"
    Right ByteString
bytes -> ByteString -> Either String ByteString
forall a b. b -> Either a b
Right ByteString
bytes
  let canonicalUpper = (Word8 -> Bool) -> ByteString -> ByteString
BS.filter (Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
/= Word8
0x3d) (Base -> ByteString -> ByteString
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
Base -> bin -> bout
convertToBase Base
Base32 ByteString
decoded)
      canonical = if Bool
lowercase then (Word8 -> Word8) -> ByteString -> ByteString
BS.map Word8 -> Word8
asciiToLower ByteString
canonicalUpper else ByteString
canonicalUpper
  if canonical == encoded
    then Right decoded
    else Left "decodeMultibase: non-canonical base32 encoding"

-- | Decode canonical base58btc.
decodeBase58Btc :: ByteString -> Either String ByteString
decodeBase58Btc :: ByteString -> Either String ByteString
decodeBase58Btc ByteString
encoded = case ByteString -> Maybe ByteString
B58.decode ByteString
encoded of
  Maybe ByteString
Nothing -> String -> Either String ByteString
forall a b. a -> Either a b
Left String
"decodeMultibase: invalid base58btc encoding"
  Just ByteString
decoded
    | ByteString -> ByteString
B58.encode ByteString
decoded ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
encoded -> ByteString -> Either String ByteString
forall a b. b -> Either a b
Right ByteString
decoded
    | Bool
otherwise -> String -> Either String ByteString
forall a b. a -> Either a b
Left String
"decodeMultibase: non-canonical base58btc encoding"

asciiToUpper :: Word8 -> Word8
asciiToUpper :: Word8 -> Word8
asciiToUpper Word8
byte
  | Word8
byte Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word8
0x61 Bool -> Bool -> Bool
&& Word8
byte Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
<= Word8
0x7a = Word8
byte Word8 -> Word8 -> Word8
forall a. Num a => a -> a -> a
- Word8
0x20
  | Bool
otherwise = Word8
byte

asciiToLower :: Word8 -> Word8
asciiToLower :: Word8 -> Word8
asciiToLower Word8
byte
  | Word8
byte Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word8
0x41 Bool -> Bool -> Bool
&& Word8
byte Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
<= Word8
0x5a = Word8
byte Word8 -> Word8 -> Word8
forall a. Num a => a -> a -> a
+ Word8
0x20
  | Bool
otherwise = Word8
byte

-- | Show a Word64 as hex.
showHexW64 :: Word64 -> String
showHexW64 :: Word64 -> String
showHexW64 = String -> Word64 -> String
forall {t}. Integral t => String -> t -> String
go []
  where
    go :: String -> t -> String
go String
acc t
0 | String -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
acc = String
"0"
             | Bool
otherwise = String
acc
    go String
acc t
n = String -> t -> String
go (Int -> Char
hexDigit (t -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (t
n t -> t -> t
forall a. Integral a => a -> a -> a
`mod` t
16)) Char -> ShowS
forall a. a -> [a] -> [a]
: String
acc) (t
n t -> t -> t
forall a. Integral a => a -> a -> a
`div` t
16)
    hexDigit :: Int -> Char
    hexDigit :: Int -> Char
hexDigit Int
d
      | Int
d Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
10 = Int -> Char
forall a. Enum a => Int -> a
toEnum (Int
d Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Char -> Int
forall a. Enum a => a -> Int
fromEnum Char
'0')
      | Bool
otherwise = Int -> Char
forall a. Enum a => Int -> a
toEnum (Int
d Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
10 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Char -> Int
forall a. Enum a => a -> Int
fromEnum Char
'a')