{-# OPTIONS_HADDOCK prune #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}

-- |
-- Module: Bitcoin.Prim.Tx
-- Copyright: (c) 2025 Jared Tobin
-- License: MIT
-- Maintainer: Jared Tobin <jared@ppad.tech>
--
-- Minimal Bitcoin transaction primitives, including raw transaction
-- types, serialisation to/from bytes, and txid computation.

module Bitcoin.Prim.Tx (
    -- * Transaction Types
    Tx(..)
  , TxIn(..)
  , TxOut(..)
  , OutPoint(..)
  , Witness(..)
  , TxId
  , mk_txid
  , un_txid
  , null_txid

    -- * Serialisation
  , to_bytes
  , from_bytes
  , to_bytes_legacy
  , to_base16
  , from_base16

    -- * TxId
  , txid
  ) where

import Bitcoin.Prim.Tx.Internal
import qualified Crypto.Hash.SHA256 as SHA256
import Data.Bits ((.|.), shiftL)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Builder as BSB
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as NE
import Data.Word (Word32, Word64)

-- | Construct a 'TxId' from 32 bytes in internal byte order (the
--   reverse of the usual hex display).
--
--   Returns 'Nothing' if the input is not exactly 32 bytes.
--
--   >>> fmap (BS.length . un_txid) (mk_txid (BS.replicate 32 0x00))
--   Just 32
--   >>> mk_txid (BS.replicate 31 0x00)
--   Nothing
mk_txid :: BS.ByteString -> Maybe TxId
mk_txid :: ByteString -> Maybe TxId
mk_txid ByteString
bs
  | ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
32 = TxId -> Maybe TxId
forall a. a -> Maybe a
Just (ByteString -> TxId
TxId ByteString
bs)
  | Bool
otherwise          = Maybe TxId
forall a. Maybe a
Nothing

-- | The 32 bytes of a 'TxId', in internal byte order.
un_txid :: TxId -> BS.ByteString
un_txid :: TxId -> ByteString
un_txid (TxId ByteString
bs) = ByteString
bs
{-# INLINE un_txid #-}

-- | The all-zero 'TxId', referenced by coinbase inputs' outpoints.
null_txid :: TxId
null_txid :: TxId
null_txid = ByteString -> TxId
TxId (Int -> Word8 -> ByteString
BS.replicate Int
32 Word8
0x00)

-- serialisation --------------------------------------------------------------

-- | Serialise a transaction to bytes.
--
--   Uses the segwit format if any input has a non-empty witness, and
--   the legacy format otherwise (as Bitcoin Core does).
--
--   @
--   -- round-trip
--   from_bytes (to_bytes tx) == Just tx
--   @
to_bytes :: Tx -> BS.ByteString
to_bytes :: Tx -> ByteString
to_bytes tx :: Tx
tx@Tx {Word32
NonEmpty TxOut
NonEmpty TxIn
tx_version :: Word32
tx_inputs :: NonEmpty TxIn
tx_outputs :: NonEmpty TxOut
tx_locktime :: Word32
tx_locktime :: Tx -> Word32
tx_outputs :: Tx -> NonEmpty TxOut
tx_inputs :: Tx -> NonEmpty TxIn
tx_version :: Tx -> Word32
..}
    | Bool -> Bool
not ((TxIn -> Bool) -> NonEmpty TxIn -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Witness -> Bool
has_witness (Witness -> Bool) -> (TxIn -> Witness) -> TxIn -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TxIn -> Witness
txin_witness) NonEmpty TxIn
tx_inputs) = Tx -> ByteString
to_bytes_legacy Tx
tx
    | Bool
otherwise = Builder -> ByteString
to_strict (Builder -> ByteString) -> Builder -> ByteString
forall a b. (a -> b) -> a -> b
$
           Word32 -> Builder
put_word32_le Word32
tx_version
        Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word8 -> Builder
BSB.word8 Word8
0x00  -- marker
        Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word8 -> Builder
BSB.word8 Word8
0x01  -- flag
        Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word64 -> Builder
put_compact (Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (NonEmpty TxIn -> Int
forall a. NonEmpty a -> Int
NE.length NonEmpty TxIn
tx_inputs))
        Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> (TxIn -> Builder) -> NonEmpty TxIn -> Builder
forall m a. Monoid m => (a -> m) -> NonEmpty a -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap TxIn -> Builder
put_txin NonEmpty TxIn
tx_inputs
        Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word64 -> Builder
put_compact (Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (NonEmpty TxOut -> Int
forall a. NonEmpty a -> Int
NE.length NonEmpty TxOut
tx_outputs))
        Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> (TxOut -> Builder) -> NonEmpty TxOut -> Builder
forall m a. Monoid m => (a -> m) -> NonEmpty a -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap TxOut -> Builder
put_txout NonEmpty TxOut
tx_outputs
        Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> (TxIn -> Builder) -> NonEmpty TxIn -> Builder
forall m a. Monoid m => (a -> m) -> NonEmpty a -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (Witness -> Builder
put_witness (Witness -> Builder) -> (TxIn -> Witness) -> TxIn -> Builder
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TxIn -> Witness
txin_witness) NonEmpty TxIn
tx_inputs
        Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word32 -> Builder
put_word32_le Word32
tx_locktime

-- whether a witness stack is non-empty
has_witness :: Witness -> Bool
has_witness :: Witness -> Bool
has_witness (Witness [ByteString]
items) = Bool -> Bool
not ([ByteString] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [ByteString]
items)
{-# INLINE has_witness #-}

-- | Serialise a transaction to legacy format (no witness data).
--
--   Used for txid computation. Excludes witness data even if present.
--
--   @
--   -- for a legacy tx (no witnesses), the same as to_bytes
--   to_bytes_legacy legacy_tx == to_bytes legacy_tx
--
--   -- for a segwit tx, strips the witnesses
--   BS.length (to_bytes_legacy segwit_tx) < BS.length (to_bytes segwit_tx)
--   @
to_bytes_legacy :: Tx -> BS.ByteString
to_bytes_legacy :: Tx -> ByteString
to_bytes_legacy Tx {Word32
NonEmpty TxOut
NonEmpty TxIn
tx_locktime :: Tx -> Word32
tx_outputs :: Tx -> NonEmpty TxOut
tx_inputs :: Tx -> NonEmpty TxIn
tx_version :: Tx -> Word32
tx_version :: Word32
tx_inputs :: NonEmpty TxIn
tx_outputs :: NonEmpty TxOut
tx_locktime :: Word32
..} = Builder -> ByteString
to_strict (Builder -> ByteString) -> Builder -> ByteString
forall a b. (a -> b) -> a -> b
$
       Word32 -> Builder
put_word32_le Word32
tx_version
    Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word64 -> Builder
put_compact (Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (NonEmpty TxIn -> Int
forall a. NonEmpty a -> Int
NE.length NonEmpty TxIn
tx_inputs))
    Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> (TxIn -> Builder) -> NonEmpty TxIn -> Builder
forall m a. Monoid m => (a -> m) -> NonEmpty a -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap TxIn -> Builder
put_txin NonEmpty TxIn
tx_inputs
    Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word64 -> Builder
put_compact (Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (NonEmpty TxOut -> Int
forall a. NonEmpty a -> Int
NE.length NonEmpty TxOut
tx_outputs))
    Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> (TxOut -> Builder) -> NonEmpty TxOut -> Builder
forall m a. Monoid m => (a -> m) -> NonEmpty a -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap TxOut -> Builder
put_txout NonEmpty TxOut
tx_outputs
    Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word32 -> Builder
put_word32_le Word32
tx_locktime

-- | Serialise a transaction to base16 (hex).
--
--   @
--   to_base16 tx = B16.encode (to_bytes tx)
--   @
to_base16 :: Tx -> BS.ByteString
to_base16 :: Tx -> ByteString
to_base16 Tx
tx = ByteString -> ByteString
B16.encode (Tx -> ByteString
to_bytes Tx
tx)

-- | Parse a transaction from base16 (hex).
--
--   @
--   -- round-trip
--   from_base16 (to_base16 tx) == Just tx
--   @
from_base16 :: BS.ByteString -> Maybe Tx
from_base16 :: ByteString -> Maybe Tx
from_base16 ByteString
b16 = do
  bs <- ByteString -> Maybe ByteString
B16.decode ByteString
b16
  from_bytes bs

-- decoding -------------------------------------------------------------------

-- | Parse a transaction from bytes.
--
--   Automatically detects segwit vs legacy format by checking for
--   marker byte 0x00 followed by flag 0x01 after the version field.
--
--   Returns 'Nothing' on invalid or truncated input.
--
--   @
--   -- round-trip
--   from_bytes (to_bytes tx) == Just tx
--   @
from_bytes :: BS.ByteString -> Maybe Tx
from_bytes :: ByteString -> Maybe Tx
from_bytes !ByteString
bs = do
  -- need at least 4 bytes for version
  Bool -> Maybe ()
guard (ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
4)
  let !version :: Word32
version = ByteString -> Int -> Word32
get_word32_le ByteString
bs Int
0
      !off0 :: Int
off0 = Int
4
  -- check for segwit marker (0x00) and flag (0x01)
  if   ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
off0 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1
    Bool -> Bool -> Bool
&& HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs Int
off0 Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
== Word8
0x00
    Bool -> Bool -> Bool
&& HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
off0 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
== Word8
0x01
  then ByteString -> Word32 -> Int -> Maybe Tx
parse_segwit ByteString
bs Word32
version (Int
off0 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2)
  else ByteString -> Word32 -> Int -> Maybe Tx
parse_legacy ByteString
bs Word32
version Int
off0

-- Parse legacy transaction (no witness data)
parse_legacy :: BS.ByteString -> Word32 -> Int -> Maybe Tx
parse_legacy :: ByteString -> Word32 -> Int -> Maybe Tx
parse_legacy !ByteString
bs !Word32
version !Int
off0 = do
  -- input count
  (input_count, off1) <- ByteString -> Int -> Maybe (Word64, Int)
get_compact ByteString
bs Int
off0
  -- inputs (must have at least one)
  (inputs_list, off2) <- get_many get_txin bs off1 input_count
  inputs <- NE.nonEmpty inputs_list
  -- output count
  (output_count, off3) <- get_compact bs off2
  -- outputs (must have at least one)
  (outputs_list, off4) <- get_many get_txout bs off3 output_count
  outputs <- NE.nonEmpty outputs_list
  -- locktime (4 bytes)
  guard (BS.length bs >= off4 + 4)
  let !locktime = ByteString -> Int -> Word32
get_word32_le ByteString
bs Int
off4
      !off5 = Int
off4 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
4
  -- should have consumed all bytes
  guard (off5 == BS.length bs)
  pure $! Tx version inputs outputs locktime

-- Parse segwit transaction (with witness data)
parse_segwit :: BS.ByteString -> Word32 -> Int -> Maybe Tx
parse_segwit :: ByteString -> Word32 -> Int -> Maybe Tx
parse_segwit !ByteString
bs !Word32
version !Int
off0 = do
  -- input count
  (input_count, off1) <- ByteString -> Int -> Maybe (Word64, Int)
get_compact ByteString
bs Int
off0
  -- inputs (must have at least one)
  (inputs_list, off2) <- get_many get_txin bs off1 input_count
  inputs <- NE.nonEmpty inputs_list
  -- output count
  (output_count, off3) <- get_compact bs off2
  -- outputs (must have at least one)
  (outputs_list, off4) <- get_many get_txout bs off3 output_count
  outputs <- NE.nonEmpty outputs_list
  -- witnesses (one per input)
  (witnesses, off5) <- get_many get_witness bs off4 input_count
  -- a marker and flag with no witness data is invalid (Bitcoin Core:
  -- "superfluous witness record")
  guard (any has_witness witnesses)
  -- locktime (4 bytes)
  guard (BS.length bs >= off5 + 4)
  let !locktime = ByteString -> Int -> Word32
get_word32_le ByteString
bs Int
off5
      !off6 = Int
off5 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
4
  -- should have consumed all bytes
  guard (off6 == BS.length bs)
  pure $! Tx version (attach_witnesses inputs witnesses) outputs locktime

-- Pair each input with its witness (get_many returns exactly one per
-- input).
attach_witnesses :: NonEmpty TxIn -> [Witness] -> NonEmpty TxIn
attach_witnesses :: NonEmpty TxIn -> [Witness] -> NonEmpty TxIn
attach_witnesses (TxIn
i :| [TxIn]
is) [Witness]
ws = case [Witness]
ws of
  (Witness
w : [Witness]
rest) -> TxIn -> Witness -> TxIn
set TxIn
i Witness
w TxIn -> [TxIn] -> NonEmpty TxIn
forall a. a -> [a] -> NonEmpty a
:| (TxIn -> Witness -> TxIn) -> [TxIn] -> [Witness] -> [TxIn]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith TxIn -> Witness -> TxIn
set [TxIn]
is [Witness]
rest
  []         -> TxIn
i TxIn -> [TxIn] -> NonEmpty TxIn
forall a. a -> [a] -> NonEmpty a
:| [TxIn]
is
  where
    set :: TxIn -> Witness -> TxIn
set TxIn
x Witness
w = TxIn
x { txin_witness = w }

-- internal helpers -----------------------------------------------------------

-- | Guard for Maybe monad.
guard :: Bool -> Maybe ()
guard :: Bool -> Maybe ()
guard Bool
True  = () -> Maybe ()
forall a. a -> Maybe a
Just ()
guard Bool
False = Maybe ()
forall a. Maybe a
Nothing
{-# INLINE guard #-}

-- | Decode a 32-bit little-endian word at the given offset.
--   Does not bounds-check; caller must ensure sufficient bytes.
get_word32_le :: BS.ByteString -> Int -> Word32
get_word32_le :: ByteString -> Int -> Word32
get_word32_le !ByteString
bs !Int
off =
  let !b0 :: Word32
b0 = Word8 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs Int
off) :: Word32
      !b1 :: Word32
b1 = Word8 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)) :: Word32
      !b2 :: Word32
