packages feed

haskoin-core-3.0.0: src/Haskoin/Script/SigHash.hs

{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ImportQualifiedPost #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE NoFieldSelectors #-}

-- |
-- Module      : Haskoin.Script.SigHash
-- Copyright   : No rights reserved
-- License     : MIT
-- Maintainer  : jprupp@protonmail.ch
-- Stability   : experimental
-- Portability : POSIX
--
-- Transaction signatures and related functions.
module Haskoin.Script.SigHash
  ( -- * Script Signatures
    SigHash (..),
    SigHashFlag (..),
    sigHashAll,
    sigHashNone,
    sigHashSingle,
    sigHashDefault,
    anyoneCanPay,
    hasForkIdFlag,
    setAnyoneCanPay,
    setForkIdFlag,
    isSigHashAll,
    isSigHashNone,
    isSigHashSingle,
    isSigHashUnknown,
    sigHashAddForkId,
    sigHashGetForkId,
    sigHashAddNetworkId,
    txSigHash,
    txSigHashForkId,
    txSigHashCashToken,

    -- * Digests of every input of a transaction
    TxSigHashes,
    txSigHashes,
    sigHashesTx,
    txSigHashWith,
    txSigHashForkIdWith,
    txSigHashCashTokenWith,
    splitTokenPrefix,
    TxSignature (..),
    decodeTxSig,
    encodeTxSig,
  )
where

import Control.DeepSeq
import Control.Monad
import Crypto.Secp256k1
import Data.Aeson
import Data.Bits
import Data.Bool (bool)
import Data.ByteString (ByteString)
import Data.ByteString qualified as B
import Data.Bytes.Get
import Data.Bytes.Put
import Data.Bytes.Serial
import Data.Hashable
import Data.Maybe
import Data.Scientific
import Data.Vector (Vector)
import Data.Vector qualified as V
import Data.Word
import GHC.Generics (Generic)
import Haskoin.Crypto.Hash
import Haskoin.Crypto.Signature
import Haskoin.Network.Common
import Haskoin.Network.Data
import Haskoin.Script.CashToken (splitTokenData)
import Haskoin.Script.Common
import Haskoin.Transaction.Common
import Haskoin.Util

-- | Constant representing a SIGHASH flag that controls what is being signed.
data SigHashFlag
  = -- | sign all outputs
    SIGHASH_ALL
  | -- | sign no outputs
    SIGHASH_NONE
  | -- | sign the output index corresponding to the input
    SIGHASH_SINGLE
  | -- | replay protection for Bitcoin Cash transactions
    SIGHASH_FORKID
  | -- | new inputs can be added
    SIGHASH_ANYONECANPAY
  deriving (Eq, Ord, Show, Read, Generic, Bounded)

instance NFData SigHashFlag

instance Hashable SigHashFlag

-- | 'fromEnum' gives the value of the flag in a hash type byte, and 'toEnum'
-- reads it back. The values are not consecutive, so the functions that list
-- flags walk the constructors in their order instead of counting: @[minBound
-- ..]@ is the five flags. 'toEnum' of a number that is no flag, 'succ' of the
-- last flag and 'pred' of the first raise an error, as they do for any
-- enumeration.
instance Enum SigHashFlag where
  fromEnum SIGHASH_ALL = 0x01
  fromEnum SIGHASH_NONE = 0x02
  fromEnum SIGHASH_SINGLE = 0x03
  fromEnum SIGHASH_FORKID = 0x40
  fromEnum SIGHASH_ANYONECANPAY = 0x80
  toEnum 0x01 = SIGHASH_ALL
  toEnum 0x02 = SIGHASH_NONE
  toEnum 0x03 = SIGHASH_SINGLE
  toEnum 0x40 = SIGHASH_FORKID
  toEnum 0x80 = SIGHASH_ANYONECANPAY
  toEnum _ = error "Not a valid sighash flag"
  succ flag
    | flag == maxBound = error "succ: SIGHASH_ANYONECANPAY is the last sighash flag"
    | otherwise = sigHashFlags !! (flagPosition flag + 1)
  pred flag
    | flag == minBound = error "pred: SIGHASH_ALL is the first sighash flag"
    | otherwise = sigHashFlags !! (flagPosition flag - 1)
  enumFrom flag = enumFromTo flag maxBound
  enumFromTo from to = map (sigHashFlags !!) [flagPosition from .. flagPosition to]
  enumFromThen from next
    | next >= from = enumFromThenTo from next maxBound
    | otherwise = enumFromThenTo from next minBound
  enumFromThenTo from next to =
    map (sigHashFlags !!) [flagPosition from, flagPosition next .. flagPosition to]

-- | The flags in the order of their constructors.
sigHashFlags :: [SigHashFlag]
sigHashFlags =
  [ SIGHASH_ALL,
    SIGHASH_NONE,
    SIGHASH_SINGLE,
    SIGHASH_FORKID,
    SIGHASH_ANYONECANPAY
  ]

-- | The position of a flag in 'sigHashFlags'.
flagPosition :: SigHashFlag -> Int
flagPosition flag = length (takeWhile (/= flag) sigHashFlags)

-- | Data type representing the different ways a transaction can be signed.
-- When producing a signature, a hash of the transaction is used as the message
-- to be signed. The 'SigHash' parameter controls which parts of the
-- transaction are used or ignored to produce the transaction hash. The idea is
-- that if some part of a transaction is not used to produce the transaction
-- hash, then you can change that part of the transaction after producing a
-- signature without invalidating that signature.
--
-- If the 'SIGHASH_ANYONECANPAY' flag is set (true), then only the current input
-- is signed. Otherwise, all of the inputs of a transaction are signed. The
-- default value for 'SIGHASH_ANYONECANPAY' is unset (false).
newtype SigHash
  = SigHash Word32
  deriving (Eq, Ord, Enum, Show, Read, Generic)
  deriving newtype (Bits, Integral, Num, Real, Hashable, NFData)

instance FromJSON SigHash where
  parseJSON =
    withScientific "sighash" $
      maybe mzero (return . SigHash) . toBoundedInteger

instance ToJSON SigHash where
  toJSON = Number . fromIntegral
  toEncoding (SigHash n) = toEncoding n

-- | SIGHASH_DEFAULT of BIP 341: the hash type 0, which a Taproot key path
-- signature leaves out and which signs like 'sigHashAll'. It is only valid
-- in Taproot signatures.
sigHashDefault :: SigHash
sigHashDefault = 0

-- | SIGHASH_NONE as a byte.
sigHashNone :: SigHash
sigHashNone = fromIntegral $ fromEnum SIGHASH_NONE

-- | SIGHASH_ALL as a byte.
sigHashAll :: SigHash
sigHashAll = fromIntegral $ fromEnum SIGHASH_ALL

-- | SIGHASH_SINGLE as a byte.
sigHashSingle :: SigHash
sigHashSingle = fromIntegral $ fromEnum SIGHASH_SINGLE

-- | SIGHASH_FORKID as a byte.
sigHashForkId :: SigHash
sigHashForkId = fromIntegral $ fromEnum SIGHASH_FORKID

-- | SIGHASH_ANYONECANPAY as a byte.
sigHashAnyoneCanPay :: SigHash
sigHashAnyoneCanPay = fromIntegral $ fromEnum SIGHASH_ANYONECANPAY

-- | Set SIGHASH_FORKID flag.
setForkIdFlag :: SigHash -> SigHash
setForkIdFlag = (.|. sigHashForkId)

-- | Set SIGHASH_ANYONECANPAY flag.
setAnyoneCanPay :: SigHash -> SigHash
setAnyoneCanPay = (.|. sigHashAnyoneCanPay)

-- | Is the SIGHASH_FORKID flag set?
hasForkIdFlag :: SigHash -> Bool
hasForkIdFlag = (/= 0) . (.&. sigHashForkId)

-- | Is the SIGHASH_ANYONECANPAY flag set?
anyoneCanPay :: SigHash -> Bool
anyoneCanPay = (/= 0) . (.&. sigHashAnyoneCanPay)

-- | Returns 'True' if the 'SigHash' has the value 'SIGHASH_ALL'.
isSigHashAll :: SigHash -> Bool
isSigHashAll = (== sigHashAll) . (.&. 0x1f)

-- | Returns 'True' if the 'SigHash' has the value 'SIGHASH_NONE'.
isSigHashNone :: SigHash -> Bool
isSigHashNone = (== sigHashNone) . (.&. 0x1f)

-- | Returns 'True' if the 'SigHash' has the value 'SIGHASH_SINGLE'.
isSigHashSingle :: SigHash -> Bool
isSigHashSingle = (== sigHashSingle) . (.&. 0x1f)

-- | Is the hash type byte one that no node accepts in a signature? This is
-- the test of @IsDefinedHashtypeSignature@ in Bitcoin Core, which the
-- @STRICTENC@ flag enforces: after masking the 'SIGHASH_ANYONECANPAY' and
-- 'SIGHASH_FORKID' bits, the byte must be 'SIGHASH_ALL', 'SIGHASH_NONE' or
-- 'SIGHASH_SINGLE'. Whether the 'SIGHASH_FORKID' bit itself is allowed
-- depends on the network, see 'decodeTxSig'. Only the low byte is looked at,
-- since a fork id may sit in the upper bytes.
isSigHashUnknown :: SigHash -> Bool
isSigHashUnknown sh = base < sigHashAll || base > sigHashSingle
  where
    base = (sh .&. 0xff) .&. complement (sigHashAnyoneCanPay .|. sigHashForkId)

-- | Add a fork id to a 'SigHash'.
sigHashAddForkId :: SigHash -> Word32 -> SigHash
sigHashAddForkId sh w = (fromIntegral w `shiftL` 8) .|. (sh .&. 0x000000ff)

-- | Add fork id of a particular network to a 'SigHash'.
sigHashAddNetworkId :: Network -> SigHash -> SigHash
sigHashAddNetworkId net =
  (`sigHashAddForkId` fromMaybe 0 net.sigHashForkId)

-- | Get fork id from 'SigHash'.
sigHashGetForkId :: SigHash -> Word32
sigHashGetForkId (SigHash n) = fromIntegral $ n `shiftR` 8

-- | Computes the hash that will be used for signing a transaction input that
-- is not a SegWit input.
--
-- The script is the @scriptCode@ of the input: the output script being spent,
-- or the redeem script for a pay-to-script-hash output. If that script
-- contains 'OP_CODESEPARATOR', the caller must pass the part after the last
-- 'OP_CODESEPARATOR' executed before the signature check, as consensus
-- defines it. Any 'OP_CODESEPARATOR' left in that part is removed here, as
-- @SerializeScriptCode@ does in Bitcoin Core.
--
-- Bitcoin Core makes a second change to the script before it hashes a legacy
-- input: @FindAndDelete@ removes every push of the signature being checked.
-- This function does not do that. The standard output scripts never hold a
-- signature, so nothing is lost for them. A caller that verifies another
-- legacy script must remove the pushes of the signature from the script
-- first.
--
-- The hash type is written as four bytes, as Bitcoin Core writes the
-- @nHashType@ it is given. A signature only carries the low byte, so a
-- 'SigHash' above 0xff gives a digest that no signature can match.
--
-- On a network with a fork id, such as Bitcoin Cash, every signature must use
-- the fork id digest of 'txSigHashForkId', so the 'SigHash' must carry the
-- 'SIGHASH_FORKID' flag and the digest is computed by that function. A
-- 'SigHash' without the flag fails, instead of producing a digest no node
-- accepts.
--
-- Fails when the input index is not an index of the transaction.
--
-- This is the function for one digest. For the digests of several inputs
-- of one transaction, 'txSigHashWith' does not hash the transaction again
-- for each of them on a network with a fork id.
txSigHash ::
  Network ->
  -- | transaction to sign
  Tx ->
  -- | script from output being spent
  Script ->
  -- | value of output being spent
  Word64 ->
  -- | index of input being signed
  Int ->
  -- | what to sign
  SigHash ->
  -- | hash to be signed
  Either String Hash256
txSigHash net = txSigHashWith net . txSigHashes

-- | 'txSigHash' for the transaction of the t'TxSigHashes'. It gives the
-- digest that 'txSigHash' gives, and fails as it does.
--
-- On a network with a fork id the digest is that of 'txSigHashForkIdWith',
-- which takes the hashes that the inputs share. Without a fork id nothing
-- is shared: the legacy digest hashes a copy of the whole transaction for
-- each input by its design, in Bitcoin Core too.
txSigHashWith ::
  Network ->
  TxSigHashes ->
  -- | script from output being spent
  Script ->
  -- | value of output being spent
  Word64 ->
  -- | index of input being signed
  Int ->
  -- | what to sign
  SigHash ->
  -- | hash to be signed
  Either String Hash256
txSigHashWith net hashes out v i sh
  | i < 0 || i >= V.length hashes.inputs =
      Left "txSigHash: input index out of range"
  | isJust net.sigHashForkId && not (hasForkIdFlag sh) =
      Left "txSigHash: SIGHASH_FORKID is required on this network"
  | isJust net.sigHashForkId =
      txSigHashForkIdWith net hashes out v i sh
  | otherwise = do
      let newIn = buildInputs tx.inputs fout i sh
      -- When SigSingle and input index > outputs, then sign integer 1
      return . fromMaybe one $ do
        newOut <- buildOutputs tx.outputs i sh
        let newTx = Tx tx.version newIn newOut [] tx.locktime
        return . doubleSHA256 . runPutS $ do
          serialize newTx
          putWord32le $ fromIntegral sh
  where
    tx = hashes.tx
    fout = Script $ filter (/= OP_CODESEPARATOR) out.ops
    one = "0100000000000000000000000000000000000000000000000000000000000000"

-- | Build transaction inputs for computing sighashes. With
-- 'SIGHASH_ANYONECANPAY' only the signed input remains. With 'SIGHASH_NONE'
-- or 'SIGHASH_SINGLE' the sequence numbers of the other inputs are zero. Any
-- other base type, including the undefined ones, behaves as 'SIGHASH_ALL',
-- as in Bitcoin Core.
buildInputs :: [TxIn] -> Script -> Int -> SigHash -> [TxIn]
buildInputs txins out i sh
  | anyoneCanPay sh = [serialOut (txins !! i)]
  | isSigHashNone sh || isSigHashSingle sh = zipWith noSeq single [0 ..]
  | otherwise = single
  where
    serialOut TxIn {..} = TxIn {script = runPutS $ serialize out, ..}
    emptyIn TxIn {..} = TxIn {script = B.empty, ..}
    emptyIns = map emptyIn txins
    single = updateIndex i emptyIns serialOut
    noSeq TxIn {..} j = TxIn {sequence = if i == j then sequence else 0, ..}

-- | Build transaction outputs for computing sighashes. 'SIGHASH_NONE' signs
-- no output. 'SIGHASH_SINGLE' signs the output at the input index, with the
-- outputs before it blanked, and gives 'Nothing' when there is no such
-- output. Any other base type signs every output.
buildOutputs :: [TxOut] -> Int -> SigHash -> Maybe [TxOut]
buildOutputs txos i sh
  | isSigHashNone sh = return []
  | not (isSigHashSingle sh) = return txos
  | i >= length txos = Nothing
  | otherwise = return $ buffer ++ [txos !! i]
  where
    buffer = replicate i $ TxOut maxBound B.empty

-- | Compute the digest of BIP 143, used for SegWit version 0 inputs on
-- Bitcoin and, with the fork id of the network, for every input on Bitcoin
-- Cash.
--
-- The script is the @scriptCode@ of BIP 143: the pay-to-public-key-hash
-- script of the key for a pay-to-witness-public-key-hash input, or the
-- witness script for a pay-to-witness-script-hash input. If it contains
-- 'OP_CODESEPARATOR', the caller must pass the part after the last one
-- executed before the signature check. Unlike 'txSigHash', nothing is removed
-- from that part, as BIP 143 specifies.
--
-- The last field of the digest is the hash type as four bytes. On a network
-- without a fork id it is the 'SigHash' as given, which is what
-- @SignatureHash@ of Bitcoin Core writes. A signature only carries the low
-- byte, so a 'SigHash' above 0xff gives a digest that no signature can
-- match. On a network with a fork id it is the low byte with the fork id of
-- the network in the three bytes above it.
--
-- What is not supported on Bitcoin Cash, where Bitcoin Cash Node is the
-- reference:
--
-- * @SIGHASH_UTXOS@ (0x20), which adds a hash of all the coins spent to the
--   digest. 'isSigHashUnknown' treats the bit as undefined, so 'decodeTxSig'
--   refuses such a signature.
--
-- * Coins that hold tokens, in this function. Their digest also covers the
--   token data, and their output script starts with the prefix byte 0xef,
--   which 'Haskoin.Script.Standard.decodeOutput' does not read. Their
--   digest is 'txSigHashCashToken', with the prefix that 'splitTokenPrefix'
--   takes off the script. "Haskoin.Script.CashToken" reads the prefix.
--
-- * Schnorr signatures as a 'TxSignature'. They are verified by
--   'Haskoin.Crypto.Signature.verifyCashSchnorr', and by
--   'Haskoin.Transaction.Builder.judgeInputs' in an input.
--
-- Fails when the input index is not an index of the transaction.
--
-- This is the function for one digest. It hashes every input and every
-- output of the transaction, so the digests of all the inputs take time
-- by the square of its size: 'txSigHashForkIdWith' is the function for
-- them.
txSigHashForkId ::
  Network ->
  -- | transaction to sign
  Tx ->
  -- | script from output being spent
  Script ->
  -- | value of output being spent
  Word64 ->
  -- | index of input being signed
  Int ->
  -- | what to sign
  SigHash ->
  -- | hash to be signed
  Either String Hash256
txSigHashForkId net = txSigHashForkIdWith net . txSigHashes

-- | 'txSigHashForkId' for the transaction of the t'TxSigHashes', from the
-- hashes that the inputs share. It gives the digest that 'txSigHashForkId'
-- gives, and fails as it does. Its time does not depend on the size of the
-- transaction.
txSigHashForkIdWith ::
  Network ->
  TxSigHashes ->
  -- | script from output being spent
  Script ->
  -- | value of output being spent
  Word64 ->
  -- | index of input being signed
  Int ->
  -- | what to sign
  SigHash ->
  -- | hash to be signed
  Either String Hash256
txSigHashForkIdWith net hashes = txSigHashCashTokenWith net hashes B.empty

-- | 'txSigHashForkId' for a coin of Bitcoin Cash that holds tokens. The
-- digest of such a coin also covers its token prefix, the bytes that
-- 'splitTokenPrefix' takes off the front of its output script, which go in
-- right before the script. With an empty prefix this is 'txSigHashForkId'.
--
-- The outputs of the transaction need nothing done: on the wire the
-- prefix of an output is part of its script field, and so it is in the
-- 'TxOut' that is hashed.
txSigHashCashToken ::
  Network ->
  -- | transaction to sign
  Tx ->
  -- | token prefix of the output being spent, or empty
  ByteString ->
  -- | script from output being spent, without the prefix
  Script ->
  -- | value of output being spent
  Word64 ->
  -- | index of input being signed
  Int ->
  -- | what to sign
  SigHash ->
  -- | hash to be signed
  Either String Hash256
txSigHashCashToken net = txSigHashCashTokenWith net . txSigHashes

-- | 'txSigHashCashToken' for the transaction of the t'TxSigHashes', from
-- the hashes that the inputs share. It gives the digest that
-- 'txSigHashCashToken' gives, and fails as it does.
txSigHashCashTokenWith ::
  Network ->
  TxSigHashes ->
  -- | token prefix of the output being spent, or empty
  ByteString ->
  -- | script from output being spent, without the prefix
  Script ->
  -- | value of output being spent
  Word64 ->
  -- | index of input being signed
  Int ->
  -- | what to sign
  SigHash ->
  -- | hash to be signed
  Either String Hash256
txSigHashCashTokenWith net hashes prefix out v i sh = do
  input <- maybe (Left "txSigHashForkId: input index out of range") Right (hashes.inputs V.!? i)
  return . doubleSHA256 . runPutS $ do
    putWord32le hashes.tx.version
    serialize hashPrevouts
    serialize hashSequence
    serialize input.outpoint
    putByteString prefix
    putScript out
    putWord64le v
    putWord32le input.sequence
    serialize hashOutputs
    putWord32le hashes.tx.locktime
    putWord32le $ fromIntegral hashType
  where
    hashType = case net.sigHashForkId of
      Just forkId -> sigHashAddForkId sh forkId
      Nothing -> sh
    hashPrevouts
      | not (anyoneCanPay sh) = hashes.hashPrevouts
      | otherwise = zeros
    hashSequence
      | not (anyoneCanPay sh || isSigHashSingle sh || isSigHashNone sh) = hashes.hashSequence
      | otherwise = zeros
    hashOutputs
      | not (isSigHashSingle sh || isSigHashNone sh) = hashes.hashOutputs
      | isSigHashSingle sh, Just output <- hashes.outputs V.!? i = doubleSHA256 (runPutS (serialize output))
      | otherwise = zeros
    putScript s = do
      let encodedScript = runPutS $ serialize s
      putVarInt $ B.length encodedScript
      putByteString encodedScript
    zeros :: Hash256
    zeros = "0000000000000000000000000000000000000000000000000000000000000000"

-- | A transaction with what the digests of its inputs share: the three
-- hashes of BIP 143 that are the same for every input (@hashPrevouts@,
-- @hashSequence@ and @hashOutputs@). They are in the digest of a SegWit
-- version 0 input on Bitcoin and of every input on Bitcoin Cash.
--
-- The three hashes cover every input and every output, so a digest that
-- computes them again takes time by the size of the transaction, and the
-- digests of all the inputs by its square. Bitcoin Core computes them once
-- for a transaction (@PrecomputedTransactionData@), and so does Bitcoin
-- Cash Node. With a value of this type, a BIP 143 digest takes time by the
-- size of its own input. t'Haskoin.Transaction.Taproot.TaprootTxHashes' is
-- the same thing for the digest of a Taproot input.
--
-- Make it with 'txSigHashes', which is the only way, so that the hashes
-- are always those of the transaction. A hash is computed when the first
-- digest needs it: one with @SIGHASH_ANYONECANPAY@ needs none of the two
-- over the inputs, and one with @SIGHASH_NONE@ or @SIGHASH_SINGLE@ does not
-- need the one over all the outputs.
--
-- No digest of this module commits to the input scripts nor to the
-- witnesses of the transaction: BIP 143 leaves them out, and the legacy
-- digest empties them. So the value stays right while the inputs of the
-- transaction are signed. After any other change of the transaction, make
-- it again.
data TxSigHashes = TxSigHashes
  { tx :: !Tx,
    inputs :: !(Vector TxIn),
    outputs :: !(Vector TxOut),
    hashPrevouts :: Hash256,
    hashSequence :: Hash256,
    hashOutputs :: Hash256
  }

-- | The transaction with the hashes that the digests of its inputs share
txSigHashes :: Tx -> TxSigHashes
txSigHashes tx =
  TxSigHashes
    { tx = tx,
      inputs = V.fromList tx.inputs,
      outputs = V.fromList tx.outputs,
      hashPrevouts = hashOf (mapM_ (serialize . (.outpoint)) tx.inputs),
      hashSequence = hashOf (mapM_ (putWord32le . (.sequence)) tx.inputs),
      hashOutputs = hashOf (mapM_ serialize tx.outputs)
    }
  where
    hashOf = doubleSHA256 . runPutS

-- | The transaction that the hashes were made from
sigHashesTx :: TxSigHashes -> Tx
sigHashesTx hashes = hashes.tx

-- | Split the script field of an output of Bitcoin Cash into its token
-- prefix and the output script after it. An output without tokens has an
-- empty prefix. 'Nothing' for a prefix that is not well formed.
--
-- This gives the prefix as bytes, which is what 'txSigHashCashToken' needs.
-- 'Haskoin.Script.CashToken.splitTokenData' reads the same prefix into a
-- t'Haskoin.Script.CashToken.TokenData', and says what is wrong with one that
-- is not well formed.
splitTokenPrefix :: ByteString -> Maybe (ByteString, ByteString)
splitTokenPrefix bytes = case splitTokenData bytes of
  Left _ -> Nothing
  Right (_, rest) -> Just (B.splitAt (B.length bytes - B.length rest) bytes)

-- | Data type representing a signature together with a 'SigHash'. The 'SigHash'
-- is serialized as one byte at the end of an ECDSA 'Sig'. All signatures in
-- transaction inputs are of type 'TxSignature'.
--
-- This is the form of a signature that nodes relay. The binary and JSON
-- forms, and 'decodeTxSig', apply the three signature rules of the standard
-- script flags of Bitcoin Core, and two rules of the network:
--
-- * @DERSIG@: strict DER, as BIP 66 defines it, with r and s between 1 and
--   the curve order minus 1.
--
-- * @LOW_S@: s is at most half the curve order.
--
-- * @STRICTENC@: the hash type byte is defined ('isSigHashUnknown').
--
-- * The 'SIGHASH_FORKID' flag is set exactly on the networks that have a
--   fork id.
--
-- * On a network that has a fork id, the signature is not 64 bytes long
--   before its hash type byte ('isCashSchnorrLength'). See below.
--
-- Nothing may follow the hash type byte.
--
-- On Bitcoin only the first rule is a consensus rule, and only since BIP 66.
-- A block can therefore hold signatures that do not decode: one with a high
-- S, one with an undefined hash type byte, and, before BIP 66 activated, one
-- in a looser DER form. An input with such a signature fails
-- 'Haskoin.Script.Standard.decodeInput', and has no
-- 'Haskoin.Address.inputAddress'. This type is not a parser for the whole
-- chain history. 'Haskoin.Crypto.Signature.decodeStrictSig' reads a
-- signature under BIP 66 alone.
--
-- On Bitcoin Cash, a signature of 64 bytes followed by the hash type byte is
-- a Schnorr signature, whatever its bytes. Bitcoin Cash Node verifies it as
-- one in @OP_CHECKSIG@, and takes no signature of that length in a multisig
-- that has no field of bits. This type only holds ECDSA signatures, so on a
-- network with a fork id nothing of 64 bytes decodes: not a Schnorr
-- signature, and not an ECDSA signature whose DER form has that length.
--
-- Such an ECDSA signature exists: its r and s take 58 bytes together, where
-- they mostly take 64 or 65. It verifies as ECDSA, and no block of Bitcoin
-- Cash holds it, so to read it as a good signature is to call valid a
-- transaction that a node refuses and drops its peer for. The specification
-- of the Schnorr signatures of Bitcoin Cash gives one chance in 2^49 of
-- making one by accident, but a computer makes one on purpose in a minute.
-- On Bitcoin it is an ordinary signature, and it decodes. 'encodeTxSig'
-- writes such a value on every network: on a network with a fork id it is
-- written and not read back. The signer does not make one there
-- ('Haskoin.Transaction.Builder.Sign.makeSignature').
data TxSignature
  = TxSignature
      { sig :: !Sig,
        hash :: !SigHash
      }
  | TxSignatureEmpty
  deriving (Eq, Show, Read, Generic, NFData)

instance Marshal Network TxSignature where
  marshalPut net TxSignatureEmpty = return ()
  marshalPut net (TxSignature sig (SigHash n)) = do
    serialize sig
    putWord8 (fromIntegral n)

  marshalGet net =
    bool decode empty =<< isEmpty
    where
      empty = return TxSignatureEmpty
      decode = do
        sig <- deserialize
        unless (isCanonicalHalfOrder sig) $
          fail "Non-canonical signature: S value is unnecessarily high"
        when (isJust net.sigHashForkId && isCashSchnorrLength sig) $
          fail "Non-canonical signature: a signature of 64 bytes is a Schnorr signature on this network"
        sh <- fromIntegral <$> getWord8
        when (isSigHashUnknown sh) $
          fail "Non-canonical signature: unknown hashtype byte"
        when (isNothing net.sigHashForkId && hasForkIdFlag sh) $
          fail "Non-canonical signature: invalid network for forkId"
        when (isJust net.sigHashForkId && not (hasForkIdFlag sh)) $
          fail "Non-canonical signature: SIGHASH_FORKID is required on this network"
        return $ TxSignature sig sh

instance MarshalJSON Network TxSignature where
  marshalValue net = String . encodeHex . encodeTxSig net
  marshalEncoding s = hexEncoding . runPutL . marshalPut s
  unmarshalValue net =
    withText "TxSignature" $ \t ->
      case decodeHex t of
        Nothing -> fail "Cannot decode hex signature"
        Just b -> case decodeTxSig net b of
          Left e -> fail e
          Right s -> return s

-- | Serialize a signature with its hash type byte. 'TxSignatureEmpty' is the
-- empty string.
encodeTxSig :: Network -> TxSignature -> ByteString
encodeTxSig net = runPutS . marshalPut net

-- | Parse a signature with its hash type byte, under the rules listed at
-- 'TxSignature': strict DER, a low S, a defined hash type, the fork id
-- flag that the network asks for, and on a network with a fork id a length
-- other than 64 bytes, which is a Schnorr signature there. The empty string
-- is 'TxSignatureEmpty'. A signature that is valid by consensus alone does
-- not decode.
decodeTxSig :: Network -> ByteString -> Either String TxSignature
decodeTxSig net =
  runGetS $ do
    sig <- marshalGet net
    e <- isEmpty
    unless e $
      fail "Non-canonical signature: multiple hashtype bytes"
    return sig