zcash-haskell/src/ZcashHaskell/Transparent.hs

73 lines
2.3 KiB
Haskell
Raw Normal View History

2024-01-18 18:55:23 +00:00
-- Copyright 2022-2024 Vergara Technologies LLC
--
-- This file is part of Zcash-Haskell.
--
2024-01-12 15:46:26 +00:00
-- |
-- Module : ZcashHaskell.Transparent
-- Copyright : 2022-2024 Vergara Technologies
2024-01-18 18:55:23 +00:00
-- License : MIT
2024-01-12 15:46:26 +00:00
--
-- Maintainer : pitmutt@vergara.tech
-- Stability : experimental
-- Portability : unknown
--
-- Functions to interact with the transparent addresses in the Zcash blockchain
--
module ZcashHaskell.Transparent where
import Control.Exception (throwIO)
import Crypto.Hash
import qualified Data.ByteArray as BA
2024-01-12 15:46:26 +00:00
import qualified Data.ByteString as BS
import Data.ByteString.Base58 (bitcoinAlphabet, encodeBase58)
import qualified Data.Text as T
import qualified Data.Text.Encoding as E
import ZcashHaskell.Types
( TransparentAddress(..)
, TransparentType(..)
, ZcashNet(..)
2024-03-06 19:05:00 +00:00
, getTransparentPrefix
)
2024-03-03 21:19:06 +00:00
import Crypto.Secp256k1
import Data.HexString
import Data.Word
import Haskoin.Address (Address(..))
import qualified Haskoin.Crypto.Hash as H
import Haskoin.Crypto.Keys.Extended
2024-03-03 21:19:06 +00:00
encodeTransparent :: ZcashNet -> TransparentAddress -> T.Text
encodeTransparent zNet t =
encodeTransparent' (getTransparentPrefix zNet (ta_type t)) $
toBytes $ ta_bytes t
where
encodeTransparent' :: (Word8, Word8) -> BS.ByteString -> T.Text
encodeTransparent' (a, b) h =
E.decodeUtf8 $ encodeBase58 bitcoinAlphabet $ digest <> BS.take 4 checksum
where
sha256 :: BS.ByteString -> BS.ByteString
sha256 bs = BA.convert (hash bs :: Digest SHA256)
digest = BS.pack [a, b] <> h
checksum = sha256 $ sha256 digest
2024-03-03 21:19:06 +00:00
-- | Attempts to generate an Extended Private Key from a known HDSeed.
genTransparentPrvKey :: BS.ByteString -> XPrvKey
2024-03-03 21:19:06 +00:00
genTransparentPrvKey hdseed = do
makeXPrvKey hdseed
2024-03-03 21:19:06 +00:00
-- | Attempts to obtain an Extended Public Key from a known Extended Private Key
genTransparentPubKey :: XPrvKey -> IO XPubKey
2024-03-03 21:19:06 +00:00
genTransparentPubKey xpvk = do
ioCtx <- createContext
let xpubk = deriveXPubKey ioCtx xpvk
return xpubk
2024-03-03 21:19:06 +00:00
genTransparentReceiver :: XPubKey -> IO TransparentAddress
genTransparentReceiver xpubk = do
ioCtx <- createContext
let x = xPubAddr ioCtx xpubk
case x of
PubKeyAddress k -> return $ TransparentAddress P2PKH $ fromBinary k
ScriptAddress j -> return $ TransparentAddress P2SH $ fromBinary j
_anyOtherKind -> throwIO $ userError "Unsupported transparent address type"