b2 = Word8 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2)) :: Word32
      !b3 :: Word32
b3 = Word8 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
3)) :: Word32
  in  Word32
b0 Word32 -> Word32 -> Word32
forall a. Bits a => a -> a -> a
.|. (Word32
b1 Word32 -> Int -> Word32
forall a. Bits a => a -> Int -> a
`shiftL` Int
8) Word32 -> Word32 -> Word32
forall a. Bits a => a -> a -> a
.|. (Word32
b2 Word32 -> Int -> Word32
forall a. Bits a => a -> Int -> a
`shiftL` Int
16) Word32 -> Word32 -> Word32
forall a. Bits a => a -> a -> a
.|. (Word32
b3 Word32 -> Int -> Word32
forall a. Bits a => a -> Int -> a
`shiftL` Int
24)
{-# INLINE get_word32_le #-}

-- | Decode a 64-bit little-endian word at the given offset.
--   Does not bounds-check; caller must ensure sufficient bytes.
get_word64_le :: BS.ByteString -> Int -> Word64
get_word64_le :: ByteString -> Int -> Word64
get_word64_le !ByteString
bs !Int
off =
  let !b0 :: Word64
b0 = Word8 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs Int
off) :: Word64
      !b1 :: Word64
b1 = Word8 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)) :: Word64
      !b2 :: Word64
b2 = Word8 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2)) :: Word64
      !b3 :: Word64
b3 = Word8 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
3)) :: Word64
      !b4 :: Word64
b4 = Word8 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
4)) :: Word64
      !b5 :: Word64
b5 = Word8 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
5)) :: Word64
      !b6 :: Word64
b6 = Word8 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
6)) :: Word64
      !b7 :: Word64
b7 = Word8 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
7)) :: Word64
  in  Word64
b0 Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.|. (Word64
b1 Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
`shiftL` Int
8) Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.|. (Word64
b2 Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
`shiftL` Int
16) Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.|. (Word64
b3 Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
`shiftL` Int
24)
          Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.|. (Word64
b4 Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
`shiftL` Int
32) Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.|. (Word64
b5 Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
`shiftL` Int
40)
          Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.|. (Word64
b6 Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
`shiftL` Int
48) Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.|. (Word64
b7 Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
`shiftL` Int
56)
{-# INLINE get_word64_le #-}

-- | Decode a 16-bit little-endian word at the given offset.
--   Does not bounds-check; caller must ensure sufficient bytes.
get_word16_le :: BS.ByteString -> Int -> Word64
get_word16_le :: ByteString -> Int -> Word64
get_word16_le !ByteString
bs !Int
off =
  let !b0 :: Word64
b0 = Word8 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs Int
off) :: Word64
      !b1 :: Word64
b1 = Word8 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)) :: Word64
  in  Word64
b0 Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.|. (Word64
b1 Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
`shiftL` Int
8)
{-# INLINE get_word16_le #-}

-- | Decode compactSize (Bitcoin's variable-length integer).
--   Returns (value, new_offset).
--   Enforces minimal encoding: rejects non-minimal representations.
get_compact :: BS.ByteString -> Int -> Maybe (Word64, Int)
get_compact :: ByteString -> Int -> Maybe (Word64, Int)
get_compact !ByteString
bs !Int
off
  | Int
off Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= ByteString -> Int
BS.length ByteString
bs = Maybe (Word64, Int)
forall a. Maybe a
Nothing
  | Bool
otherwise = case HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs Int
off of
      Word8
tag | Word8
tag Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
<= Word8
0xfc ->
        -- Single byte: value is the tag itself
        (Word64, Int) -> Maybe (Word64, Int)
forall a. a -> Maybe a
Just (Word8 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
tag, Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)

      Word8
0xfd ->
        -- 2-byte value follows
        if ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
3
        then Maybe (Word64, Int)
forall a. Maybe a
Nothing
        else
          let !val :: Word64
val = ByteString -> Int -> Word64
get_word16_le ByteString
bs (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)
          in  if Word64
val Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
< Word64
0xfd
              then Maybe (Word64, Int)
forall a. Maybe a
Nothing  -- non-minimal encoding
              else (Word64, Int) -> Maybe (Word64, Int)
forall a. a -> Maybe a
Just (Word64
val, Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
3)

      Word8
0xfe ->
        -- 4-byte value follows
        if ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
5
        then Maybe (Word64, Int)
forall a. Maybe a
Nothing
        else
          let !val :: Word64
val = Word32 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Int -> Word32
get_word32_le ByteString
bs (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)) :: Word64
          in  if Word64
val Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
<= Word64
0xffff
              then Maybe (Word64, Int)
forall a. Maybe a
Nothing  -- non-minimal encoding
              else (Word64, Int) -> Maybe (Word64, Int)
forall a. a -> Maybe a
Just (Word64
val, Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
5)

      Word8
_ -> -- 0xff
        -- 8-byte value follows
        if ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
9
        then Maybe (Word64, Int)
forall a. Maybe a
Nothing
        else
          let !val :: Word64
val = ByteString -> Int -> Word64
get_word64_le ByteString
bs (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)
          in  if Word64
val Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
<= Word64
0xffffffff
              then Maybe (Word64, Int)
forall a. Maybe a
Nothing  -- non-minimal encoding
              else (Word64, Int) -> Maybe (Word64, Int)
forall a. a -> Maybe a
Just (Word64
val, Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
9)
{-# INLINE get_compact #-}

-- | Decode an outpoint (txid + vout).
--   Returns (OutPoint, new_offset).
get_outpoint :: BS.ByteString -> Int -> Maybe (OutPoint, Int)
get_outpoint :: ByteString -> Int -> Maybe (OutPoint, Int)
get_outpoint !ByteString
bs !Int
off
  | ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
36 = Maybe (OutPoint, Int)
forall a. Maybe a
Nothing
  | Bool
otherwise =
      let !txid_bytes :: ByteString
txid_bytes = Int -> ByteString -> ByteString
BS.take Int
32 (Int -> ByteString -> ByteString
BS.drop Int
off ByteString
bs)
          !vout :: Word32
vout = ByteString -> Int -> Word32
get_word32_le ByteString
bs (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
32)
      in  (OutPoint, Int) -> Maybe (OutPoint, Int)
forall a. a -> Maybe a
Just (TxId -> Word32 -> OutPoint
OutPoint (ByteString -> TxId
TxId ByteString
txid_bytes) Word32
vout, Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
36)
{-# INLINE get_outpoint #-}

-- | Decode a transaction input.
--   Returns (TxIn, new_offset).
get_txin :: BS.ByteString -> Int -> Maybe (TxIn, Int)
get_txin :: ByteString -> Int -> Maybe (TxIn, Int)
get_txin !ByteString
bs !Int
off0 = do
  -- outpoint: 36 bytes
  (outpoint, off1) <- ByteString -> Int -> Maybe (OutPoint, Int)
get_outpoint ByteString
bs Int
off0
  -- scriptSig
  (script_sig, off3) <- get_bytes bs off1
  -- sequence: 4 bytes
  guard (BS.length bs >= off3 + 4)
  let !seqn = ByteString -> Int -> Word32
get_word32_le ByteString
bs Int
off3
      !off4 = Int
off3 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
4
  pure (TxIn outpoint script_sig seqn (Witness []), off4)

-- | Decode a transaction output.
--   Returns (TxOut, new_offset).
get_txout :: BS.ByteString -> Int -> Maybe (TxOut, Int)
get_txout :: ByteString -> Int -> Maybe (TxOut, Int)
get_txout !ByteString
bs !Int
off0 = do
  -- value: 8 bytes
  Bool -> Maybe ()
guard (ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
off0 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
8)
  let !value :: Word64
value = ByteString -> Int -> Word64
get_word64_le ByteString
bs Int
off0
      !off1 :: Int
off1 = Int
off0 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
8
  -- scriptPubKey
  (script_pk, off2) <- ByteString -> Int -> Maybe (ByteString, Int)
get_bytes ByteString
bs Int
off1
  pure (TxOut value script_pk, off2)

-- | Decode a witness stack for one input.
--   Returns (Witness, new_offset).
get_witness :: BS.ByteString -> Int -> Maybe (Witness, Int)
get_witness :: ByteString -> Int -> Maybe (Witness, Int)
get_witness !ByteString
bs !Int
off0 = do
  -- stack item count
  (item_count, off1) <- ByteString -> Int -> Maybe (Word64, Int)
get_compact ByteString
bs Int
off0
  -- each item: length + bytes
  (items, off2) <- get_many get_bytes bs off1 item_count
  pure (Witness items, off2)

-- | Decode compactSize-length-prefixed bytes.
--   Returns (bytes, new_offset).
get_bytes :: BS.ByteString -> Int -> Maybe (BS.ByteString, Int)
get_bytes :: ByteString -> Int -> Maybe (ByteString, Int)
get_bytes !ByteString
bs !Int
off0 = do
  (len, off1) <- ByteString -> Int -> Maybe (Word64, Int)
get_compact ByteString
bs Int
off0
  -- compare in Word64, so that huge lengths can't wrap negative
  guard (len <= fromIntegral (BS.length bs - off1))
  let !n = Word64 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word64
len
  pure (BS.take n (BS.drop off1 bs), off1 + n)

-- | Decode a counted sequence of items using a decoder function.
--   Returns (list of items, new_offset).
get_many :: (BS.ByteString -> Int -> Maybe (a, Int))
         -> BS.ByteString -> Int -> Word64 -> Maybe ([a], Int)
get_many :: forall a.
(ByteString -> Int -> Maybe (a, Int))
-> ByteString -> Int -> Word64 -> Maybe ([a], Int)
get_many ByteString -> Int -> Maybe (a, Int)
getter !ByteString
bs !Int
off0 !Word64
count
  -- every item occupies at least one byte, so a larger count is
  -- malformed (and might not fit in an Int)
  | Word64
count Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
> Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Int
BS.length ByteString
bs Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
off0) = Maybe ([a], Int)
forall a. Maybe a
Nothing
  | Bool
otherwise = [a] -> Int -> Int -> Maybe ([a], Int)
forall {t}. (Ord t, Num t) => [a] -> Int -> t -> Maybe ([a], Int)
go [] Int
off0 (Word64 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word64
count :: Int)
  where
    go :: [a] -> Int -> t -> Maybe ([a], Int)
go ![a]
acc !Int
off !t
n
      | t
n t -> t -> Bool
forall a. Ord a => a -> a -> Bool
<= t
0    = ([a], Int) -> Maybe ([a], Int)
forall a. a -> Maybe a
Just ([a] -> [a]
forall a. [a] -> [a]
reverse [a]
acc, Int
off)
      | Bool
otherwise = do
          (item, off') <- ByteString -> Int -> Maybe (a, Int)
getter ByteString
bs Int
off
          go (item : acc) off' (n - 1)
{-# INLINE get_many #-}

-- txid -----------------------------------------------------------------------

-- | Compute the transaction ID (double SHA256 of legacy serialisation).
--
--   The txid is computed from the legacy serialisation, so segwit
--   transactions have the same txid regardless of witness data. It is
--   in internal byte order; reverse it for the usual hex display.
--
--   @
--   -- Satoshi->Hal tx (block 170)
--   B16.encode (BS.reverse (un_txid (txid satoshi_hal_tx)))
--     == "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16"
--   @
txid :: Tx -> TxId
txid :: Tx -> TxId
txid Tx
tx = ByteString -> TxId
TxId (ByteString -> ByteString
SHA256.hash (ByteString -> ByteString
SHA256.hash (Tx -> ByteString
to_bytes_legacy Tx
tx)))