packages feed

haskoin-core 1.6.4 → 2.0.0

raw patch · 50 files changed

+5126/−2881 lines, 50 filesdep +tasty-benchdep ~base64dep ~bytestringdep ~secp256k1-haskellsetup-changedPVP ok

version bump matches the API change (PVP)

Dependencies added: tasty-bench

Dependency ranges changed: base64, bytestring, secp256k1-haskell

API changes (from Hackage documentation)

- Haskoin.Crypto.Keys.Common: instance Haskoin.Util.Marshal.Marshal Crypto.Secp256k1.Internal.Context.Ctx Haskoin.Crypto.Keys.Common.PublicKey
- Haskoin.Crypto.Keys.Common: instance Haskoin.Util.Marshal.MarshalJSON Crypto.Secp256k1.Internal.Context.Ctx Haskoin.Crypto.Keys.Common.PublicKey
- Haskoin.Crypto.Keys.Extended: instance Haskoin.Util.Marshal.Marshal (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) Haskoin.Crypto.Keys.Extended.XPubKey
- Haskoin.Crypto.Keys.Extended: instance Haskoin.Util.Marshal.MarshalJSON (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) Haskoin.Crypto.Keys.Extended.XPubKey
- Haskoin.Crypto.Signature: instance Haskoin.Util.Marshal.Marshal Crypto.Secp256k1.Internal.Context.Ctx Crypto.Secp256k1.Internal.Base.Sig
- Haskoin.Crypto.Signature: instance Haskoin.Util.Marshal.MarshalJSON Crypto.Secp256k1.Internal.Context.Ctx Crypto.Secp256k1.Internal.Base.Sig
- Haskoin.Script.SigHash: instance Haskoin.Util.Marshal.Marshal (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) Haskoin.Script.SigHash.TxSignature
- Haskoin.Script.SigHash: instance Haskoin.Util.Marshal.MarshalJSON (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) Haskoin.Script.SigHash.TxSignature
- Haskoin.Script.Standard: instance Haskoin.Util.Marshal.Marshal (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) Haskoin.Script.Standard.ScriptInput
- Haskoin.Script.Standard: instance Haskoin.Util.Marshal.Marshal Crypto.Secp256k1.Internal.Context.Ctx Haskoin.Script.Standard.ScriptOutput
- Haskoin.Script.Standard: instance Haskoin.Util.Marshal.MarshalJSON Crypto.Secp256k1.Internal.Context.Ctx Haskoin.Script.Standard.ScriptOutput
- Haskoin.Transaction.Builder.Sign: instance Haskoin.Util.Marshal.MarshalJSON Crypto.Secp256k1.Internal.Context.Ctx Haskoin.Transaction.Builder.Sign.SigInput
- Haskoin.Transaction.Taproot: instance Haskoin.Util.Marshal.Marshal Crypto.Secp256k1.Internal.Context.Ctx Haskoin.Transaction.Taproot.XOnlyPubKey
- Haskoin.Transaction.Taproot: instance Haskoin.Util.Marshal.MarshalJSON Crypto.Secp256k1.Internal.Context.Ctx Haskoin.Transaction.Taproot.XOnlyPubKey
- Haskoin.Util.Arbitrary.Util: instance GHC.Internal.Show.Show Crypto.Secp256k1.Internal.Context.Ctx
- Haskoin.Util.Helpers: prepareContext :: (Ctx -> SpecWith a) -> SpecWith a
+ Haskoin.Crypto.Keys.Common: instance Data.Aeson.Types.FromJSON.FromJSON Haskoin.Crypto.Keys.Common.PublicKey
+ Haskoin.Crypto.Keys.Common: instance Data.Aeson.Types.ToJSON.ToJSON Haskoin.Crypto.Keys.Common.PublicKey
+ Haskoin.Crypto.Keys.Common: instance Data.Binary.Class.Binary Haskoin.Crypto.Keys.Common.PublicKey
+ Haskoin.Crypto.Keys.Common: instance Data.Bytes.Serial.Serial Haskoin.Crypto.Keys.Common.PublicKey
+ Haskoin.Crypto.Keys.Common: instance Data.Serialize.Serialize Haskoin.Crypto.Keys.Common.PublicKey
+ Haskoin.Crypto.Keys.Extended: instance Haskoin.Util.Marshal.Marshal Haskoin.Network.Data.Network Haskoin.Crypto.Keys.Extended.XPubKey
+ Haskoin.Crypto.Keys.Extended: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network Haskoin.Crypto.Keys.Extended.XPubKey
+ Haskoin.Crypto.Signature: instance Data.Aeson.Types.FromJSON.FromJSON Crypto.Secp256k1.Internal.Base.Sig
+ Haskoin.Crypto.Signature: instance Data.Aeson.Types.ToJSON.ToJSON Crypto.Secp256k1.Internal.Base.Sig
+ Haskoin.Crypto.Signature: instance Data.Binary.Class.Binary Crypto.Secp256k1.Internal.Base.Sig
+ Haskoin.Crypto.Signature: instance Data.Bytes.Serial.Serial Crypto.Secp256k1.Internal.Base.Sig
+ Haskoin.Crypto.Signature: instance Data.Serialize.Serialize Crypto.Secp256k1.Internal.Base.Sig
+ Haskoin.Script.SigHash: instance Haskoin.Util.Marshal.Marshal Haskoin.Network.Data.Network Haskoin.Script.SigHash.TxSignature
+ Haskoin.Script.SigHash: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network Haskoin.Script.SigHash.TxSignature
+ Haskoin.Script.Standard: instance Data.Aeson.Types.FromJSON.FromJSON Haskoin.Script.Standard.ScriptOutput
+ Haskoin.Script.Standard: instance Data.Aeson.Types.ToJSON.ToJSON Haskoin.Script.Standard.ScriptOutput
+ Haskoin.Script.Standard: instance Data.Binary.Class.Binary Haskoin.Script.Standard.ScriptOutput
+ Haskoin.Script.Standard: instance Data.Bytes.Serial.Serial Haskoin.Script.Standard.ScriptOutput
+ Haskoin.Script.Standard: instance Data.Serialize.Serialize Haskoin.Script.Standard.ScriptOutput
+ Haskoin.Script.Standard: instance Haskoin.Util.Marshal.Marshal Haskoin.Network.Data.Network Haskoin.Script.Standard.ScriptInput
+ Haskoin.Transaction.Builder.Sign: instance Data.Aeson.Types.FromJSON.FromJSON Haskoin.Transaction.Builder.Sign.SigInput
+ Haskoin.Transaction.Builder.Sign: instance Data.Aeson.Types.ToJSON.ToJSON Haskoin.Transaction.Builder.Sign.SigInput
+ Haskoin.Transaction.Taproot: instance Data.Aeson.Types.FromJSON.FromJSON Haskoin.Transaction.Taproot.XOnlyPubKey
+ Haskoin.Transaction.Taproot: instance Data.Aeson.Types.ToJSON.ToJSON Haskoin.Transaction.Taproot.XOnlyPubKey
+ Haskoin.Transaction.Taproot: instance Data.Binary.Class.Binary Haskoin.Transaction.Taproot.XOnlyPubKey
+ Haskoin.Transaction.Taproot: instance Data.Bytes.Serial.Serial Haskoin.Transaction.Taproot.XOnlyPubKey
+ Haskoin.Transaction.Taproot: instance Data.Serialize.Serialize Haskoin.Transaction.Taproot.XOnlyPubKey
+ Haskoin.Util.Direct: data Peek a
+ Haskoin.Util.Direct: data Poke a
+ Haskoin.Util.Direct: data Size a
+ Haskoin.Util.Direct: decodeDirect :: (forall (m :: Type -> Type). MonadGet m => m a) -> ByteString -> Either String a
+ Haskoin.Util.Direct: encodeDirect :: (forall (m :: Type -> Type). MonadPut m => m ()) -> ByteString
+ Haskoin.Util.Direct: getDirect :: (forall (m :: Type -> Type). MonadGet m => m a) -> Get a
+ Haskoin.Util.Direct: getShortBytes :: MonadGet m => Int -> m ShortByteString
+ Haskoin.Util.Direct: instance Data.Bytes.Get.MonadGet Haskoin.Util.Direct.Peek
+ Haskoin.Util.Direct: instance Data.Bytes.Put.MonadPut Haskoin.Util.Direct.Poke
+ Haskoin.Util.Direct: instance Data.Bytes.Put.MonadPut Haskoin.Util.Direct.Size
+ Haskoin.Util.Direct: instance GHC.Internal.Base.Applicative Haskoin.Util.Direct.Peek
+ Haskoin.Util.Direct: instance GHC.Internal.Base.Applicative Haskoin.Util.Direct.Poke
+ Haskoin.Util.Direct: instance GHC.Internal.Base.Applicative Haskoin.Util.Direct.Size
+ Haskoin.Util.Direct: instance GHC.Internal.Base.Functor Haskoin.Util.Direct.Peek
+ Haskoin.Util.Direct: instance GHC.Internal.Base.Functor Haskoin.Util.Direct.Poke
+ Haskoin.Util.Direct: instance GHC.Internal.Base.Functor Haskoin.Util.Direct.Size
+ Haskoin.Util.Direct: instance GHC.Internal.Base.Monad Haskoin.Util.Direct.Peek
+ Haskoin.Util.Direct: instance GHC.Internal.Base.Monad Haskoin.Util.Direct.Poke
+ Haskoin.Util.Direct: instance GHC.Internal.Base.Monad Haskoin.Util.Direct.Size
+ Haskoin.Util.Direct: instance GHC.Internal.Control.Monad.Fail.MonadFail Haskoin.Util.Direct.Peek
+ Haskoin.Util.Direct: putDirect :: (forall (m :: Type -> Type). MonadPut m => m ()) -> Put
+ Haskoin.Util.Direct: putShortBytes :: MonadPut m => ShortByteString -> m ()
+ Haskoin.Util.Direct: sizeDirect :: (forall (m :: Type -> Type). MonadPut m => m ()) -> Int
+ Haskoin.Util.Marshal: decodeSerial :: Serial a => ByteString -> Either String a
+ Haskoin.Util.Marshal: encodeSerial :: Serial a => a -> ByteString
- Haskoin.Address: addressToScript :: Ctx -> Address -> Maybe Script
+ Haskoin.Address: addressToScript :: Address -> Maybe Script
- Haskoin.Address: addressToScriptBS :: Ctx -> Address -> Maybe ByteString
+ Haskoin.Address: addressToScriptBS :: Address -> Maybe ByteString
- Haskoin.Address: inputAddress :: Ctx -> ScriptInput -> Maybe Address
+ Haskoin.Address: inputAddress :: ScriptInput -> Maybe Address
- Haskoin.Address: outputAddress :: Network -> Ctx -> ScriptOutput -> Maybe Address
+ Haskoin.Address: outputAddress :: Network -> ScriptOutput -> Maybe Address
- Haskoin.Address: payToNestedScriptAddress :: Ctx -> ScriptOutput -> Either String Address
+ Haskoin.Address: payToNestedScriptAddress :: ScriptOutput -> Either String Address
- Haskoin.Address: payToScriptAddress :: Ctx -> ScriptOutput -> Either String Address
+ Haskoin.Address: payToScriptAddress :: ScriptOutput -> Either String Address
- Haskoin.Address: payToWitnessScriptAddress :: Ctx -> ScriptOutput -> Either String Address
+ Haskoin.Address: payToWitnessScriptAddress :: ScriptOutput -> Either String Address
- Haskoin.Address: pubKeyAddr :: Ctx -> PublicKey -> Address
+ Haskoin.Address: pubKeyAddr :: PublicKey -> Address
- Haskoin.Address: pubKeyCompatWitnessAddr :: Ctx -> PublicKey -> Maybe Address
+ Haskoin.Address: pubKeyCompatWitnessAddr :: PublicKey -> Maybe Address
- Haskoin.Address: pubKeyWitnessAddr :: Ctx -> PublicKey -> Maybe Address
+ Haskoin.Address: pubKeyWitnessAddr :: PublicKey -> Maybe Address
- Haskoin.Address: scriptToAddress :: Network -> Ctx -> Script -> Either String Address
+ Haskoin.Address: scriptToAddress :: Network -> Script -> Either String Address
- Haskoin.Address: scriptToAddressBS :: Network -> Ctx -> ByteString -> Either String Address
+ Haskoin.Address: scriptToAddressBS :: Network -> ByteString -> Either String Address
- Haskoin.Crypto.Keys.Common: decodePubKey :: Ctx -> ByteString -> Either String PublicKey
+ Haskoin.Crypto.Keys.Common: decodePubKey :: ByteString -> Either String PublicKey
- Haskoin.Crypto.Keys.Common: derivePublicKey :: Ctx -> PrivateKey -> PublicKey
+ Haskoin.Crypto.Keys.Common: derivePublicKey :: PrivateKey -> PublicKey
- Haskoin.Crypto.Keys.Common: tweakPubKey :: Ctx -> PubKey -> Hash256 -> Maybe PubKey
+ Haskoin.Crypto.Keys.Common: tweakPubKey :: PubKey -> Hash256 -> Maybe PubKey
- Haskoin.Crypto.Keys.Common: tweakSecKey :: Ctx -> SecKey -> Hash256 -> Maybe SecKey
+ Haskoin.Crypto.Keys.Common: tweakSecKey :: SecKey -> Hash256 -> Maybe SecKey
- Haskoin.Crypto.Keys.Extended: applyPath :: Ctx -> ParsedPath -> XKey -> Either String XKey
+ Haskoin.Crypto.Keys.Extended: applyPath :: ParsedPath -> XKey -> Either String XKey
- Haskoin.Crypto.Keys.Extended: deriveAddr :: Ctx -> XPubKey -> KeyIndex -> (Address, PubKey)
+ Haskoin.Crypto.Keys.Extended: deriveAddr :: XPubKey -> KeyIndex -> (Address, PubKey)
- Haskoin.Crypto.Keys.Extended: deriveAddrs :: Ctx -> XPubKey -> KeyIndex -> [(Address, PubKey, KeyIndex)]
+ Haskoin.Crypto.Keys.Extended: deriveAddrs :: XPubKey -> KeyIndex -> [(Address, PubKey, KeyIndex)]
- Haskoin.Crypto.Keys.Extended: deriveCompatWitnessAddr :: Ctx -> XPubKey -> KeyIndex -> (Address, PubKey)
+ Haskoin.Crypto.Keys.Extended: deriveCompatWitnessAddr :: XPubKey -> KeyIndex -> (Address, PubKey)
- Haskoin.Crypto.Keys.Extended: deriveCompatWitnessAddrs :: Ctx -> XPubKey -> KeyIndex -> [(Address, PubKey, KeyIndex)]
+ Haskoin.Crypto.Keys.Extended: deriveCompatWitnessAddrs :: XPubKey -> KeyIndex -> [(Address, PubKey, KeyIndex)]
- Haskoin.Crypto.Keys.Extended: deriveMSAddr :: Ctx -> [XPubKey] -> Int -> KeyIndex -> Either String (Address, RedeemScript)
+ Haskoin.Crypto.Keys.Extended: deriveMSAddr :: [XPubKey] -> Int -> KeyIndex -> Either String (Address, RedeemScript)
- Haskoin.Crypto.Keys.Extended: deriveMSAddrs :: Ctx -> [XPubKey] -> Int -> KeyIndex -> Either String [(Address, RedeemScript, KeyIndex)]
+ Haskoin.Crypto.Keys.Extended: deriveMSAddrs :: [XPubKey] -> Int -> KeyIndex -> Either String [(Address, RedeemScript, KeyIndex)]
- Haskoin.Crypto.Keys.Extended: derivePath :: Ctx -> DerivPathI t -> XPrvKey -> XPrvKey
+ Haskoin.Crypto.Keys.Extended: derivePath :: DerivPathI t -> XPrvKey -> XPrvKey
- Haskoin.Crypto.Keys.Extended: derivePathAddr :: Ctx -> XPubKey -> SoftPath -> KeyIndex -> (Address, PubKey)
+ Haskoin.Crypto.Keys.Extended: derivePathAddr :: XPubKey -> SoftPath -> KeyIndex -> (Address, PubKey)
- Haskoin.Crypto.Keys.Extended: derivePathAddrs :: Ctx -> XPubKey -> SoftPath -> KeyIndex -> [(Address, PubKey, KeyIndex)]
+ Haskoin.Crypto.Keys.Extended: derivePathAddrs :: XPubKey -> SoftPath -> KeyIndex -> [(Address, PubKey, KeyIndex)]
- Haskoin.Crypto.Keys.Extended: derivePathMSAddr :: Ctx -> [XPubKey] -> SoftPath -> Int -> KeyIndex -> Either String (Address, RedeemScript)
+ Haskoin.Crypto.Keys.Extended: derivePathMSAddr :: [XPubKey] -> SoftPath -> Int -> KeyIndex -> Either String (Address, RedeemScript)
- Haskoin.Crypto.Keys.Extended: derivePathMSAddrs :: Ctx -> [XPubKey] -> SoftPath -> Int -> KeyIndex -> Either String [(Address, RedeemScript, KeyIndex)]
+ Haskoin.Crypto.Keys.Extended: derivePathMSAddrs :: [XPubKey] -> SoftPath -> Int -> KeyIndex -> Either String [(Address, RedeemScript, KeyIndex)]
- Haskoin.Crypto.Keys.Extended: derivePubPath :: Ctx -> SoftPath -> XPubKey -> XPubKey
+ Haskoin.Crypto.Keys.Extended: derivePubPath :: SoftPath -> XPubKey -> XPubKey
- Haskoin.Crypto.Keys.Extended: deriveWitnessAddr :: Ctx -> XPubKey -> KeyIndex -> (Address, PubKey)
+ Haskoin.Crypto.Keys.Extended: deriveWitnessAddr :: XPubKey -> KeyIndex -> (Address, PubKey)
- Haskoin.Crypto.Keys.Extended: deriveWitnessAddrs :: Ctx -> XPubKey -> KeyIndex -> [(Address, PubKey, KeyIndex)]
+ Haskoin.Crypto.Keys.Extended: deriveWitnessAddrs :: XPubKey -> KeyIndex -> [(Address, PubKey, KeyIndex)]
- Haskoin.Crypto.Keys.Extended: deriveXPubKey :: Ctx -> XPrvKey -> XPubKey
+ Haskoin.Crypto.Keys.Extended: deriveXPubKey :: XPrvKey -> XPubKey
- Haskoin.Crypto.Keys.Extended: hardSubKey :: Ctx -> XPrvKey -> KeyIndex -> XPrvKey
+ Haskoin.Crypto.Keys.Extended: hardSubKey :: XPrvKey -> KeyIndex -> XPrvKey
- Haskoin.Crypto.Keys.Extended: hardSubKeys :: Ctx -> XPrvKey -> KeyIndex -> [(XPrvKey, KeyIndex)]
+ Haskoin.Crypto.Keys.Extended: hardSubKeys :: XPrvKey -> KeyIndex -> [(XPrvKey, KeyIndex)]
- Haskoin.Crypto.Keys.Extended: prvSubKey :: Ctx -> XPrvKey -> KeyIndex -> XPrvKey
+ Haskoin.Crypto.Keys.Extended: prvSubKey :: XPrvKey -> KeyIndex -> XPrvKey
- Haskoin.Crypto.Keys.Extended: prvSubKeys :: Ctx -> XPrvKey -> KeyIndex -> [(XPrvKey, KeyIndex)]
+ Haskoin.Crypto.Keys.Extended: prvSubKeys :: XPrvKey -> KeyIndex -> [(XPrvKey, KeyIndex)]
- Haskoin.Crypto.Keys.Extended: pubSubKey :: Ctx -> XPubKey -> KeyIndex -> XPubKey
+ Haskoin.Crypto.Keys.Extended: pubSubKey :: XPubKey -> KeyIndex -> XPubKey
- Haskoin.Crypto.Keys.Extended: pubSubKeys :: Ctx -> XPubKey -> KeyIndex -> [(XPubKey, KeyIndex)]
+ Haskoin.Crypto.Keys.Extended: pubSubKeys :: XPubKey -> KeyIndex -> [(XPubKey, KeyIndex)]
- Haskoin.Crypto.Keys.Extended: tryDerivePath :: Ctx -> DerivPathI t -> XPrvKey -> Either String XPrvKey
+ Haskoin.Crypto.Keys.Extended: tryDerivePath :: DerivPathI t -> XPrvKey -> Either String XPrvKey
- Haskoin.Crypto.Keys.Extended: tryDerivePubPath :: Ctx -> SoftPath -> XPubKey -> Either String XPubKey
+ Haskoin.Crypto.Keys.Extended: tryDerivePubPath :: SoftPath -> XPubKey -> Either String XPubKey
- Haskoin.Crypto.Keys.Extended: xPrvFP :: Ctx -> XPrvKey -> Fingerprint
+ Haskoin.Crypto.Keys.Extended: xPrvFP :: XPrvKey -> Fingerprint
- Haskoin.Crypto.Keys.Extended: xPrvID :: Ctx -> XPrvKey -> Hash160
+ Haskoin.Crypto.Keys.Extended: xPrvID :: XPrvKey -> Hash160
- Haskoin.Crypto.Keys.Extended: xPubAddr :: Ctx -> XPubKey -> Address
+ Haskoin.Crypto.Keys.Extended: xPubAddr :: XPubKey -> Address
- Haskoin.Crypto.Keys.Extended: xPubCompatWitnessAddr :: Ctx -> XPubKey -> Address
+ Haskoin.Crypto.Keys.Extended: xPubCompatWitnessAddr :: XPubKey -> Address
- Haskoin.Crypto.Keys.Extended: xPubExport :: Network -> Ctx -> XPubKey -> Base58
+ Haskoin.Crypto.Keys.Extended: xPubExport :: Network -> XPubKey -> Base58
- Haskoin.Crypto.Keys.Extended: xPubFP :: Ctx -> XPubKey -> Fingerprint
+ Haskoin.Crypto.Keys.Extended: xPubFP :: XPubKey -> Fingerprint
- Haskoin.Crypto.Keys.Extended: xPubID :: Ctx -> XPubKey -> Hash160
+ Haskoin.Crypto.Keys.Extended: xPubID :: XPubKey -> Hash160
- Haskoin.Crypto.Keys.Extended: xPubImport :: Network -> Ctx -> Base58 -> Maybe XPubKey
+ Haskoin.Crypto.Keys.Extended: xPubImport :: Network -> Base58 -> Maybe XPubKey
- Haskoin.Crypto.Keys.Extended: xPubWitnessAddr :: Ctx -> XPubKey -> Address
+ Haskoin.Crypto.Keys.Extended: xPubWitnessAddr :: XPubKey -> Address
- Haskoin.Crypto.Signature: decodeStrictSig :: Ctx -> ByteString -> Maybe Sig
+ Haskoin.Crypto.Signature: decodeStrictSig :: ByteString -> Maybe Sig
- Haskoin.Crypto.Signature: exportSig :: Ctx -> Sig -> ByteString
+ Haskoin.Crypto.Signature: exportSig :: Sig -> ByteString
- Haskoin.Crypto.Signature: isCanonicalHalfOrder :: Ctx -> Sig -> Bool
+ Haskoin.Crypto.Signature: isCanonicalHalfOrder :: Sig -> Bool
- Haskoin.Crypto.Signature: signHash :: Ctx -> SecKey -> Hash256 -> Sig
+ Haskoin.Crypto.Signature: signHash :: SecKey -> Hash256 -> Sig
- Haskoin.Crypto.Signature: verifyCashSchnorr :: Ctx -> PubKey -> ByteString -> Hash256 -> Bool
+ Haskoin.Crypto.Signature: verifyCashSchnorr :: PubKey -> ByteString -> Hash256 -> Bool
- Haskoin.Crypto.Signature: verifyHashSig :: Ctx -> Hash256 -> Sig -> PubKey -> Bool
+ Haskoin.Crypto.Signature: verifyHashSig :: Hash256 -> Sig -> PubKey -> Bool
- Haskoin.Network.Bloom: bloomRelevantUpdate :: Ctx -> BloomFilter -> Tx -> Maybe BloomFilter
+ Haskoin.Network.Bloom: bloomRelevantUpdate :: BloomFilter -> Tx -> Maybe BloomFilter
- Haskoin.Script.SigHash: decodeTxSig :: Network -> Ctx -> ByteString -> Either String TxSignature
+ Haskoin.Script.SigHash: decodeTxSig :: Network -> ByteString -> Either String TxSignature
- Haskoin.Script.SigHash: encodeTxSig :: Network -> Ctx -> TxSignature -> ByteString
+ Haskoin.Script.SigHash: encodeTxSig :: Network -> TxSignature -> ByteString
- Haskoin.Script.Standard: decodeInput :: Network -> Ctx -> Script -> Either String ScriptInput
+ Haskoin.Script.Standard: decodeInput :: Network -> Script -> Either String ScriptInput
- Haskoin.Script.Standard: decodeOutput :: Ctx -> Script -> Either String ScriptOutput
+ Haskoin.Script.Standard: decodeOutput :: Script -> Either String ScriptOutput
- Haskoin.Script.Standard: encodeInput :: Network -> Ctx -> ScriptInput -> Script
+ Haskoin.Script.Standard: encodeInput :: Network -> ScriptInput -> Script
- Haskoin.Script.Standard: encodeOutput :: Ctx -> ScriptOutput -> Either String Script
+ Haskoin.Script.Standard: encodeOutput :: ScriptOutput -> Either String Script
- Haskoin.Script.Standard: sortMulSig :: Ctx -> ScriptOutput -> ScriptOutput
+ Haskoin.Script.Standard: sortMulSig :: ScriptOutput -> ScriptOutput
- Haskoin.Transaction.Builder: buildAddrTx :: Network -> Ctx -> [OutPoint] -> [(Text, Word64)] -> Either String Tx
+ Haskoin.Transaction.Builder: buildAddrTx :: Network -> [OutPoint] -> [(Text, Word64)] -> Either String Tx
- Haskoin.Transaction.Builder: buildInput :: Network -> Ctx -> Tx -> Int -> ScriptOutput -> Word64 -> Maybe RedeemScript -> TxSignature -> PublicKey -> Either String ScriptInput
+ Haskoin.Transaction.Builder: buildInput :: Network -> Tx -> Int -> ScriptOutput -> Word64 -> Maybe RedeemScript -> TxSignature -> PublicKey -> Either String ScriptInput
- Haskoin.Transaction.Builder: buildTx :: Ctx -> [OutPoint] -> [(ScriptOutput, Word64)] -> Tx
+ Haskoin.Transaction.Builder: buildTx :: [OutPoint] -> [(ScriptOutput, Word64)] -> Tx
- Haskoin.Transaction.Builder: countMulSig :: Network -> Ctx -> Tx -> Script -> Word64 -> Int -> [PubKey] -> [TxSignature] -> Int
+ Haskoin.Transaction.Builder: countMulSig :: Network -> Tx -> Script -> Word64 -> Int -> [PubKey] -> [TxSignature] -> Int
- Haskoin.Transaction.Builder: judgeInputs :: Network -> Ctx -> Tx -> [Maybe TxOut] -> [InputVerdict]
+ Haskoin.Transaction.Builder: judgeInputs :: Network -> Tx -> [Maybe TxOut] -> [InputVerdict]
- Haskoin.Transaction.Builder: makeSignature :: Network -> Ctx -> Tx -> Int -> SigInput -> PrivateKey -> Either String TxSignature
+ Haskoin.Transaction.Builder: makeSignature :: Network -> Tx -> Int -> SigInput -> PrivateKey -> Either String TxSignature
- Haskoin.Transaction.Builder: mergeTxInput :: Network -> Ctx -> [Tx] -> Tx -> ((ScriptOutput, Word64), Int) -> Either String Tx
+ Haskoin.Transaction.Builder: mergeTxInput :: Network -> [Tx] -> Tx -> ((ScriptOutput, Word64), Int) -> Either String Tx
- Haskoin.Transaction.Builder: mergeTxs :: Network -> Ctx -> [Tx] -> [(ScriptOutput, Word64, OutPoint)] -> Either String Tx
+ Haskoin.Transaction.Builder: mergeTxs :: Network -> [Tx] -> [(ScriptOutput, Word64, OutPoint)] -> Either String Tx
- Haskoin.Transaction.Builder: sigKeys :: Ctx -> ScriptOutput -> Maybe RedeemScript -> [SecKey] -> Either String [PrivateKey]
+ Haskoin.Transaction.Builder: sigKeys :: ScriptOutput -> Maybe RedeemScript -> [SecKey] -> Either String [PrivateKey]
- Haskoin.Transaction.Builder: signInput :: Network -> Ctx -> Tx -> Int -> SigInput -> PrivateKey -> Either String Tx
+ Haskoin.Transaction.Builder: signInput :: Network -> Tx -> Int -> SigInput -> PrivateKey -> Either String Tx
- Haskoin.Transaction.Builder: signNestedInput :: Network -> Ctx -> Tx -> Int -> SigInput -> PrivateKey -> Either String Tx
+ Haskoin.Transaction.Builder: signNestedInput :: Network -> Tx -> Int -> SigInput -> PrivateKey -> Either String Tx
- Haskoin.Transaction.Builder: signNestedWitnessTx :: Network -> Ctx -> Tx -> [SigInput] -> [SecKey] -> Either String Tx
+ Haskoin.Transaction.Builder: signNestedWitnessTx :: Network -> Tx -> [SigInput] -> [SecKey] -> Either String Tx
- Haskoin.Transaction.Builder: signTaprootInput :: Ctx -> Tx -> [TxOut] -> Int -> SigHash -> SecKey -> Either String Tx
+ Haskoin.Transaction.Builder: signTaprootInput :: Tx -> [TxOut] -> Int -> SigHash -> SecKey -> Either String Tx
- Haskoin.Transaction.Builder: signTx :: Network -> Ctx -> Tx -> [SigInput] -> [SecKey] -> Either String Tx
+ Haskoin.Transaction.Builder: signTx :: Network -> Tx -> [SigInput] -> [SecKey] -> Either String Tx
- Haskoin.Transaction.Builder: verifyStdInput :: Network -> Ctx -> Tx -> [(ScriptOutput, Word64, OutPoint)] -> Int -> Bool
+ Haskoin.Transaction.Builder: verifyStdInput :: Network -> Tx -> [(ScriptOutput, Word64, OutPoint)] -> Int -> Bool
- Haskoin.Transaction.Builder: verifyStdTx :: Network -> Ctx -> Tx -> [(ScriptOutput, Word64, OutPoint)] -> Bool
+ Haskoin.Transaction.Builder: verifyStdTx :: Network -> Tx -> [(ScriptOutput, Word64, OutPoint)] -> Bool
- Haskoin.Transaction.Builder.Sign: buildInput :: Network -> Ctx -> Tx -> Int -> ScriptOutput -> Word64 -> Maybe RedeemScript -> TxSignature -> PublicKey -> Either String ScriptInput
+ Haskoin.Transaction.Builder.Sign: buildInput :: Network -> Tx -> Int -> ScriptOutput -> Word64 -> Maybe RedeemScript -> TxSignature -> PublicKey -> Either String ScriptInput
- Haskoin.Transaction.Builder.Sign: makeSigHash :: Network -> Ctx -> Tx -> Int -> ScriptOutput -> Word64 -> SigHash -> Maybe RedeemScript -> Either String Hash256
+ Haskoin.Transaction.Builder.Sign: makeSigHash :: Network -> Tx -> Int -> ScriptOutput -> Word64 -> SigHash -> Maybe RedeemScript -> Either String Hash256
- Haskoin.Transaction.Builder.Sign: makeSignature :: Network -> Ctx -> Tx -> Int -> SigInput -> PrivateKey -> Either String TxSignature
+ Haskoin.Transaction.Builder.Sign: makeSignature :: Network -> Tx -> Int -> SigInput -> PrivateKey -> Either String TxSignature
- Haskoin.Transaction.Builder.Sign: sigKeys :: Ctx -> ScriptOutput -> Maybe RedeemScript -> [SecKey] -> Either String [PrivateKey]
+ Haskoin.Transaction.Builder.Sign: sigKeys :: ScriptOutput -> Maybe RedeemScript -> [SecKey] -> Either String [PrivateKey]
- Haskoin.Transaction.Builder.Sign: signInput :: Network -> Ctx -> Tx -> Int -> (SigInput, Bool) -> PrivateKey -> Either String Tx
+ Haskoin.Transaction.Builder.Sign: signInput :: Network -> Tx -> Int -> (SigInput, Bool) -> PrivateKey -> Either String Tx
- Haskoin.Transaction.Builder.Sign: signTaprootInput :: Ctx -> Tx -> [TxOut] -> Int -> SigHash -> SecKey -> Either String Tx
+ Haskoin.Transaction.Builder.Sign: signTaprootInput :: Tx -> [TxOut] -> Int -> SigHash -> SecKey -> Either String Tx
- Haskoin.Transaction.Builder.Sign: signTx :: Network -> Ctx -> Tx -> [(SigInput, Bool)] -> [SecKey] -> Either String Tx
+ Haskoin.Transaction.Builder.Sign: signTx :: Network -> Tx -> [(SigInput, Bool)] -> [SecKey] -> Either String Tx
- Haskoin.Transaction.Psbt: finalizePsbt :: Network -> Ctx -> Psbt -> Either String Psbt
+ Haskoin.Transaction.Psbt: finalizePsbt :: Network -> Psbt -> Either String Psbt
- Haskoin.Transaction.Psbt: inputDerivations :: Ctx -> PsbtMap -> Either String [(PublicKey, Derivation)]
+ Haskoin.Transaction.Psbt: inputDerivations :: PsbtMap -> Either String [(PublicKey, Derivation)]
- Haskoin.Transaction.Psbt: inputTapDerivations :: Ctx -> PsbtMap -> Either String [(PubKey, TapDerivation)]
+ Haskoin.Transaction.Psbt: inputTapDerivations :: PsbtMap -> Either String [(PubKey, TapDerivation)]
- Haskoin.Transaction.Psbt: inputTapInternalKey :: Ctx -> PsbtMap -> Either String (Maybe PubKey)
+ Haskoin.Transaction.Psbt: inputTapInternalKey :: PsbtMap -> Either String (Maybe PubKey)
- Haskoin.Transaction.Psbt: insertInputDerivation :: Ctx -> PublicKey -> Derivation -> PsbtMap -> PsbtMap
+ Haskoin.Transaction.Psbt: insertInputDerivation :: PublicKey -> Derivation -> PsbtMap -> PsbtMap
- Haskoin.Transaction.Psbt: insertInputTapDerivation :: Ctx -> PubKey -> TapDerivation -> PsbtMap -> PsbtMap
+ Haskoin.Transaction.Psbt: insertInputTapDerivation :: PubKey -> TapDerivation -> PsbtMap -> PsbtMap
- Haskoin.Transaction.Psbt: insertInputTapInternalKey :: Ctx -> PubKey -> PsbtMap -> PsbtMap
+ Haskoin.Transaction.Psbt: insertInputTapInternalKey :: PubKey -> PsbtMap -> PsbtMap
- Haskoin.Transaction.Psbt: insertOutputDerivation :: Ctx -> PublicKey -> Derivation -> PsbtMap -> PsbtMap
+ Haskoin.Transaction.Psbt: insertOutputDerivation :: PublicKey -> Derivation -> PsbtMap -> PsbtMap
- Haskoin.Transaction.Psbt: insertOutputTapDerivation :: Ctx -> PubKey -> TapDerivation -> PsbtMap -> PsbtMap
+ Haskoin.Transaction.Psbt: insertOutputTapDerivation :: PubKey -> TapDerivation -> PsbtMap -> PsbtMap
- Haskoin.Transaction.Psbt: insertOutputTapInternalKey :: Ctx -> PubKey -> PsbtMap -> PsbtMap
+ Haskoin.Transaction.Psbt: insertOutputTapInternalKey :: PubKey -> PsbtMap -> PsbtMap
- Haskoin.Transaction.Psbt: insertPartialSignature :: Ctx -> PublicKey -> ByteString -> PsbtMap -> PsbtMap
+ Haskoin.Transaction.Psbt: insertPartialSignature :: PublicKey -> ByteString -> PsbtMap -> PsbtMap
- Haskoin.Transaction.Psbt: insertTapScriptSig :: Ctx -> PubKey -> Digest SHA256 -> TaprootSignature -> PsbtMap -> PsbtMap
+ Haskoin.Transaction.Psbt: insertTapScriptSig :: PubKey -> Digest SHA256 -> TaprootSignature -> PsbtMap -> PsbtMap
- Haskoin.Transaction.Psbt: insertXpubRecord :: Network -> Ctx -> XPubKey -> Derivation -> PsbtMap -> PsbtMap
+ Haskoin.Transaction.Psbt: insertXpubRecord :: Network -> XPubKey -> Derivation -> PsbtMap -> PsbtMap
- Haskoin.Transaction.Psbt: keySigner :: Ctx -> SecKey -> Signer
+ Haskoin.Transaction.Psbt: keySigner :: SecKey -> Signer
- Haskoin.Transaction.Psbt: outputDerivations :: Ctx -> PsbtMap -> Either String [(PublicKey, Derivation)]
+ Haskoin.Transaction.Psbt: outputDerivations :: PsbtMap -> Either String [(PublicKey, Derivation)]
- Haskoin.Transaction.Psbt: outputTapDerivations :: Ctx -> PsbtMap -> Either String [(PubKey, TapDerivation)]
+ Haskoin.Transaction.Psbt: outputTapDerivations :: PsbtMap -> Either String [(PubKey, TapDerivation)]
- Haskoin.Transaction.Psbt: outputTapInternalKey :: Ctx -> PsbtMap -> Either String (Maybe PubKey)
+ Haskoin.Transaction.Psbt: outputTapInternalKey :: PsbtMap -> Either String (Maybe PubKey)
- Haskoin.Transaction.Psbt: partialSignatures :: Ctx -> PsbtMap -> Either String [(PublicKey, ByteString)]
+ Haskoin.Transaction.Psbt: partialSignatures :: PsbtMap -> Either String [(PublicKey, ByteString)]
- Haskoin.Transaction.Psbt: signPsbt :: Network -> Ctx -> Signer -> Psbt -> Either String Psbt
+ Haskoin.Transaction.Psbt: signPsbt :: Network -> Signer -> Psbt -> Either String Psbt
- Haskoin.Transaction.Psbt: tapLeafScripts :: Ctx -> PsbtMap -> Either String [TapLeafScript]
+ Haskoin.Transaction.Psbt: tapLeafScripts :: PsbtMap -> Either String [TapLeafScript]
- Haskoin.Transaction.Psbt: tapScriptSigs :: Ctx -> PsbtMap -> Either String [((PubKey, Digest SHA256), TaprootSignature)]
+ Haskoin.Transaction.Psbt: tapScriptSigs :: PsbtMap -> Either String [((PubKey, Digest SHA256), TaprootSignature)]
- Haskoin.Transaction.Psbt: xPrvSigner :: Ctx -> XPrvKey -> Maybe Derivation -> Signer
+ Haskoin.Transaction.Psbt: xPrvSigner :: XPrvKey -> Maybe Derivation -> Signer
- Haskoin.Transaction.Psbt: xpubRecords :: Network -> Ctx -> PsbtMap -> Either String [(XPubKey, Derivation)]
+ Haskoin.Transaction.Psbt: xpubRecords :: Network -> PsbtMap -> Either String [(XPubKey, Derivation)]
- Haskoin.Transaction.Segwit: calcWitnessProgram :: Network -> Ctx -> ScriptOutput -> ScriptInput -> Either String WitnessProgram
+ Haskoin.Transaction.Segwit: calcWitnessProgram :: Network -> ScriptOutput -> ScriptInput -> Either String WitnessProgram
- Haskoin.Transaction.Segwit: decodeWitnessInput :: Network -> Ctx -> WitnessProgram -> Either String (Maybe ScriptOutput, SimpleInput)
+ Haskoin.Transaction.Segwit: decodeWitnessInput :: Network -> WitnessProgram -> Either String (Maybe ScriptOutput, SimpleInput)
- Haskoin.Transaction.Segwit: simpleInputStack :: Network -> Ctx -> SimpleInput -> [ByteString]
+ Haskoin.Transaction.Segwit: simpleInputStack :: Network -> SimpleInput -> [ByteString]
- Haskoin.Transaction.Segwit: toWitnessStack :: Network -> Ctx -> WitnessProgram -> WitnessStack
+ Haskoin.Transaction.Segwit: toWitnessStack :: Network -> WitnessProgram -> WitnessStack
- Haskoin.Transaction.Segwit: viewWitnessProgram :: Network -> Ctx -> ScriptOutput -> WitnessStack -> Either String WitnessProgram
+ Haskoin.Transaction.Segwit: viewWitnessProgram :: Network -> ScriptOutput -> WitnessStack -> Either String WitnessProgram
- Haskoin.Transaction.Taproot: decodeControlBlock :: Ctx -> ByteString -> Either String (Word8, PubKey, [Digest SHA256])
+ Haskoin.Transaction.Taproot: decodeControlBlock :: ByteString -> Either String (Word8, PubKey, [Digest SHA256])
- Haskoin.Transaction.Taproot: encodeControlBlock :: Ctx -> Word8 -> PubKey -> [Digest SHA256] -> ByteString
+ Haskoin.Transaction.Taproot: encodeControlBlock :: Word8 -> PubKey -> [Digest SHA256] -> ByteString
- Haskoin.Transaction.Taproot: encodeTaprootWitness :: Ctx -> TaprootWitness -> Either String WitnessStack
+ Haskoin.Transaction.Taproot: encodeTaprootWitness :: TaprootWitness -> Either String WitnessStack
- Haskoin.Transaction.Taproot: keyParity :: Ctx -> PubKey -> Word8
+ Haskoin.Transaction.Taproot: keyParity :: PubKey -> Word8
- Haskoin.Transaction.Taproot: taprootOutputKey :: Ctx -> TaprootOutput -> PubKey
+ Haskoin.Transaction.Taproot: taprootOutputKey :: TaprootOutput -> PubKey
- Haskoin.Transaction.Taproot: taprootOutputSecKey :: Ctx -> SecKey -> Maybe MAST -> Maybe SecKey
+ Haskoin.Transaction.Taproot: taprootOutputSecKey :: SecKey -> Maybe MAST -> Maybe SecKey
- Haskoin.Transaction.Taproot: taprootScriptOutput :: Ctx -> TaprootOutput -> ScriptOutput
+ Haskoin.Transaction.Taproot: taprootScriptOutput :: TaprootOutput -> ScriptOutput
- Haskoin.Transaction.Taproot: verifyScriptPathData :: Ctx -> PubKey -> ScriptPathData -> Bool
+ Haskoin.Transaction.Taproot: verifyScriptPathData :: PubKey -> ScriptPathData -> Bool
- Haskoin.Transaction.Taproot: viewTaprootWitness :: Ctx -> WitnessStack -> Maybe TaprootWitness
+ Haskoin.Transaction.Taproot: viewTaprootWitness :: WitnessStack -> Maybe TaprootWitness
- Haskoin.Util.Arbitrary.Block: arbitraryBlock :: Network -> Ctx -> Gen Block
+ Haskoin.Util.Arbitrary.Block: arbitraryBlock :: Network -> Gen Block
- Haskoin.Util.Arbitrary.Block: arbitraryNetworkTx :: Network -> Ctx -> Gen Tx
+ Haskoin.Util.Arbitrary.Block: arbitraryNetworkTx :: Network -> Gen Tx
- Haskoin.Util.Arbitrary.Keys: arbitraryKeyPair :: Ctx -> Gen (PrivateKey, PublicKey)
+ Haskoin.Util.Arbitrary.Keys: arbitraryKeyPair :: Gen (PrivateKey, PublicKey)
- Haskoin.Util.Arbitrary.Keys: arbitraryKeyPairC :: Ctx -> Gen (PrivateKey, PublicKey)
+ Haskoin.Util.Arbitrary.Keys: arbitraryKeyPairC :: Gen (PrivateKey, PublicKey)
- Haskoin.Util.Arbitrary.Keys: arbitraryPublicKey :: Ctx -> Gen PublicKey
+ Haskoin.Util.Arbitrary.Keys: arbitraryPublicKey :: Gen PublicKey
- Haskoin.Util.Arbitrary.Keys: arbitrarySignature :: Ctx -> Gen (Hash256, SecKey, Sig)
+ Haskoin.Util.Arbitrary.Keys: arbitrarySignature :: Gen (Hash256, SecKey, Sig)
- Haskoin.Util.Arbitrary.Keys: arbitraryXKeyPair :: Ctx -> Gen (XPrvKey, XPubKey)
+ Haskoin.Util.Arbitrary.Keys: arbitraryXKeyPair :: Gen (XPrvKey, XPubKey)
- Haskoin.Util.Arbitrary.Keys: arbitraryXPubKey :: Ctx -> Gen XPubKey
+ Haskoin.Util.Arbitrary.Keys: arbitraryXPubKey :: Gen XPubKey
- Haskoin.Util.Arbitrary.Message: arbitraryBlockTxn :: Network -> Ctx -> Gen BlockTxn
+ Haskoin.Util.Arbitrary.Message: arbitraryBlockTxn :: Network -> Gen BlockTxn
- Haskoin.Util.Arbitrary.Message: arbitraryCompactBlock :: Network -> Ctx -> Gen CompactBlock
+ Haskoin.Util.Arbitrary.Message: arbitraryCompactBlock :: Network -> Gen CompactBlock
- Haskoin.Util.Arbitrary.Message: arbitraryMessage :: Network -> Ctx -> Gen Message
+ Haskoin.Util.Arbitrary.Message: arbitraryMessage :: Network -> Gen Message
- Haskoin.Util.Arbitrary.Script: arbitraryMSInput :: Network -> Ctx -> Gen ScriptInput
+ Haskoin.Util.Arbitrary.Script: arbitraryMSInput :: Network -> Gen ScriptInput
- Haskoin.Util.Arbitrary.Script: arbitraryMSOutput :: Ctx -> Gen ScriptOutput
+ Haskoin.Util.Arbitrary.Script: arbitraryMSOutput :: Gen ScriptOutput
- Haskoin.Util.Arbitrary.Script: arbitraryMSOutputC :: Ctx -> Gen ScriptOutput
+ Haskoin.Util.Arbitrary.Script: arbitraryMSOutputC :: Gen ScriptOutput
- Haskoin.Util.Arbitrary.Script: arbitraryMulSigSHInput :: Network -> Ctx -> Gen ScriptInput
+ Haskoin.Util.Arbitrary.Script: arbitraryMulSigSHInput :: Network -> Gen ScriptInput
- Haskoin.Util.Arbitrary.Script: arbitraryMulSigSHInputC :: Network -> Ctx -> Gen ScriptInput
+ Haskoin.Util.Arbitrary.Script: arbitraryMulSigSHInputC :: Network -> Gen ScriptInput
- Haskoin.Util.Arbitrary.Script: arbitraryMulSigSHInputFull :: Network -> Ctx -> Gen ScriptInput
+ Haskoin.Util.Arbitrary.Script: arbitraryMulSigSHInputFull :: Network -> Gen ScriptInput
- Haskoin.Util.Arbitrary.Script: arbitraryMulSigSHInputFullC :: Network -> Ctx -> Gen ScriptInput
+ Haskoin.Util.Arbitrary.Script: arbitraryMulSigSHInputFullC :: Network -> Gen ScriptInput
- Haskoin.Util.Arbitrary.Script: arbitraryP2SHMSOutput :: Ctx -> Gen ScriptOutput
+ Haskoin.Util.Arbitrary.Script: arbitraryP2SHMSOutput :: Gen ScriptOutput
- Haskoin.Util.Arbitrary.Script: arbitraryP2SHMSOutputC :: Ctx -> Gen ScriptOutput
+ Haskoin.Util.Arbitrary.Script: arbitraryP2SHMSOutputC :: Gen ScriptOutput
- Haskoin.Util.Arbitrary.Script: arbitraryPKHashInput :: Network -> Ctx -> Gen ScriptInput
+ Haskoin.Util.Arbitrary.Script: arbitraryPKHashInput :: Network -> Gen ScriptInput
- Haskoin.Util.Arbitrary.Script: arbitraryPKHashInputFull :: Network -> Ctx -> Gen ScriptInput
+ Haskoin.Util.Arbitrary.Script: arbitraryPKHashInputFull :: Network -> Gen ScriptInput
- Haskoin.Util.Arbitrary.Script: arbitraryPKHashInputFullC :: Network -> Ctx -> Gen ScriptInput
+ Haskoin.Util.Arbitrary.Script: arbitraryPKHashInputFullC :: Network -> Gen ScriptInput
- Haskoin.Util.Arbitrary.Script: arbitraryPKInput :: Network -> Ctx -> Gen ScriptInput
+ Haskoin.Util.Arbitrary.Script: arbitraryPKInput :: Network -> Gen ScriptInput
- Haskoin.Util.Arbitrary.Script: arbitraryPKOutput :: Ctx -> Gen ScriptOutput
+ Haskoin.Util.Arbitrary.Script: arbitraryPKOutput :: Gen ScriptOutput
- Haskoin.Util.Arbitrary.Script: arbitrarySHInput :: Network -> Ctx -> Gen ScriptInput
+ Haskoin.Util.Arbitrary.Script: arbitrarySHInput :: Network -> Gen ScriptInput
- Haskoin.Util.Arbitrary.Script: arbitraryScriptInput :: Network -> Ctx -> Gen ScriptInput
+ Haskoin.Util.Arbitrary.Script: arbitraryScriptInput :: Network -> Gen ScriptInput
- Haskoin.Util.Arbitrary.Script: arbitraryScriptOutput :: Network -> Ctx -> Gen ScriptOutput
+ Haskoin.Util.Arbitrary.Script: arbitraryScriptOutput :: Network -> Gen ScriptOutput
- Haskoin.Util.Arbitrary.Script: arbitrarySimpleInput :: Network -> Ctx -> Gen ScriptInput
+ Haskoin.Util.Arbitrary.Script: arbitrarySimpleInput :: Network -> Gen ScriptInput
- Haskoin.Util.Arbitrary.Script: arbitrarySimpleOutput :: Ctx -> Gen ScriptOutput
+ Haskoin.Util.Arbitrary.Script: arbitrarySimpleOutput :: Gen ScriptOutput
- Haskoin.Util.Arbitrary.Script: arbitraryTxSignature :: Network -> Ctx -> Gen (TxHash, SecKey, TxSignature)
+ Haskoin.Util.Arbitrary.Script: arbitraryTxSignature :: Network -> Gen (TxHash, SecKey, TxSignature)
- Haskoin.Util.Arbitrary.Script: arbitraryTxSignatureEmpty :: Network -> Ctx -> Gen TxSignature
+ Haskoin.Util.Arbitrary.Script: arbitraryTxSignatureEmpty :: Network -> Gen TxSignature
- Haskoin.Util.Arbitrary.Transaction: arbitraryAddrOnlyTx :: Network -> Ctx -> Gen Tx
+ Haskoin.Util.Arbitrary.Transaction: arbitraryAddrOnlyTx :: Network -> Gen Tx
- Haskoin.Util.Arbitrary.Transaction: arbitraryAddrOnlyTxFull :: Network -> Ctx -> Gen Tx
+ Haskoin.Util.Arbitrary.Transaction: arbitraryAddrOnlyTxFull :: Network -> Gen Tx
- Haskoin.Util.Arbitrary.Transaction: arbitraryAddrOnlyTxIn :: Network -> Ctx -> Gen TxIn
+ Haskoin.Util.Arbitrary.Transaction: arbitraryAddrOnlyTxIn :: Network -> Gen TxIn
- Haskoin.Util.Arbitrary.Transaction: arbitraryAddrOnlyTxInFull :: Network -> Ctx -> Gen TxIn
+ Haskoin.Util.Arbitrary.Transaction: arbitraryAddrOnlyTxInFull :: Network -> Gen TxIn
- Haskoin.Util.Arbitrary.Transaction: arbitraryAddrOnlyTxOut :: Network -> Ctx -> Gen TxOut
+ Haskoin.Util.Arbitrary.Transaction: arbitraryAddrOnlyTxOut :: Network -> Gen TxOut
- Haskoin.Util.Arbitrary.Transaction: arbitraryAnyInput :: Network -> Ctx -> Bool -> Gen (SigInput, PrivateKey)
+ Haskoin.Util.Arbitrary.Transaction: arbitraryAnyInput :: Network -> Bool -> Gen (SigInput, PrivateKey)
- Haskoin.Util.Arbitrary.Transaction: arbitraryAnyInputOf :: Gen (PrivateKey, PublicKey) -> Network -> Ctx -> Bool -> Gen (SigInput, PrivateKey)
+ Haskoin.Util.Arbitrary.Transaction: arbitraryAnyInputOf :: Gen (PrivateKey, PublicKey) -> Network -> Bool -> Gen (SigInput, PrivateKey)
- Haskoin.Util.Arbitrary.Transaction: arbitraryEmptyTx :: Network -> Ctx -> Gen Tx
+ Haskoin.Util.Arbitrary.Transaction: arbitraryEmptyTx :: Network -> Gen Tx
- Haskoin.Util.Arbitrary.Transaction: arbitraryLegacyTx :: Network -> Ctx -> Gen Tx
+ Haskoin.Util.Arbitrary.Transaction: arbitraryLegacyTx :: Network -> Gen Tx
- Haskoin.Util.Arbitrary.Transaction: arbitraryMSSigInput :: Network -> Ctx -> Gen (SigInput, [PrivateKey])
+ Haskoin.Util.Arbitrary.Transaction: arbitraryMSSigInput :: Network -> Gen (SigInput, [PrivateKey])
- Haskoin.Util.Arbitrary.Transaction: arbitraryMSSigInputOf :: Gen (Int, Int) -> Network -> Ctx -> Gen (SigInput, [PrivateKey])
+ Haskoin.Util.Arbitrary.Transaction: arbitraryMSSigInputOf :: Gen (Int, Int) -> Network -> Gen (SigInput, [PrivateKey])
- Haskoin.Util.Arbitrary.Transaction: arbitraryOutputsWithin :: Network -> Ctx -> Word64 -> Int -> Gen [TxOut]
+ Haskoin.Util.Arbitrary.Transaction: arbitraryOutputsWithin :: Network -> Word64 -> Int -> Gen [TxOut]
- Haskoin.Util.Arbitrary.Transaction: arbitraryPKHashSigInput :: Network -> Ctx -> Gen (SigInput, PrivateKey)
+ Haskoin.Util.Arbitrary.Transaction: arbitraryPKHashSigInput :: Network -> Gen (SigInput, PrivateKey)
- Haskoin.Util.Arbitrary.Transaction: arbitraryPKSigInput :: Network -> Ctx -> Gen (SigInput, PrivateKey)
+ Haskoin.Util.Arbitrary.Transaction: arbitraryPKSigInput :: Network -> Gen (SigInput, PrivateKey)
- Haskoin.Util.Arbitrary.Transaction: arbitraryPartialTxs :: Network -> Ctx -> Gen ([Tx], [(ScriptOutput, Word64, OutPoint, Int, Int)])
+ Haskoin.Util.Arbitrary.Transaction: arbitraryPartialTxs :: Network -> Gen ([Tx], [(ScriptOutput, Word64, OutPoint, Int, Int)])
- Haskoin.Util.Arbitrary.Transaction: arbitraryPsbt :: Network -> Ctx -> Gen Psbt
+ Haskoin.Util.Arbitrary.Transaction: arbitraryPsbt :: Network -> Gen Psbt
- Haskoin.Util.Arbitrary.Transaction: arbitrarySHSigInput :: Network -> Ctx -> Gen (SigInput, [PrivateKey])
+ Haskoin.Util.Arbitrary.Transaction: arbitrarySHSigInput :: Network -> Gen (SigInput, [PrivateKey])
- Haskoin.Util.Arbitrary.Transaction: arbitrarySigInput :: Network -> Ctx -> Gen (SigInput, [PrivateKey])
+ Haskoin.Util.Arbitrary.Transaction: arbitrarySigInput :: Network -> Gen (SigInput, [PrivateKey])
- Haskoin.Util.Arbitrary.Transaction: arbitrarySigningData :: Network -> Ctx -> Gen (Tx, [SigInput], [PrivateKey])
+ Haskoin.Util.Arbitrary.Transaction: arbitrarySigningData :: Network -> Gen (Tx, [SigInput], [PrivateKey])
- Haskoin.Util.Arbitrary.Transaction: arbitraryTaprootSigInput :: Network -> Ctx -> Gen (SigInput, PrivateKey)
+ Haskoin.Util.Arbitrary.Transaction: arbitraryTaprootSigInput :: Network -> Gen (SigInput, PrivateKey)
- Haskoin.Util.Arbitrary.Transaction: arbitraryTx :: Network -> Ctx -> Gen Tx
+ Haskoin.Util.Arbitrary.Transaction: arbitraryTx :: Network -> Gen Tx
- Haskoin.Util.Arbitrary.Transaction: arbitraryTxIn :: Network -> Ctx -> Gen TxIn
+ Haskoin.Util.Arbitrary.Transaction: arbitraryTxIn :: Network -> Gen TxIn
- Haskoin.Util.Arbitrary.Transaction: arbitraryTxOut :: Network -> Ctx -> Gen TxOut
+ Haskoin.Util.Arbitrary.Transaction: arbitraryTxOut :: Network -> Gen TxOut
- Haskoin.Util.Arbitrary.Transaction: arbitraryWLTx :: Network -> Ctx -> Bool -> Gen Tx
+ Haskoin.Util.Arbitrary.Transaction: arbitraryWLTx :: Network -> Bool -> Gen Tx
- Haskoin.Util.Arbitrary.Transaction: arbitraryWPKHSigInput :: Network -> Ctx -> Gen (SigInput, PrivateKey)
+ Haskoin.Util.Arbitrary.Transaction: arbitraryWPKHSigInput :: Network -> Gen (SigInput, PrivateKey)
- Haskoin.Util.Arbitrary.Transaction: arbitraryWSHSigInput :: Network -> Ctx -> Gen (SigInput, [PrivateKey])
+ Haskoin.Util.Arbitrary.Transaction: arbitraryWSHSigInput :: Network -> Gen (SigInput, [PrivateKey])
- Haskoin.Util.Arbitrary.Transaction: arbitraryWitnessTx :: Network -> Ctx -> Gen Tx
+ Haskoin.Util.Arbitrary.Transaction: arbitraryWitnessTx :: Network -> Gen Tx

Files

CHANGELOG.md view
@@ -5,22 +5,316 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [2.0.0] - 2026-11-15++This release breaks backwards compatibility on purpose: the secp256k1 context+is gone from the whole API.++### Changed++- **No function takes a `Ctx` any more.** secp256k1-haskell 3.0.0 creates and+  randomizes one context inside the library, on first use, and shares it+  between all threads. Every function of Haskoin Core that took a `Ctx` lost+  that argument and kept the order of the others: `derivePublicKey key`,+  `pubKeyAddr public`, `outputAddress net output`, `signTx net tx inputs keys`,+  `signPsbt net (keySigner key) psbt`, and so on through keys, addresses,+  scripts, transactions, PSBT, Taproot and the bloom filter. The generators of+  `Haskoin.Util.Arbitrary` lost it as well.+- **`PublicKey`, `Sig`, `ScriptOutput` and `XOnlyPubKey` are ordinary `Serial`,+  `Binary`, `Serialize`, `ToJSON` and `FromJSON` instances**, like `Tx` and+  `OutPoint`, instead of `Marshal Ctx` and `MarshalJSON Ctx` instances.+  `SigInput` is a `ToJSON` and `FromJSON` instance instead of a+  `MarshalJSON Ctx` one. The bytes and the JSON are the same as before.+- **`XPubKey`, `TxSignature` and `ScriptInput` take a `Network`** where they+  took a `(Network, Ctx)` pair: `marshal net xpub`, `unmarshalValue net value`.+  The bytes and the JSON are the same as before.+- Requires secp256k1-haskell 3.0. With it, `show` of a `SecKey` prints+  `SecKey <redacted>` and is no longer the inverse of `read`. `PrivateKey` and+  `XPrvKey` already hid their secret.+- **Transactions, blocks, headers, outpoints and addresses are written and+  read through cereal several times faster, and hashed in half the time.**+  No byte and no error message changed, and no exported name.++  The serializers are written for any monad, and GHC already compiled them+  for the monads of cereal: they did not run through a class dictionary.+  The time went into those monads themselves. Cereal writes through a+  builder, one closure for each field, into a first buffer of 4 kB that it+  then copies, and reads through continuations. A transaction of 387 bytes+  cost 10.7 kB of memory to write and 7.2 kB to read. A hash cost more+  memory than time: the pure interface of crypton allocated 1.5 kB for each+  round of SHA-256.++  The `Serialize` instances of `Tx`, `TxIn`, `BlockHeader` and `Block` now+  run the same serializers on a buffer directly, with the new module+  `Haskoin.Util.Direct`: once to count the bytes, once to write them into a+  buffer of that length, and to read, at a position in the bytes at hand.+  Those of `TxOut`, `OutPoint` and `Address` read that way, and still write+  through the builder, which is cheaper for two or three fields.+  `encodeSerial`, `decodeSerial`, `decodeTx`, `txHash`, `txWitnessHash`,+  `nosigTxHash`, `headerHash`, `txWeight` and `txVirtualSize` use the module+  too, and so do `getMessage` and `putMessage` for the payload of a `block`+  or a `tx` message. `txWeight` counts and writes nothing. `sha256` and+  `doubleSHA256` call the C code of crypton on memory that they hold for the+  call. A hash is read with one copy where it took two.++  What did not change: the `Serial` instances, so `runPutS . serialize` and+  `runGetS deserialize` cost about what they did, and the `Binary`+  instances. Binary reads a transaction in under half the time all the+  same: the helpers that read a list are now `INLINEABLE`, and for binary+  they had been running through a class dictionary. Use `encodeSerial` and+  `decodeSerial`, or cereal, where speed matters. `encode` of cereal still+  allocates its buffer of 4 kB, about 200 ns, before the first byte:+  `encodeSerial` does not, and is ten times as fast as `encode` for a value+  of a few bytes.++  One thing is slower. When bytes do not parse, they are read twice:+  directly, and then by cereal, which reports the error. The one case that+  was measured is a script that does not parse, in the table of+  `scriptToAddressBS` below: it takes a sixth longer than it did.++  The timings are from the benchmark of this package, built with GHC 9.12.4+  on an AMD Ryzen 9 3900X at `-O1` and at `-O2`, before this change and+  after it. Each is the lower of two runs, in nanoseconds. A timing moves by+  about a tenth from one run to the next. The memory is what one call+  allocates at `-O2`, which does not move, and is about the same at `-O1`.++  | ns | before `-O1` | now `-O1` | before `-O2` | now `-O2` | allocated before | now |+  | --- | ---: | ---: | ---: | ---: | ---: | ---: |+  | `encode` of a SegWit transaction of 387 bytes | 1,640 | 503 | 1,580 | 521 | 11 kB | 5.5 kB |+  | `decode` of it | 1,050 | 520 | 1,030 | 422 | 7.2 kB | 2.2 kB |+  | `encodeSerial` of it | 1,630 | 189 | 1,640 | 181 | 11 kB | 502 B |+  | `decodeSerial` of it | 1,060 | 507 | 1,100 | 410 | 7.2 kB | 2.1 kB |+  | `runPutS . serialize` of it | 1,640 | 1,530 | 1,650 | 1,550 | 11 kB | 10 kB |+  | `runGetS deserialize` of it | 1,060 | 966 | 1,030 | 984 | 7.2 kB | 6.7 kB |+  | `encode` of it through binary | 1,600 | 1,510 | 1,700 | 1,560 | 11 kB | 10 kB |+  | `decode` of it through binary | 1,700 | 745 | 1,630 | 579 | 6.4 kB | 3.7 kB |+  | `encode` of a block of 3,000 transactions, 1.1 MB | 5,287,000 | 520,000 | 5,026,000 | 496,000 | 20.1 MB | 1.2 MB |+  | `decode` of it | 5,073,000 | 1,984,000 | 5,793,000 | 1,619,000 | 21.7 MB | 6.7 MB |+  | `getMessage` of it, checksum included | 8,945,000 | 5,834,000 | 9,233,000 | 5,663,000 | 22.9 MB | 8.2 MB |+  | `putMessage` of it, checksum included | 9,048,000 | 4,395,000 | 8,778,000 | 4,837,000 | 21.4 MB | 2.4 MB |+  | `txHash` of the SegWit transaction | 2,960 | 1,060 | 2,870 | 1,070 | 11 kB | 712 B |+  | `txWitnessHash` of it | 4,370 | 1,950 | 4,380 | 1,960 | 14 kB | 927 B |+  | `txWeight` of it | 2,730 | 85 | 2,740 | 75 | 19 kB | 0 B |+  | `txHash` of the 3,000 transactions | 10,477,000 | 3,909,000 | 10,916,000 | 4,113,000 | 35.0 MB | 2.5 MB |+  | `headerHash` | 1,910 | 811 | 1,930 | 817 | 8.5 kB | 600 B |+  | `doubleSHA256` of 387 bytes | 2,430 | 1,680 | 2,520 | 1,690 | 3.4 kB | 433 B |+  | `decode` of an `OutPoint` | 59 | 26 | 55 | 18 | 407 B | 151 B |+  | `encodeSerial` of an `OutPoint` | 236 | 24 | 256 | 21 | 4.7 kB | 119 B |+  | `decodeSerial` of an `OutPoint` | 69 | 11 | 63 | 11 | 431 B | 87 B |+  | `decode` of a `TxHash` | 42 | 20 | 38 | 17 | 279 B | 135 B |+  | `encodeSerial` of a `TxHash` | 235 | 26 | 208 | 20 | 4.6 kB | 95 B |+  | `decode` of a `BlockHeader` | 122 | 42 | 120 | 38 | 911 B | 303 B |+  | `decode` of a P2WSH `Address` | 59 | 25 | 56 | 20 | 431 B | 159 B |++- Requires bytestring 0.11 or later, for the layout of a `ByteString` that+  `Haskoin.Util.Direct` reads.++### Added++- `Haskoin.Util.Direct`, the module behind the entry above, for the types of+  other packages. `encodeDirect`, `decodeDirect` and `sizeDirect` take a+  serializer written for any `MonadPut` or `MonadGet` and give what+  `runPutS` and `runGetS` give, or the length of it. `putDirect` and+  `getDirect` do the same inside cereal, for the `put` and `get` of a+  `Serialize` instance. `putShortBytes` and `getShortBytes` write and read a+  short byte string with one copy. When bytes do not parse, the parser runs+  again through cereal, which reports the error: a failure costs a little+  more than it did, and its message is the same. `import Haskoin` does not+  bring the module in.+- The `Serial` methods of the types above, and of `VarInt`, `Script`,+  `ScriptOp`, `ScriptOutput`, `PublicKey`, `Sig` and `XOnlyPubKey`, are+  `INLINEABLE`, and so are the helpers `putList`, `getList`, `putMaybe`,+  `getMaybe`, `putLengthBytes`, `getLengthBytes`, `putIntMap`, `getIntMap`,+  `putInteger`, `getInteger` and the `VarInt` ones. A package that writes its+  own records with them can have GHC compile the lot for+  `Haskoin.Util.Direct`.+- The group `serial` of the benchmark suite, which times all of this and+  shows the memory that each call allocates.+- `encodeSerial` and `decodeSerial` in `Haskoin.Util.Marshal`, for the types+  that are now `Serial`. `encodeSerial` gives the bytes of+  `runPutS . serialize`. `decodeSerial` reads a value from bytes that hold+  it and nothing else, and fails on bytes left over, as `unmarshal` did for+  these types. Plain `runGetS deserialize` accepts a value followed by junk.+- A benchmark suite, `bench/Bench.hs`, run with `stack bench`. It times hex,+  `scriptToAddressBS`, the text of an address, the JSON of a transaction and+  Base58, most of them next to a copy of what 1.6.0 did, and prints the ratio.+  The README says how to run it at `-O1` and at `-O2`. CI compiles it. Every+  timing in this entry comes from it.++### Fixed++A [report on 1.6.4](https://gist.github.com/tzwierzbicki/90c429e2fb829777cac7e5f27b07a601)+compared it with 1.6.0. It found that 1.6.3 and 1.6.4, two releases made for+speed, had made some paths slower, and that figures in this file did not hold.+Its main findings were reproduced on another machine, and they are fixed+here. The entries of 1.6.3 and 1.6.4 below are corrected, each with a note+that says what was changed.++The timings below are from an AMD Ryzen 9 3900X with GHC 9.12.4. Versions+1.6.0 and 1.6.4 were built from their tags and this one from its source, each+at `-O1` and at `-O2`, and all ran the same benchmark. `-O1` is the level the+package is built at unless the user asks for another. Each figure is the lower+of two runs. A timing moves by about a tenth from one run to the next, so a+difference smaller than that between two columns means nothing.++- **`hexBuilder` and `hexEncoding` are as fast as in 1.6.0 again.** They are+  `lazyByteStringHex` of bytestring, as they were. Version 1.6.4 wrote chunks+  of 256 bytes and more with a loop of its own, into a new string that it then+  gave to the builder. The builder already looks its digits up in a table and+  writes them straight into its buffer, so the loop only added work: 1.6 times+  the time on a megabyte at `-O2`, and 5.3 times at `-O1`.++  | `hexBuilder`, µs | 1.6.0 `-O1` | 1.6.4 `-O1` | 2.0.0 `-O1` | 1.6.0 `-O2` | 1.6.4 `-O2` | 2.0.0 `-O2` |+  | --- | ---: | ---: | ---: | ---: | ---: | ---: |+  | 32 bytes | 0.24 | 0.30 | 0.22 | 0.23 | 0.28 | 0.21 |+  | 250 bytes | 0.47 | 0.52 | 0.47 | 0.42 | 0.54 | 0.41 |+  | 1,000 bytes | 1.03 | 3.63 | 0.98 | 1.01 | 1.46 | 1.01 |+  | 1,000,000 bytes | 548 | 2,888 | 523 | 529 | 832 | 558 |+  | 1,000,000 bytes, in the chunks of `runPutL` | 529 | 2,859 | 550 | 548 | 852 | 574 |+  | 1,000,000 bytes, in chunks of 100 | 728 | 1,251 | 786 | 712 | 1,261 | 721 |++- **The JSON of a transaction is faster than in 1.6.0.** Version 1.6.4 was+  slower than 1.6.0 for a SegWit transaction, and at `-O1` for one with long+  multisig inputs. The loss came from `hexEncoding` and is gone. The gain of+  1.6.4 on hashes is kept.++  | `toEncoding`, µs | 1.6.0 `-O1` | 1.6.4 `-O1` | 2.0.0 `-O1` | 1.6.0 `-O2` | 1.6.4 `-O2` | 2.0.0 `-O2` |+  | --- | ---: | ---: | ---: | ---: | ---: | ---: |+  | legacy transaction, 2 inputs, 2 outputs | 4.15 | 3.87 | 3.21 | 3.90 | 3.60 | 3.30 |+  | SegWit transaction, 2 inputs, 2 outputs | 4.25 | 4.89 | 3.43 | 4.22 | 4.66 | 3.45 |+  | 2 multisig inputs of 254 and 296 bytes | 4.37 | 5.21 | 3.56 | 4.43 | 4.20 | 3.58 |+  | 100 inputs, 100 outputs | 151 | 137 | 104 | 141 | 127 | 106 |+  | `TxHash` | 0.51 | 0.32 | 0.23 | 0.50 | 0.26 | 0.23 |+  | `BlockHeader` | 1.53 | 1.20 | 1.07 | 1.47 | 1.03 | 1.10 |++- **`encodeHex`, `encodeHexBytes`, `encodeHexLazy`, `encodeHexReversed` and+  the JSON of a hash are about as fast at `-O1` as at `-O2`.** The loop of 1.6.4+  kept its table of digits in a `ByteString`. GHC found where the table was+  once, before the loop, only at `-O2`. At `-O1` it looked again for every+  byte, and `encodeHex` was slower than the base16 it had replaced. The loop+  now writes each pair of digits with `word8HexFixed` of bytestring, whose+  table is a literal. No compiler option is needed to get this speed.++  | ns | 1.6.0 `-O1` | 1.6.4 `-O1` | 2.0.0 `-O1` | 1.6.0 `-O2` | 1.6.4 `-O2` | 2.0.0 `-O2` |+  | --- | ---: | ---: | ---: | ---: | ---: | ---: |+  | `encodeHex`, 32 bytes | 132 | 143 | 67 | 123 | 74 | 58 |+  | `encodeHex`, 250 bytes | 663 | 859 | 289 | 653 | 358 | 275 |+  | `encodeHex`, 1,000 bytes | 2,378 | 3,223 | 873 | 2,441 | 1,178 | 856 |+  | `encodeHex`, 1,000,000 bytes | 2,289,110 | 3,064,763 | 701,903 | 2,362,564 | 992,927 | 699,730 |+  | `txHashToHex` | 415 | 149 | 65 | 379 | 73 | 59 |++- **`scriptToAddressBS` is faster than 1.6.0 for every script.** Versions+  1.6.3 and 1.6.4 read the four usual kinds by their bytes and were much+  faster for them, but took nearly twice as long as 1.6.0 for every other+  script: Taproot, `OP_RETURN`, and all that has no address. Removing the+  context, earlier in this release, had brought those back to the time of+  1.6.0. That time was itself long, because the parser ran through a class+  dictionary. `decodeSerial` is now inlined where it is called, so the parser+  that GHC compiled for the type is the one that runs, and it reads the+  script where it is, with `Haskoin.Util.Direct`, instead of through the+  continuations of cereal. A Taproot output takes a tenth of the time it took+  in 1.6.0, and an eighteenth of the time it took in 1.6.4. A script that+  does not parse is read twice, directly and then by cereal for the text of+  the error, and takes a sixth longer than cereal alone took. The answers+  are the same, and so is the text of every `Left`.++  | `scriptToAddressBS`, ns | 1.6.0 `-O1` | 1.6.4 `-O1` | 2.0.0 `-O1` | 1.6.0 `-O2` | 1.6.4 `-O2` | 2.0.0 `-O2` |+  | --- | ---: | ---: | ---: | ---: | ---: | ---: |+  | P2PKH | 1,613 | 66 | 27 | 1,549 | 67 | 25 |+  | P2SH | 1,111 | 68 | 28 | 1,105 | 70 | 25 |+  | P2WPKH | 934 | 70 | 31 | 892 | 75 | 29 |+  | P2WSH | 936 | 59 | 18 | 892 | 64 | 17 |+  | Taproot | 901 | 1,595 | 86 | 868 | 1,585 | 82 |+  | witness version 2, 20 bytes | 914 | 1,581 | 85 | 872 | 1,521 | 82 |+  | `OP_RETURN`, 20 bytes | 940 | 1,635 | 136 | 920 | 1,576 | 128 |+  | `OP_RETURN`, 80 bytes | 973 | 1,797 | 127 | 963 | 1,649 | 118 |+  | P2SH32 on Bitcoin Cash | 1,152 | 1,826 | 80 | 1,110 | 1,786 | 72 |+  | P2WPKH form on Bitcoin Cash | 983 | 1,695 | 113 | 960 | 1,613 | 109 |+  | empty script | 776 | 979 | 668 | 782 | 929 | 713 |+  | non-standard script | 2,390 | 3,259 | 1,119 | 2,352 | 3,174 | 1,122 |+  | pay to public key | 5,253 | 6,178 | 4,248 | 5,133 | 5,958 | 4,320 |+  | multisig 2 of 3 | 14,869 | 16,663 | 13,069 | 14,762 | 15,898 | 13,364 |++- **`encodeBase58` is faster than 1.6.0 at every length.** The limbs of 1.6.3+  were faster for an address and slower than 1.6.0 from about 500 bytes up.+  The bytes are now read into one number eight at a time, and the number is+  divided by 58^10, the largest power of 58 that fits in a machine word, so+  that each division of the big number gives ten digits. Nothing in Bitcoin+  encodes more than the 82 bytes of an extended key, so the long lengths+  matter only to a caller with data of its own.++  | `encodeBase58`, µs | 1.6.0 `-O1` | 1.6.4 `-O1` | 2.0.0 `-O1` | 1.6.0 `-O2` | 1.6.4 `-O2` | 2.0.0 `-O2` |+  | --- | ---: | ---: | ---: | ---: | ---: | ---: |+  | 25 bytes | 4.31 | 1.61 | 1.49 | 3.91 | 1.57 | 1.45 |+  | 82 bytes | 15.88 | 8.00 | 5.12 | 14.70 | 7.82 | 5.09 |+  | 2,000 bytes | 1,687 | 2,623 | 216 | 1,679 | 2,598 | 209 |+  | 20,000 bytes | 144,478 | 264,988 | 11,462 | 132,856 | 255,077 | 11,387 |++### Removed++- `Ctx`, `withContext`, `createContext`, `randomizeContext` and+  `cloneContext`, which `Haskoin.Crypto` and `Haskoin` re-exported from+  secp256k1-haskell.+- `prepareContext` from `Haskoin.Util.Helpers`.+- The `Marshal Ctx` and `MarshalJSON Ctx` instances, and the `Show Ctx`+  instance of `Haskoin.Util.Arbitrary.Util`.++### Migrating++- Delete `withContext $ \ctx ->` or `createContext` at the start of the+  program, and delete the `ctx` argument at every call.+- Replace the marshalling calls that took a context:++  | Before                    | After                      |+  | ------------------------- | -------------------------- |+  | `marshal ctx x`           | `encodeSerial x`           |+  | `unmarshal ctx bytes`     | `decodeSerial bytes`       |+  | `marshalPut ctx x`        | `serialize x`              |+  | `marshalGet ctx`          | `deserialize`              |+  | `marshalValue ctx x`      | `toJSON x`                 |+  | `marshalEncoding ctx x`   | `toEncoding x`             |+  | `unmarshalValue ctx v`    | `parseJSON v`              |+  | `marshalJSON ctx x`       | `Data.Aeson.encode x`      |+  | `unmarshalJSON ctx json`  | `Data.Aeson.decode json`   |+  | `marshal (net, ctx) x`    | `marshal net x`            |+  | `unmarshalValue (net, ctx) v` | `unmarshalValue net v` |++- A type of your own that held a `Ctx` to encode a key can now derive or write+  plain `Serial` and `ToJSON` instances.+- In `stack.yaml`, name `haskoin-core-2.0.0` and `secp256k1-haskell-3.0.0`.+ ## [1.6.4] - 2026-11-14  ### Changed -- **Hex is written faster.** `encodeHex`, `encodeHexLazy`, `hexBuilder` and-  `hexEncoding` look up the two digits of each byte in a table. On a-  250-byte transaction, that is four times as fast as base16, which-  `encodeHex` used, and on a block of a megabyte, 1.5 times as fast as the-  builder of bytestring, which `hexBuilder` used. Short input inside a-  builder is still written by the builder's own hex, which is as fast-  there and allocates nothing.-- **Hashes of blocks and transactions are written five times as fast in-  JSON**: 78 ns where it took 390, straight from their bytes, without-  serializing and reversing them first. `txHashToHex`, `blockHashToHex`-  and the hashes in a block header gain too.+- **`encodeHex` and `encodeHexLazy` are faster when the package is built+  with `-O2`, and `hexBuilder` and `hexEncoding` are slower.** The four+  functions look up the two digits of each byte in a table. On a 250-byte+  transaction at `-O2`, `encodeHex` takes 358 ns where base16, which it used+  before, took 653. At `-O1`, the level the package is built at by default,+  it takes 859 ns where base16 took 663: it is slower. `hexBuilder` and+  `hexEncoding` use the same loop for chunks of 256 bytes and more, and are+  slower than the builder of bytestring that they used before, at every+  size: on a megabyte, 832 µs against 529 at `-O2`, and 2,888 µs against 548+  at `-O1`. Shorter chunks are still written by the builder's own hex.+  Version 2.0.0 fixes both.+- **Hashes of blocks and transactions are written faster**, straight from+  their bytes, without serializing and reversing them first. `txHashToHex`+  takes 73 ns where it took 379 at `-O2`, and 149 ns where it took 415 at+  `-O1`. The JSON encoding of a `TxHash`, run to bytes, takes 0.26 µs where+  it took 0.50 at `-O2`, and 0.32 µs where it took 0.51 at `-O1`.+  `blockHashToHex` and the hashes in a block header gain too. +*Corrected on 2026-11-15, after the report cited under 2.0.0. This entry+first said that hex was "four times as fast as base16" on a 250-byte+transaction, that on a megabyte `hexBuilder` was "1.5 times as fast as the+builder of bytestring", and that hashes were written "five times as fast in+JSON: 78 ns where it took 390". The second was wrong at both levels of+optimisation. The first is 1.8 times at `-O2` and a loss at `-O1`. The third+is right for `txHashToHex` at `-O2`; in JSON a hash is written twice as fast+at `-O2` and 1.6 times as fast at `-O1`. The figures above are from the+benchmark suite of 2.0.0, on the machine named there.*+ ### Added  - `encodeHexBytes`, the hex of bytes as the bytes of its digits.@@ -41,6 +335,18 @@     addresses take 60 ms where they took 81.   - `toBase32` reads five bits at a time from the bytes, and the Bech32     checksum has no lists: SegWit addresses take 50 ms where they took 81.++*Corrected on 2026-11-15, after the report cited under 2.0.0. The three+figures above held, in proportion, when measured again with the benchmark+suite of 2.0.0, at `-O1` and at `-O2`. But this entry left out two losses,+which 2.0.0 fixes:*++- *`scriptToAddressBS` got slower for every script that is not one of the+  four kinds, such as a Taproot output or an `OP_RETURN`. A Taproot output+  takes 1,595 ns where 1.6.2 took 944, at `-O1`.*+- *`encodeBase58` got slower for long input. At 2,000 bytes it takes 2.6 ms+  where 1.6.2 took 0.7, and it is slower than 1.6.0 from about 500 bytes up.+  Nothing in Bitcoin is that long.*  ## [1.6.2] - 2026-11-12 
README.md view
@@ -115,9 +115,9 @@ ```yaml resolver: nightly-2026-10-28 extra-deps:-  - haskoin-core-1.6.4+  - haskoin-core-2.0.0   - base16-2.0-  - secp256k1-haskell-2.0.1+  - secp256k1-haskell-3.0.0 ```  ## Quick start@@ -139,15 +139,15 @@ mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"  main :: IO ()-main = withContext $ \ctx -> do+main = do   seed <- either fail pure (mnemonicToSeed "" mnemonic)   let master = makeXPrvKey seed       -- Hardened steps need the private key.-      account = derivePath ctx ("m/84'/0'/0'" :: HardPath) master-      accountPub = deriveXPubKey ctx account+      account = derivePath ("m/84'/0'/0'" :: HardPath) master+      accountPub = deriveXPubKey account       -- The remaining steps only need the public key.-      receiving = derivePubPath ctx ("m/0" :: SoftPath) accountPub-      (address, _publicKey) = deriveWitnessAddr ctx receiving 0+      receiving = derivePubPath ("m/0" :: SoftPath) accountPub+      (address, _publicKey) = deriveWitnessAddr receiving 0   print (addrToText btc address)   -- => Just "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu" ```@@ -160,17 +160,18 @@ A few conventions apply across the whole library. Reading this section first will save you time. -### The context+### No context to pass -Most cryptographic functions take a `Ctx`, a secp256k1 context. Create one when-your program starts, with `withContext` or `createContext`. Then pass it around.-You can share it between threads.+Signing, verifying and deriving keys are pure functions that take only their+data. The secp256k1 context that libsecp256k1 needs is created and randomized+once, inside secp256k1-haskell, the first time a function uses it, and is+shared by every thread. Up to version 1.6 most functions took that context as+an argument. From 2.0.0 none does, and there is nothing to create or pass around.  ### Networks  A `Network` is a record of the parameters of one chain. Functions that depend on-the chain take one as an argument. Functions that need both take the `Network`-first and the `Ctx` second.+the chain take one as their first argument.  | Value        | Chain                 | Name for `netByName` | | ------------ | --------------------- | -------------------- |@@ -216,24 +217,53 @@  Most types have `Serial` instances, from the [bytes](https://hackage.haskell.org/package/bytes) package, and also `Binary` and-`Serialize` instances. Some types need a context or a network to encode, so they-have `Marshal` or `MarshalJSON` instances instead.+`Serialize` instances, and `ToJSON` and `FromJSON` instances for JSON. Public+keys, signatures and output scripts are among them. The encoding of some types+depends on the network, so they have `Marshal` or `MarshalJSON` instances+instead, which take the `Network` as their first argument. `XPrvKey`,+`XPubKey`, `PrivateKey`, `Address`, `TxSignature` and `ScriptInput` are those.  | Task                | Encode                     | Decode                       | | ------------------- | -------------------------- | ---------------------------- | | Binary              | `runPutS (serialize x)`    | `runGetS deserialize bytes`  |-| Binary with context | `marshal ctx x`            | `unmarshal ctx bytes`        |+| Binary, whole input | `encodeSerial x`           | `decodeSerial bytes`         |+| Binary with network | `marshal net x`            | `unmarshal net bytes`        | | Hexadecimal         | `encodeHex bytes`          | `decodeHex text`             | | JSON                | `toJSON x`                 | `parseJSON value`            |-| JSON with context   | `marshalJSON ctx x`        | `unmarshalJSON ctx json`     |+| JSON with network   | `marshalJSON net x`        | `unmarshalJSON net json`     | -The first argument depends on the type. For example, it is a `Ctx` for-`PublicKey`, a `Network` for `XPrvKey` and a `(Network, Ctx)` pair for `XPubKey`.+`decodeSerial` and `unmarshal` fail when bytes are left over after the value,+and `decodeTx` does the same for a transaction. `runGetS deserialize` reads a+value from the start of the bytes and ignores the rest. `encodeSerial x` gives+the bytes of `runPutS (serialize x)`. -`unmarshal` fails when bytes are left over after the value, and `decodeTx` does-the same for a transaction. `runGetS deserialize` reads a value from the start of-the bytes and ignores the rest.+**Which one is fast.** All of these give the same bytes, but not at the same+price. `encodeSerial` and `decodeSerial` are the cheapest: they write into one+buffer of the exact length and read the bytes where they are. `decode` of+cereal reads the same way for transactions, their inputs and outputs,+outpoints, block headers, blocks and addresses, and `encode` writes the same+way for transactions, inputs, headers and blocks. But `encode` first allocates+a buffer of 4 kB whatever the value, which is most of the cost of a value of a+few bytes. `runPutS (serialize x)` and `runGetS deserialize` go through the+builder and the continuations of cereal one field at a time, and are several+times slower on a transaction: keep them for a value that is part of a longer+stream. +The module `Haskoin.Util.Direct` has the functions behind this, for your own+types: give `encodeDirect`, `decodeDirect` or `sizeDirect` a serializer written+for any `MonadPut` or `MonadGet`, or write the `put` and `get` of a cereal+instance with `putDirect` and `getDirect`. They give what cereal gives, errors+included.++```haskell+instance Serialize Record where+  put record = putDirect (serialize record)+  get = getDirect deserialize+```++Mark the `serialize` and `deserialize` of such a type `INLINEABLE`, so that GHC+can compile them for the monads of that module.+ ### Hash byte order  `TxHash` and `BlockHash` show as hexadecimal in reversed byte order. This is the@@ -257,7 +287,7 @@ import Haskoin  main :: IO ()-main = withContext $ \ctx -> do+main = do   -- This is the public BIP-39 test mnemonic. Never send coins to it.   seed <-     either fail pure $@@ -299,21 +329,21 @@  -- True asks for the compressed form of the public key. let private = wrapSecKey True secret-    public = derivePublicKey ctx private+    public = derivePublicKey private  print private -- => PrivateKey {key = <redacted>, compress = True} print (toWif btc private) -- => "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn"-print (encodeHex (marshal ctx public))+print (encodeHex (encodeSerial public)) -- => "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"-print (addrToText btc (pubKeyAddr ctx public))+print (addrToText btc (pubKeyAddr public)) -- => Just "1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH"  -- Sign and verify a hash. let digest = doubleSHA256 bytes-    signature = signHash ctx secret digest-print (verifyHashSig ctx digest signature public.point)+    signature = signHash secret digest+print (verifyHashSig digest signature public.point) -- => True ``` @@ -328,15 +358,15 @@ Hardened steps can be written `'`, `h` or `H`.  ```haskell-let account = derivePath ctx ("m/84'/0'/0'" :: HardPath) master-    accountPub = deriveXPubKey ctx account+let account = derivePath ("m/84'/0'/0'" :: HardPath) master+    accountPub = deriveXPubKey account -print (xPubExport btc ctx accountPub)+print (xPubExport btc accountPub) -- => "xpub6CatWdiZiodmUeTDp8LT5or8nmbKNcuyvz7WyksVFkKB4RHwCD3XyuvPEbvqAQY3rAPshWcMLoP2fMFMKHPJ4ZeZXYVUhLv1VMrjPC7PW6V"  -- The account's public key derives all its receiving addresses.-let receiving = derivePubPath ctx ("m/0" :: SoftPath) accountPub-    addresses = [address | (address, _, _) <- deriveWitnessAddrs ctx receiving 0]+let receiving = derivePubPath ("m/0" :: SoftPath) accountPub+    addresses = [address | (address, _, _) <- deriveWitnessAddrs receiving 0] print (map (addrToText btc) (take 2 addresses)) -- => [Just "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu",Just "bc1qnjg0jd8228aq7egyzacy8cys3knf9xvrerkf9g"] ```@@ -370,7 +400,7 @@ -- => Nothing  -- The output script an address pays to.-print (encodeHex <$> (addressToScriptBS ctx =<< textToAddr btc text))+print (encodeHex <$> (addressToScriptBS =<< textToAddr btc text)) -- => Just "0014c0cebcd6c3d3ca8c75dc5ec62ebe55330ef910e2" ``` @@ -387,19 +417,19 @@ let keyA = wrapPubKey True "02ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f8"     keyB = wrapPubKey True "02fe6f0a5a297eb38c391581c4413e084773ea23954d93f7753db7dc0adc188b2f"     -- BIP-67 sorts the keys, so that all signers build the same script.-    multisig = sortMulSig ctx (PayMulSig [keyA, keyB] 2)+    multisig = sortMulSig (PayMulSig [keyA, keyB] 2)  -- The address can fail, because a P2SH redeem script holds at most 520 bytes.-print (addrToText btc <$> payToScriptAddress ctx multisig)+print (addrToText btc <$> payToScriptAddress multisig) -- => Right (Just "39bgKC7RFbpoCRbtD5KEdkYKtNyhpsNa3Z")  -- OP_RETURN is 6a, then the push of 5 bytes, then "hello".-print (encodeHex (marshal ctx (DataCarrier ["hello"])))+print (encodeHex (encodeSerial (DataCarrier ["hello"]))) -- => "6a0568656c6c6f"  -- Read the same bytes back. script <- maybe (fail "bad hex") pure (decodeHex "6a0568656c6c6f")-print (unmarshal ctx script :: Either String ScriptOutput)+print (decodeSerial script :: Either String ScriptOutput) -- => Right (DataCarrier {pushes = ["hello"]}) ``` @@ -419,28 +449,28 @@  ```haskell -- The key at m/84'/0'/0'/0/0 and its address.-let key = derivePath ctx ("m/84'/0'/0'/0/0" :: DerivPath) master-    address = xPubWitnessAddr ctx (deriveXPubKey ctx key)+let key = derivePath ("m/84'/0'/0'/0/0" :: DerivPath) master+    address = xPubWitnessAddr (deriveXPubKey key)  -- The coin to spend, and the transaction that paid it. Both are made up. -- The coin holds 100,000 satoshi. coinScript <- maybe (fail "no output script") pure (addressToOutput address) let amount = 100000     fundingInput = TxIn (OutPoint "1111111111111111111111111111111111111111111111111111111111111111" 0) "" 0xffffffff-    funding = Tx 2 [fundingInput] [TxOut amount (marshal ctx coinScript)] [] 0+    funding = Tx 2 [fundingInput] [TxOut amount (encodeSerial coinScript)] [] 0     coin = OutPoint (txHash funding) 0  -- Pay 99,000 satoshi. The 1,000 satoshi left over are the fee. unsigned <-   either fail pure $-    buildAddrTx btc ctx [coin] [("bc1qnjg0jd8228aq7egyzacy8cys3knf9xvrerkf9g", 99000)]+    buildAddrTx btc [coin] [("bc1qnjg0jd8228aq7egyzacy8cys3knf9xvrerkf9g", 99000)]  -- SigInput describes the coin. The last argument is the redeem script. signed <-   either fail pure $-    signTx btc ctx unsigned [SigInput coinScript amount coin sigHashAll Nothing] [key.key]+    signTx btc unsigned [SigInput coinScript amount coin sigHashAll Nothing] [key.key] -print (verifyStdTx btc ctx signed [(coinScript, amount, coin)])+print (verifyStdTx btc signed [(coinScript, amount, coin)]) -- => True print (txVirtualSize signed) -- => 110@@ -547,10 +577,10 @@  -- Signer: read the text, and sign every input the keys can sign. received <- either fail pure (decodePsbtBase64 shared)-signedPsbt <- either fail pure (signPsbt btc ctx (keySigner ctx key.key) received)+signedPsbt <- either fail pure (signPsbt btc (keySigner key.key) received)  -- Finalizer and extractor: check the signatures and build the transaction.-finalized <- either fail pure (finalizePsbt btc ctx signedPsbt)+finalized <- either fail pure (finalizePsbt btc signedPsbt) extracted <- either fail pure (psbtTransaction finalized)  -- RFC 6979 signatures are deterministic, so this is the same transaction.@@ -582,23 +612,23 @@ ### Taproot  ```haskell-let key = derivePath ctx ("m/86'/0'/0'/0/0" :: DerivPath) master-    internalKey = (deriveXPubKey ctx key).key+let key = derivePath ("m/86'/0'/0'/0/0" :: DerivPath) master+    internalKey = (deriveXPubKey key).key     -- Nothing means that the output has no script tree.-    output = taprootScriptOutput ctx (TaprootOutput internalKey Nothing)+    output = taprootScriptOutput (TaprootOutput internalKey Nothing) -print (addrToText btc =<< outputAddress btc ctx output)+print (addrToText btc =<< outputAddress btc output) -- => Just "bc1p5cyxnuxmeuwuvkwfem96lqzszd02n6xdcjrs20cac6yqjjwudpxqkedrcr"  -- Spend a made-up coin of 100,000 satoshi by its key path. let coin = OutPoint "1111111111111111111111111111111111111111111111111111111111111111" 0-    unsigned = buildTx ctx [coin] [(output, 99000)]+    unsigned = buildTx [coin] [(output, 99000)]  signed <-   either fail pure $-    signTx btc ctx unsigned [SigInput output 100000 coin sigHashDefault Nothing] [key.key]+    signTx btc unsigned [SigInput output 100000 coin sigHashDefault Nothing] [key.key] -print (verifyStdTx btc ctx signed [(output, 100000, coin)])+print (verifyStdTx btc signed [(output, 100000, coin)]) -- => True ``` @@ -655,8 +685,8 @@  ```haskell -- The BIP-44 coin type of Bitcoin Cash is 145.-let key = derivePath ctx ("m/44'/145'/0'/0/0" :: DerivPath) master-    address = xPubAddr ctx (deriveXPubKey ctx key)+let key = derivePath ("m/44'/145'/0'/0/0" :: DerivPath) master+    address = xPubAddr (deriveXPubKey key)  -- addrToText writes CashAddr on Bitcoin Cash. print (addrToText bch address)@@ -669,7 +699,7 @@ -- => True  -- SegWit addresses do not exist on Bitcoin Cash.-print (addrToText bch (xPubWitnessAddr ctx (deriveXPubKey ctx key)))+print (addrToText bch (xPubWitnessAddr (deriveXPubKey key))) -- => Nothing ``` @@ -749,7 +779,7 @@  ## Module overview -`import Haskoin` brings in everything below except the two modules marked as+`import Haskoin` brings in everything below except the modules marked as separate. It exports many short names, so you may prefer to import only the modules you need, or to import it qualified. @@ -763,6 +793,7 @@ | `Haskoin.Script`              | Scripts, standard templates and signature hashes                     | | `Haskoin.Transaction`         | Transaction types, builder, signing, SegWit, Taproot and PSBT        | | `Haskoin.Util`                | Hexadecimal helpers, `Marshal` and small utilities                   |+| `Haskoin.Util.Direct`         | Serializers run straight on a buffer (separate import)               | | `Haskoin.Util.Arbitrary`      | QuickCheck generators such as `arbitraryTx` (separate import)        |  ## Security notes@@ -774,7 +805,8 @@   `getEntropy` from the entropy package. Never use `System.Random`. - **Secrets in logs.** `PrivateKey` and `XPrvKey` show as `<redacted>` and have no   `Read` instance. `toWif` and `xPrvExport` write a key out on purpose. A bare-  `SecKey`, such as the `key` field of a `PrivateKey`, still shows its bytes. The+  `SecKey`, such as the `key` field of a `PrivateKey`, shows as+  `SecKey <redacted>` too, since secp256k1-haskell 3.0.0. The   errors of `fromMnemonic` and `mnemonicToSeed` name the position of a bad word,   never the word. - **Secrets in memory.** Keys live in the GHC heap. The library cannot wipe them,@@ -814,6 +846,67 @@  The tests are in `test/` and use [hspec](https://hspec.github.io/). The test vectors from the BIPs, Bitcoin Core and other implementations are in `data/`.++### Benchmarks++The benchmarks are in `bench/Bench.hs` and use+[tasty-bench](https://hackage.haskell.org/package/tasty-bench). They time the+functions that a server calls for every input and output it shows: hex,+`scriptToAddressBS`, the text of an address, the JSON of a transaction, and+Base58. The group `serial` times the binary encoding of hashes, outpoints,+transactions, headers, blocks and addresses, written and read through cereal,+through `runPutS` and `runGetS`, and through `encodeSerial` and `decodeSerial`,+and the hashing of transactions and headers.++```sh+stack bench                                                 # at -O1, as the package builds by default+stack bench --ghc-options -O2                               # at -O2+stack bench --benchmark-arguments '-p hexBuilder'           # one group+stack bench --benchmark-arguments '-p /All.serial/'         # the binary encodings+stack bench --benchmark-arguments '--csv before.csv'        # keep the timings+stack bench --benchmark-arguments '--baseline before.csv'   # compare with them+```++Each line shows the memory allocated next to the time. The time of an encoder+of a few bytes is mostly the time it takes to allocate, and the memory does+not move from one run to the next as the time does, so compare that first.++Run them at both levels. Most users build this package at `-O1`, so a change+that is only faster at `-O2` is not faster for them. Stack does not always+rebuild when only `--ghc-options` changes: add `--force-dirty` if the numbers+of the two levels look the same.++Most functions are timed next to a copy of what haskoin-core 1.6.0 did, kept+in the benchmark as a reference. The reference is the line `as in 1.6.0`, and+the function of the library is the line `now`, which ends with its time as a+multiple of the reference:++```+encodeHex+  250 B+    as in 1.6.0:                                           OK+      680  ns ±  55 ns+    now:                                                   OK+      310  ns ±  20 ns, 0.46x+```++Below `1.00x` the library is faster than the reference. `hexBuilder` and+`hexEncoding` are the same code as their reference, so their lines show how+much the timings move by themselves on your machine: about a tenth either way+on a desktop with other programs open. A line that stays above `1.00x` by+more than that, at either level, is a regression: fix it, or say in the+changelog why it is worth it.++Quote a timing in the changelog or in the documentation only with the level it+was measured at, and only after running it here. The entries of 1.6.3 and+1.6.4 in the changelog quoted timings that did not hold at `-O1`, and one that+did not hold at either level, which is why this suite exists.++A reference is a copy of the old code compiled into the benchmark, not the old+library. To time an old release itself, check out its tag, copy `bench/` and+the `benchmarks` section of `package.yaml` into it, and give+`scriptToAddressBS` and the functions around it the `Ctx` argument that+releases before 2.0.0 take.  ### Contributing 
Setup.hs view
@@ -1,2 +1,3 @@ import Distribution.Simple+ main = defaultMain
+ bench/Bench.hs view
@@ -0,0 +1,480 @@+{-# LANGUAGE ImportQualifiedPost #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- |+-- Module      : Main+-- Description : Benchmarks of the hot paths of a server+-- Copyright   : No rights reserved+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+--+-- A server that indexes the block chain writes hex, addresses and JSON for+-- every input and output that it shows, so those few functions decide how+-- fast it answers. Releases 1.6.3 and 1.6.4 rewrote them for speed. Some of+-- the rewrites were slower than what they replaced, and some of the figures+-- quoted for them held only at @-O2@, or not at all. The package had no+-- benchmark to check them with. This suite is here so that a claim about+-- speed can be checked by anyone, and so that the next rewrite is measured+-- before it is released.+--+-- The group @serial@ is about the other half of such a server: the bytes+-- that it keeps. It reads a transaction from its database for every one that+-- it returns, and writes and hashes every transaction of a block that it+-- imports. That group has no reference from 1.6.0: it measures each type+-- through every way to its bytes, with the memory that each allocates, and+-- is compared with a run of the release before.+--+-- Wherever it is possible, a function of the library is measured next to the+-- same work done the way haskoin-core 1.6.0 did it, copied into this file as+-- a reference. The reference is the benchmark named @as in 1.6.0@, and the+-- function of the library is the one named @now@, printed with the ratio+-- between the two: below 1 the library is faster than the reference. A+-- reference is a copy compiled here, not the old library, so it shows what+-- the old method costs, not exactly what the old release cost.+--+-- Run it at both levels of optimisation. The package is built with @-O1@+-- unless the user asks otherwise, and code that is only fast with @-O2@ is+-- not fast for most users:+--+-- > stack bench+-- > stack bench --ghc-options -O2+--+-- The README says how to run a part of it and how to compare two runs.+module Main (main) where++import Control.DeepSeq (NFData)+import Control.Monad (unless, (<=<))+import Data.Aeson (ToJSON (toEncoding))+import Data.Aeson.Encoding (Encoding, encodingToLazyByteString, unsafeToEncoding)+import Data.Base16.Types (extractBase16)+import Data.Binary qualified as Binary+import Data.Bits (shiftR, xor)+import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.ByteString.Base16 (encodeBase16)+import Data.ByteString.Builder (Builder, char7, lazyByteStringHex, toLazyByteString, word8)+import Data.ByteString.Lazy qualified as L+import Data.ByteString.Lazy.Base16 qualified as L16+import Data.Bytes.Get (isEmpty, runGetS)+import Data.Bytes.Put (runPutL, runPutS)+import Data.Bytes.Serial (Serial (deserialize, serialize))+import Data.Char (chr)+import Data.List (intercalate)+import Data.Maybe (fromMaybe)+import Data.Serialize qualified as Cereal+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Lazy qualified as LT+import Data.Word (Word32, Word64)+import Haskoin+import Numeric (showIntAtBase)+import Test.Tasty.Bench++main :: IO ()+main =+  defaultMain+    [ bgroup "hex" hexBenchmarks,+      bgroup "address" addressBenchmarks,+      bgroup "json" jsonBenchmarks,+      bgroup "base58" base58Benchmarks,+      bgroup "serial" serialBenchmarks+    ]++-- | The benchmark of a function of the library, named @now@, after the same+-- work done as haskoin-core 1.6.0 did it, named @as in 1.6.0@. The first+-- argument is the names of the groups that the pair is in, outermost first:+-- tasty-bench finds the reference by its full name, to print how many times+-- as long as the reference the library takes.+versus :: [String] -> String -> Benchmarkable -> Benchmarkable -> Benchmark+versus groups name old new =+  bgroup+    name+    [ bench reference old,+      bcompare (intercalate " && " (zipWith field [0 :: Int ..] path)) (bench "now" new)+    ]+  where+    reference = "as in 1.6.0"+    path = reference : name : reverse groups+    field 0 s = "$NF == \"" <> s <> "\""+    field i s = "$(NF-" <> show i <> ") == \"" <> s <> "\""++-- Input++-- | Bytes that look random and are the same in every run: the output of a+-- SplitMix64 generator. Hex and Base58 read their input a byte at a time, so+-- bytes that are all alike would flatter a table lookup.+bytes :: Word64 -> Int -> ByteString+bytes seed n = fst (B.unfoldrN n (Just . next) seed)+  where+    next s =+      let s' = s + 0x9e3779b97f4a7c15+          a = (s' `xor` (s' `shiftR` 30)) * 0xbf58476d1ce4e5b9+          b = (a `xor` (a `shiftR` 27)) * 0x94d049bb133111eb+       in (fromIntegral (b `xor` (b `shiftR` 31)), s')++-- | Bytes from their hex. The input of this file is written by hand, so hex+-- that does not decode is a mistake here, not a case to handle.+hex :: Text -> ByteString+hex = fromMaybe (error "Bench: bad hex") . decodeHex++-- | The sizes that hex is measured on: a hash, a transaction of ordinary+-- size, a large script, and a block.+sizes :: [(String, Int)]+sizes = [("32 B", 32), ("250 B", 250), ("1 kB", 1000), ("1 MB", 1000000)]++-- | A megabyte in the chunks that serializing a block gives: the same bytes+-- written through a builder, as 'runPutL' does, which fills a first chunk of+-- about 4 kB and then chunks of about 32 kB.+megabyteSerialized :: L.ByteString+megabyteSerialized = toLazyByteString (B.foldr (\w b -> word8 w <> b) mempty (bytes 4 1000000))++-- | A megabyte in chunks of 100 bytes, as a list of scripts joined together+-- would be. haskoin-core 1.6.4 treated chunks under 256 bytes differently+-- from longer ones, so both sides of that line are measured.+megabyteSmallChunks :: L.ByteString+megabyteSmallChunks = L.fromChunks (pieces (bytes 5 1000000))+  where+    pieces b+      | B.null b = []+      | otherwise = let (h, t) = B.splitAt 100 b in h : pieces t++-- Hex++hexBenchmarks :: [Benchmark]+hexBenchmarks =+  [ bgroup "hexBuilder" $+      [ versus ["hex", "hexBuilder"] name (nf (toLazyByteString . hexBuilder160) input) $+          nf (toLazyByteString . hexBuilder) input+      | (name, input) <- lazyInputs+      ],+    bgroup "hexEncoding" $+      [ versus ["hex", "hexEncoding"] name (nf (encodingToLazyByteString . hexEncoding160) input) $+          nf (encodingToLazyByteString . hexEncoding) input+      | (name, input) <- lazyInputs+      ],+    bgroup "encodeHex" $+      [ versus ["hex", "encodeHex"] name (nf encodeHex160 input) (nf encodeHex input)+      | (name, size) <- sizes,+        let input = bytes 1 size+      ],+    bgroup "encodeHexLazy" $+      [ versus ["hex", "encodeHexLazy"] name (nf encodeHexLazy160 input) (nf encodeHexLazy input)+      | (name, input) <- lazyInputs+      ],+    bgroup "hash" $+      [ versus ["hex", "hash"] "txHashToHex" (nf txHashToHex160 txid) (nf txHashToHex txid),+        versus ["hex", "hash"] "blockHashToHex" (nf blockHashToHex160 blockid) (nf blockHashToHex blockid)+      ]+  ]+  where+    lazyInputs =+      [(name, L.fromStrict (bytes 2 size)) | (name, size) <- sizes]+        <> [ ("1 MB as serialized", megabyteSerialized),+             ("1 MB in chunks of 100 B", megabyteSmallChunks)+           ]++-- | 'hexBuilder' of haskoin-core 1.6.0: the hex of the builder of bytestring.+hexBuilder160 :: L.ByteString -> Builder+hexBuilder160 = lazyByteStringHex++-- | 'hexEncoding' of haskoin-core 1.6.0.+hexEncoding160 :: L.ByteString -> Encoding+hexEncoding160 b = unsafeToEncoding (char7 '"' <> hexBuilder160 b <> char7 '"')++-- | 'encodeHex' of haskoin-core 1.6.0: the encoder of the base16 package.+encodeHex160 :: ByteString -> Text+encodeHex160 = extractBase16 . encodeBase16++-- | 'encodeHexLazy' of haskoin-core 1.6.0.+encodeHexLazy160 :: L.ByteString -> LT.Text+encodeHexLazy160 = extractBase16 . L16.encodeBase16++-- | 'txHashToHex' of haskoin-core 1.6.0: serialize the hash, reverse it and+-- write its hex.+txHashToHex160 :: TxHash -> Text+txHashToHex160 (TxHash h) = encodeHex160 (B.reverse (runPutS (serialize h)))++-- | 'blockHashToHex' of haskoin-core 1.6.0.+blockHashToHex160 :: BlockHash -> Text+blockHashToHex160 (BlockHash h) = encodeHex160 (B.reverse (runPutS (serialize h)))++txid :: TxHash+txid = TxHash (doubleSHA256 (bytes 6 250))++blockid :: BlockHash+blockid = BlockHash (doubleSHA256 (bytes 7 80))++-- Addresses++-- | The scripts of outputs that a server reads the address of. The first+-- four are the kinds that 'scriptToAddressBS' tells by their bytes. The+-- others are read by the script parser: Taproot and data carriers are a large+-- share of the outputs of Bitcoin today, so they are not a corner case.+scripts :: [(String, Network, ByteString)]+scripts =+  [ ("P2PKH", btc, hex "76a914" <> bytes 10 20 <> hex "88ac"),+    ("P2SH", btc, hex "a914" <> bytes 11 20 <> hex "87"),+    ("P2WPKH", btc, hex "0014" <> bytes 12 20),+    ("P2WSH", btc, hex "0020" <> bytes 13 32),+    ("Taproot", btc, hex "5120" <> bytes 14 32),+    ("witness version 2 with 20 bytes", btc, hex "5214" <> bytes 15 20),+    ("OP_RETURN with 20 bytes", btc, hex "6a14" <> bytes 16 20),+    ("OP_RETURN with 80 bytes", btc, hex "6a4c50" <> bytes 17 80),+    ("pay to public key", btc, hex "21" <> key1 <> hex "ac"),+    ("multisig 2 of 3", btc, multisig),+    ("empty script", btc, B.empty),+    ("non-standard script", btc, hex "76a914" <> bytes 18 20 <> hex "88ad51"),+    ("P2SH32 on Bitcoin Cash", bch, hex "aa20" <> bytes 19 32 <> hex "87"),+    ("P2PKH on Bitcoin Cash", bch, hex "76a914" <> bytes 20 20 <> hex "88ac"),+    ("P2WPKH on Bitcoin Cash", bch, hex "0014" <> bytes 21 20)+  ]+  where+    multisig = hex "5221" <> key1 <> hex "21" <> key2 <> hex "21" <> key3 <> hex "53ae"+    -- the generator of secp256k1, twice it and three times it+    key1 = hex "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"+    key2 = hex "02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"+    key3 = hex "02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"++-- | Results are forced whole, so a script that has no address is timed with+-- the text of its error. A caller that throws the error away pays less than+-- this for a script that fails to parse.+addressBenchmarks :: [Benchmark]+addressBenchmarks =+  [ bgroup "scriptToAddressBS" $+      [ versus ["address", "scriptToAddressBS"] name (nf (scriptToAddressBS160 net) script) $+          nf (scriptToAddressBS net) script+      | (name, net, script) <- scripts+      ],+    -- the text of an address, which a server writes after reading it+    bgroup "addrToText" $+      [ bench name (nf (addrToText net) address)+      | (name, net, script) <- scripts,+        Right address <- [scriptToAddressBS net script]+      ]+  ]++-- | 'scriptToAddressBS' of haskoin-core 1.6.0: parse the script whatever it+-- is, then decode the output, then find its address.+scriptToAddressBS160 :: Network -> ByteString -> Either String Address+scriptToAddressBS160 net =+  maybeToEither "Could not decode address" . outputAddress net <=< unmarshal160++-- | What @unmarshal@ did for a 'ScriptOutput' in haskoin-core 1.6.0: run a+-- parser that is written for any monad, through the dictionary of its+-- class. The library called it that way, and that is why parsing a script of+-- 34 bytes took most of a microsecond. The pragma keeps GHC from making a+-- copy of this function for the one type it is used at here, which would+-- measure a parser that 1.6.0 did not have. With it, this reference takes+-- as long as @scriptToAddressBS@ of 1.6.0 built from its tag, or up to a+-- tenth less.+unmarshal160 :: (Serial a) => ByteString -> Either String a+unmarshal160 = runGetS $ do+  value <- deserialize+  done <- isEmpty+  unless done $ fail "unmarshal: bytes left over after the value"+  return value+{-# OPAQUE unmarshal160 #-}++-- JSON++-- | Transactions with scripts of the usual shapes and sizes. The bytes of+-- the scripts are made up: writing JSON does not parse them.+transactions :: [(String, Tx)]+transactions =+  [ ( "legacy transaction, 2 inputs and 2 outputs",+      Tx 1 [input 30 (bytes 31 107), input 32 (bytes 33 107)] outputs [] 0+    ),+    ( "SegWit transaction, 2 inputs and 2 outputs",+      Tx 2 [input 34 B.empty, input 35 B.empty] outputs [witness 36, witness 37] 0+    ),+    ( "transaction with 2 multisig inputs of 254 and 296 bytes",+      Tx 1 [input 38 (bytes 39 254), input 40 (bytes 41 296)] outputs [] 0+    ),+    ( "transaction with 100 inputs and 100 outputs",+      Tx 1 [input k (bytes (k + 1000) 107) | k <- [100 .. 199]] (concat (replicate 50 outputs)) [] 0+    )+  ]+  where+    input seed script = TxIn (OutPoint (TxHash (doubleSHA256 (bytes seed 32))) 1) script 0xffffffff+    outputs =+      [ TxOut 5000000000 (hex "76a914" <> bytes 42 20 <> hex "88ac"),+        TxOut 123456 (hex "0020" <> bytes 43 32)+      ]+    -- a signature and a public key+    witness seed = [bytes seed 72, bytes (seed + 100) 33]++jsonBenchmarks :: [Benchmark]+jsonBenchmarks =+  [ bgroup "toEncoding" $+      [bench name (nf encoded tx) | (name, tx) <- transactions]+        <> [ versus ["json", "toEncoding"] "TxHash" (nf (encodingToLazyByteString . txHashEncoding160) txid) $+               nf encoded txid,+             bench "BlockHash" (nf encoded blockid),+             bench "BlockHeader" (nf encoded header)+           ]+  ]+  where+    encoded :: (ToJSON a) => a -> L.ByteString+    encoded = encodingToLazyByteString . toEncoding+    header = blockHeader++-- | The JSON encoding of 'TxHash' of haskoin-core 1.6.0.+txHashEncoding160 :: TxHash -> Encoding+txHashEncoding160 = hexEncoding160 . L.reverse . runPutL . serialize++-- Base58++base58Benchmarks :: [Benchmark]+base58Benchmarks =+  [ bgroup "encodeBase58" $+      [ versus ["base58", "encodeBase58"] name (nf encodeBase58160 input) (nf encodeBase58 input)+      | (name, size) <- lengths,+        let input = bytes 60 size+      ],+    bench "encodeBase58Check of 21 B" (nf encodeBase58Check (bytes 61 21)),+    bench "decodeBase58Check of an address" (nf decodeBase58Check (encodeBase58Check (bytes 62 21)))+  ]+  where+    -- an address with its checksum, an extended key with its checksum, and+    -- lengths that nothing in Bitcoin has, where the cost grows with the+    -- square of the length+    lengths = [("25 B", 25), ("82 B", 82), ("2 kB", 2000), ("20 kB", 20000)]++-- | 'encodeBase58' of haskoin-core 1.6.0: the bytes as one 'Integer',+-- divided by 58 a digit at a time into a list of characters.+encodeBase58160 :: ByteString -> Text+encodeBase58160 bs = T.replicate (B.length zeros) "1" <> digits+  where+    (zeros, rest) = B.span (== 0) bs+    digits+      | B.null rest = T.empty+      | otherwise = T.pack (showIntAtBase 58 (chr . fromIntegral . B.index alphabet) (bsToInteger rest) "")+    alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"++-- Binary encoding++-- | The binary form of the types that a server reads and writes most. A+-- server that indexes the chain decodes every transaction it returns from+-- its database, writes a key of a hash or an outpoint for every input and+-- output of a block that it imports, and hashes every transaction of that+-- block. The time and the memory of these few encoders decide how fast it+-- imports a block.+--+-- Each type is measured through the entry points that such a server calls:+-- @encode@ and @decode@ of cereal, and 'runPutS' with 'serialize' and+-- 'runGetS' with 'deserialize' of the bytes package. They give the same+-- bytes, but they reach the code of the library by different doors, and one+-- may be fast while the other is not. A transaction is measured through+-- binary too.+--+-- Run these with @+RTS -T@ to see the memory allocated by each: the time+-- of an encoder of a few bytes is mostly the time that it takes to allocate.+serialBenchmarks :: [Benchmark]+serialBenchmarks =+  [ codec "TxHash" txid,+    codec "BlockHash" blockid,+    codec "Hash256" (doubleSHA256 (bytes 70 32)),+    codec "Hash160" (addressHash (bytes 71 33)),+    codec "VarInt of 1 byte" (VarInt 107),+    codec "VarInt of 3 bytes" (VarInt 3000),+    codec "OutPoint" outpoint,+    codec "TxOut" (TxOut 123456 (hex "0020" <> bytes 43 32)),+    codec "TxIn" (TxIn outpoint (bytes 72 107) 0xffffffff),+    codec "BlockHeader" blockHeader,+    codec "Address, P2PKH" (PubKeyAddress (addressHash (bytes 73 33))),+    codec "Address, P2WSH" (WitnessScriptAddress (sha256 (bytes 74 33))),+    bgroup "Tx" $+      [ bgroup name (codecs tx <> binaryCodecs tx)+      | (name, tx) <- take 2 transactions+      ],+    codec ("Block of " <> show blockSize <> " transactions") block,+    -- a block as a node gets it from a peer and sends it to one; half of+    -- the time is the checksum of the payload+    bgroup+      ("Message with a block of " <> show blockSize <> " transactions")+      [ bench "putMessage" (nf (runPutS . putMessage btc) (MBlock block)),+        bench "getMessage" (nf (runGetS (getMessage btc)) (runPutS (putMessage btc (MBlock block))))+      ],+    bgroup "hash" $+      [ bgroup+          name+          [ bench "txHash" (nf txHash tx),+            bench "txWitnessHash" (nf txWitnessHash tx),+            bench "txWeight" (nf txWeight tx),+            -- what is left of the two above once the bytes are written+            bench "doubleSHA256 of its bytes" (nf doubleSHA256 (runPutS (serialize tx)))+          ]+      | (name, tx) <- take 2 transactions+      ]+        <> [ bench "headerHash" (nf headerHash blockHeader),+             bench ("txHash of " <> show blockSize <> " transactions") (nf (map txHash) blockTransactions)+           ]+  ]+  where+    outpoint = OutPoint txid 1++-- | A value written and read through cereal and through the bytes package.+codec :: (Serial a, Cereal.Serialize a, NFData a) => String -> a -> Benchmark+codec name x = bgroup name (codecs x)+{-# INLINE codec #-}++-- | The benchmarks of 'codec'. The pragma makes a copy of them for every+-- type that they are used at, so that each one calls the library as a+-- program that names the type does, not through a dictionary that only this+-- file would have.+codecs :: forall a. (Serial a, Cereal.Serialize a, NFData a) => a -> [Benchmark]+codecs x =+  [ bench "cereal encode" (nf Cereal.encode x),+    bench "cereal decode" (nf (Cereal.decode :: ByteString -> Either String a) encoded),+    bench "runPutS serialize" (nf (runPutS . serialize) x),+    bench "runGetS deserialize" (nf (runGetS deserialize :: ByteString -> Either String a) encoded),+    bench "encodeSerial" (nf encodeSerial x),+    bench "decodeSerial" (nf (decodeSerial :: ByteString -> Either String a) encoded)+  ]+  where+    encoded = runPutS (serialize x)+{-# INLINE codecs #-}++-- | A value written and read through binary, which works on lazy bytes.+binaryCodecs :: forall a. (Binary.Binary a, NFData a) => a -> [Benchmark]+binaryCodecs x =+  [ bench "binary encode" (nf Binary.encode x),+    bench "binary decode" (nf (Binary.decode :: L.ByteString -> a) (Binary.encode x))+  ]+{-# INLINE binaryCodecs #-}++blockHeader :: BlockHeader+blockHeader = BlockHeader 1 blockid (doubleSHA256 (bytes 50 64)) 1231006505 0x1d00ffff 2083236893++-- | The number of transactions of 'block': about as many as a full block of+-- Bitcoin has.+blockSize :: Int+blockSize = 3000++-- | A block of about 1.1 MB, of transactions that differ in their bytes, in+-- their numbers of inputs and outputs, and in whether they have a witness:+-- two in three do, as in a block of Bitcoin today.+block :: Block+block = Block blockHeader blockTransactions++-- | The transactions of 'block'.+blockTransactions :: [Tx]+blockTransactions = map transaction [1 .. fromIntegral blockSize]+  where+    transaction :: Word64 -> Tx+    transaction k+      | k `mod` 3 == 0 = Tx 1 (map (input 107) (seeds k)) (outputs k) [] 0+      | otherwise = Tx 2 (map (input 0) (seeds k)) (outputs k) (map witness (seeds k)) (fromIntegral k)+    -- one to three seeds, all different from those of every other transaction+    seeds k = [1000 * k + i | i <- [1 .. 1 + k `mod` 3]]+    input size seed =+      TxIn (OutPoint (TxHash (doubleSHA256 (bytes seed 32))) (index seed)) (bytes (seed + 500) size) 0xfffffffd+    index :: Word64 -> Word32+    index seed = fromIntegral (seed `mod` 4)+    outputs k = concat (replicate (fromIntegral (1 + k `mod` 2)) (pair k))+    pair k =+      [ TxOut (1000 + k) (hex "0014" <> bytes (k + 1) 20),+        TxOut (5000000 + k) (hex "5120" <> bytes (k + 2) 32)+      ]+    witness seed = [bytes (seed + 600) 72, bytes (seed + 700) 33]
haskoin-core.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack  name:           haskoin-core-version:        1.6.4+version:        2.0.0 synopsis:       Bitcoin & Bitcoin Cash library for Haskell description:    Please see the README on GitHub at <https://github.com/jprupp/haskoin-core#readme> category:       Bitcoin, Finance, Network@@ -113,6 +113,7 @@       Haskoin.Util.Arbitrary.Script       Haskoin.Util.Arbitrary.Transaction       Haskoin.Util.Arbitrary.Util+      Haskoin.Util.Direct       Haskoin.Util.Helpers       Haskoin.Util.Marshal   other-modules:@@ -128,7 +129,7 @@     , base64 >=1.0     , binary >=0.8.8     , bytes >=0.17-    , bytestring >=0.10.10.0+    , bytestring >=0.11     , cereal >=0.5.8     , conduit >=1.3.1.2     , containers >=0.6.2.1@@ -144,7 +145,7 @@     , ram >=0.22.0     , safe >=0.3.18     , scientific >=0.3.6.2-    , secp256k1-haskell >=2.0.0+    , secp256k1-haskell >=3.0.0 && <3.1     , split >=0.2.3.3     , string-conversions >=0.4.0.1     , text >=1.2.3.0@@ -176,6 +177,7 @@       Haskoin.Transaction.TaprootSpec       Haskoin.Transaction.VerdictSpec       Haskoin.TransactionSpec+      Haskoin.Util.DirectSpec       Haskoin.UtilSpec       Paths_haskoin_core   hs-source-dirs:@@ -190,7 +192,7 @@     , base64     , binary >=0.8.8     , bytes >=0.17-    , bytestring >=0.10.10.0+    , bytestring >=0.11     , cereal >=0.5.8     , conduit >=1.3.1.2     , containers >=0.6.2.1@@ -209,7 +211,7 @@     , ram >=0.22.0     , safe >=0.3.18     , scientific >=0.3.6.2-    , secp256k1-haskell >=2.0.0+    , secp256k1-haskell >=3.0.0 && <3.1     , split >=0.2.3.3     , string-conversions >=0.4.0.1     , text >=1.2.3.0@@ -221,3 +223,48 @@     , vector >=0.12.1.2   default-language: Haskell2010   build-tool-depends: hspec-discover:hspec-discover++benchmark bench+  type: exitcode-stdio-1.0+  main-is: Bench.hs+  hs-source-dirs:+      bench+  ghc-options: "-with-rtsopts=-A32m -T"+  build-depends:+      QuickCheck >=2.13.2+    , aeson >=1.4.6.0+    , array >=0.5.4.0+    , base >=4.9 && <5+    , base16 >=2.0+    , base64 >=1.0+    , binary >=0.8.8+    , bytes >=0.17+    , bytestring >=0.11+    , cereal >=0.5.8+    , conduit >=1.3.1.2+    , containers >=0.6.2.1+    , crypton >=1.0.0+    , data-default >=0.7.1.1+    , deepseq >=1.4.4.0+    , entropy >=0.4.1.5+    , hashable >=1.3.0.0+    , haskoin-core+    , hspec >=2.7.1+    , mtl >=2.2.2+    , murmur3 >=1.0.3+    , network >=3.1.1.1+    , ram >=0.22.0+    , safe >=0.3.18+    , scientific >=0.3.6.2+    , secp256k1-haskell >=3.0.0 && <3.1+    , split >=0.2.3.3+    , string-conversions >=0.4.0.1+    , tasty-bench >=0.3+    , text >=1.2.3.0+    , time >=1.9.3+    , transformers >=0.5.6.2+    , unicode-data >=0.2+    , unicode-transforms >=0.4+    , unordered-containers >=0.2.10.0+    , vector >=0.12.1.2+  default-language: Haskell2010
src/Haskoin/Address.hs view
@@ -111,6 +111,7 @@ import Haskoin.Script.Common import Haskoin.Script.Standard import Haskoin.Util+import Haskoin.Util.Direct (getDirect) import Text.Read   ( Lexeme (Ident, Punc),     Read (readListPrec, readPrec),@@ -289,6 +290,7 @@       putWord8 0x06       putWord8 v       putSized d+  {-# INLINEABLE serialize #-}    deserialize =     getWord8 >>= \case@@ -311,6 +313,7 @@             <> encodeHex (B.singleton b)     where       checked kind = maybe (fail ("Invalid " <> kind <> " address")) return+  {-# INLINEABLE deserialize #-}  -- | Write bytes behind their length. The length is a 64-bit word to stay -- compatible with data serialized by earlier versions.@@ -318,6 +321,7 @@ putSized d = do   putWord64be (fromIntegral (B.length d))   putByteString d+{-# INLINEABLE putSized #-}  -- | Read bytes written by 'putSized'. The length is checked against a maximum -- while it is still a 64-bit word, so a corrupt or hostile length can neither@@ -327,10 +331,15 @@   n <- getWord64be   when (n > fromIntegral maxLen) $ fail "Address payload too long"   getByteString (fromIntegral n)+{-# INLINEABLE getSized #-} +-- | Through cereal an address is read on a buffer directly, with+-- 'getDirect': an index of the chain has an address in the key of every+-- output and of every balance. It is written through the builder of cereal,+-- which costs less for a tag and a hash than a buffer of their own. instance Serialize Address where   put = serialize-  get = deserialize+  get = getDirect deserialize  instance Binary Address where   put = serialize@@ -590,29 +599,29 @@       | otherwise = fail "Does not recognize address prefix"  -- | HASH160 of a public key in its serialized form.-pubKeyHash :: Ctx -> PublicKey -> Hash160-pubKeyHash ctx = addressHash . marshal ctx+pubKeyHash :: PublicKey -> Hash160+pubKeyHash = addressHash . encodeSerial  -- | Obtain a standard pay-to-public-key-hash address from a public key.-pubKeyAddr :: Ctx -> PublicKey -> Address-pubKeyAddr ctx = p2pkhAddr . pubKeyHash ctx+pubKeyAddr :: PublicKey -> Address+pubKeyAddr = p2pkhAddr . pubKeyHash  -- | Obtain a SegWit pay-to-witness-public-key-hash (P2WPKH) address from a -- public key. Returns 'Nothing' for an uncompressed key. BIP-143 makes witness -- spends with uncompressed keys non-standard, so coins sent to such an address -- could not be spent through the normal network.-pubKeyWitnessAddr :: Ctx -> PublicKey -> Maybe Address-pubKeyWitnessAddr ctx pk = do+pubKeyWitnessAddr :: PublicKey -> Maybe Address+pubKeyWitnessAddr pk = do   guard pk.compress-  return . p2wpkhAddr $ pubKeyHash ctx pk+  return . p2wpkhAddr $ pubKeyHash pk  -- | Obtain a backwards-compatible SegWit P2SH-P2WPKH address from a public key. -- Returns 'Nothing' for an uncompressed key, for the same reason as -- 'pubKeyWitnessAddr'.-pubKeyCompatWitnessAddr :: Ctx -> PublicKey -> Maybe Address-pubKeyCompatWitnessAddr ctx pk = do+pubKeyCompatWitnessAddr :: PublicKey -> Maybe Address+pubKeyCompatWitnessAddr pk = do   guard pk.compress-  return . p2shP2wpkhAddr $ pubKeyHash ctx pk+  return . p2shP2wpkhAddr $ pubKeyHash pk  -- | Obtain a standard pay-to-public-key-hash (P2PKH) address from a 'Hash160'. p2pkhAddr :: Hash160 -> Address@@ -649,9 +658,9 @@ -- -- Also fails for a value that 'encodeOutput' cannot write, such as a multisig -- that requires more signatures than it has keys.-payToScriptAddress :: Ctx -> ScriptOutput -> Either String Address-payToScriptAddress ctx =-  fmap p2shAddr . p2shScriptHash <=< encodeOutput ctx+payToScriptAddress :: ScriptOutput -> Either String Address+payToScriptAddress =+  fmap p2shAddr . p2shScriptHash <=< encodeOutput  -- | Compute a SegWit pay-to-witness-script-hash (P2WSH) address for an output -- script.@@ -662,17 +671,17 @@ -- than consensus: it does not relay the spend of a witness script above 3,600 -- bytes, nor one with an uncompressed key. This function does not check -- either.-payToWitnessScriptAddress :: Ctx -> ScriptOutput -> Either String Address-payToWitnessScriptAddress ctx =-  fmap p2wshAddr . p2wshScriptHash <=< encodeOutput ctx+payToWitnessScriptAddress :: ScriptOutput -> Either String Address+payToWitnessScriptAddress =+  fmap p2wshAddr . p2wshScriptHash <=< encodeOutput  -- | Compute a backwards-compatible SegWit P2SH-P2WSH address: the -- pay-to-script-hash address of the witness program of the script. Fails as -- 'payToWitnessScriptAddress' does.-payToNestedScriptAddress :: Ctx -> ScriptOutput -> Either String Address-payToNestedScriptAddress ctx out = do-  h <- p2wshScriptHash =<< encodeOutput ctx out-  payToScriptAddress ctx (PayWitnessScriptHash h)+payToNestedScriptAddress :: ScriptOutput -> Either String Address+payToNestedScriptAddress out = do+  h <- p2wshScriptHash =<< encodeOutput out+  payToScriptAddress (PayWitnessScriptHash h)  -- | Get the output script that locks coins sent to an address. Token-aware -- CashAddr addresses use the same script as their plain counterparts. Other@@ -707,35 +716,48 @@     len = B.length b  -- | Get output script AST for an 'Address'.-addressToScript :: Ctx -> Address -> Maybe Script-addressToScript ctx addr =-  addressToOutput addr >>= eitherToMaybe . encodeOutput ctx+addressToScript :: Address -> Maybe Script+addressToScript addr =+  addressToOutput addr >>= eitherToMaybe . encodeOutput  -- | Encode address as output script in 'ByteString' form.-addressToScriptBS :: Ctx -> Address -> Maybe ByteString-addressToScriptBS ctx addr = (runPutS . serialize) <$> addressToScript ctx addr+addressToScriptBS :: Address -> Maybe ByteString+addressToScriptBS addr = (runPutS . serialize) <$> addressToScript addr  -- | Decode an output script into the 'Address' it has on a network, if it -- has one there. See 'outputAddress'.-scriptToAddress :: Network -> Ctx -> Script -> Either String Address-scriptToAddress net ctx =-  maybeToEither e . outputAddress net ctx <=< decodeOutput ctx+scriptToAddress :: Network -> Script -> Either String Address+scriptToAddress net =+  maybeToEither e . outputAddress net <=< decodeOutput   where     e = "Could not decode address"  -- | Decode a serialized script into the 'Address' it has on a network, if it -- has one there. See 'outputAddress'. ----- The four kinds of output that nearly every transaction pays to are told--- by their bytes, without parsing the script: a key hash, a script hash,--- and on a network with SegWit a witness key hash and a witness script--- hash. A server reads the address of every input and output that it shows,--- and parsing took most of that time. Any other script is parsed, and gives--- what it gave before; the tests hold both ways to the same answers.-scriptToAddressBS :: Network -> Ctx -> ByteString -> Either String Address-scriptToAddressBS net ctx bytes+-- The four kinds of output that most transactions pay to are told by their+-- bytes, without parsing the script: a key hash, a script hash, and on a+-- network with SegWit a witness key hash and a witness script hash. A server+-- reads the address of every input and output that it shows, and parsing+-- took most of that time.+--+-- Any other script is parsed with 'decodeSerial', and gives what the parser+-- gives, with the same text in a 'Left'; the tests hold both ways to the+-- same answers. That covers Taproot and the other witness versions, the+-- 256-bit script hash of Bitcoin Cash, and the scripts that have no address:+-- data carriers, bare public keys and multisig, and everything that is not+-- standard. A script with public keys in it costs the most, because each+-- key is checked to be a point of the curve before the answer is no.+--+-- By the benchmark of this package, at @-O1@ as at @-O2@, one of the four+-- kinds takes a twelfth or less of the time it took in version 1.6.0, which+-- parsed every script, and a Taproot output or a data carrier takes about a+-- fifth. Versions 1.6.3 and 1.6.4 were as fast for the four kinds, and+-- nearly twice as slow as 1.6.0 for every script they parsed.+scriptToAddressBS :: Network -> ByteString -> Either String Address+scriptToAddressBS net bytes   | Just a <- standard = Right a-  | otherwise = maybeToEither e . outputAddress net ctx =<< unmarshal ctx bytes+  | otherwise = maybeToEither e . outputAddress net =<< decodeSerial bytes   where     e = "Could not decode address"     n = B.length bytes@@ -772,8 +794,8 @@ -- plain hash lock, which Bitcoin Core reports as non-standard. Every address -- this function returns has a text form on the network, so 'addrToText' and -- the JSON encoder succeed for it.-outputAddress :: Network -> Ctx -> ScriptOutput -> Maybe Address-outputAddress net _ =+outputAddress :: Network -> ScriptOutput -> Maybe Address+outputAddress net =   \case     PayPKHash h -> Just $ PubKeyAddress h     PayScriptHash h -> Just $ ScriptAddress h@@ -798,10 +820,10 @@ -- 'maxRedeemScriptSize' bytes, since no valid input can carry one. The -- function does not look at the output being spent, so it is a guess that a -- caller should confirm against that output when it has it.-inputAddress :: Ctx -> ScriptInput -> Maybe Address-inputAddress ctx =+inputAddress :: ScriptInput -> Maybe Address+inputAddress =   \case-    (RegularInput (SpendPKHash _ key)) -> Just $ pubKeyAddr ctx key-    (ScriptHashInput _ rdm) -> eitherToMaybe $ payToScriptAddress ctx rdm-    (NestedWitnessInput rdm) -> eitherToMaybe $ payToScriptAddress ctx rdm+    (RegularInput (SpendPKHash _ key)) -> Just $ pubKeyAddr key+    (ScriptHashInput _ rdm) -> eitherToMaybe $ payToScriptAddress rdm+    (NestedWitnessInput rdm) -> eitherToMaybe $ payToScriptAddress rdm     _ -> Nothing
src/Haskoin/Address/Base58.hs view
@@ -80,39 +80,43 @@ -- | Encode an arbitrary 'ByteString' into its 'Base58' representation, -- preserving leading zeroes. ----- The bytes are read as one number in limbs of 32 bits, and divided by 58^5--- (656,356,768) in machine words: each pass over the limbs gives five digits. An address--- of 25 bytes takes seven passes over seven limbs. Building an 'Integer'--- and dividing that, as this did until 1.6.2, took about five times as long,--- and a server writes an address for every input and output it shows.+-- The bytes are read as one number, and the number is divided by 58^10+-- (430,804,206,899,405,824), the largest power of 58 that fits in a machine+-- word: each division of the big number gives ten digits, which are then+-- taken apart in machine words. Version 1.6.0 divided the big number by 58+-- for every digit, ten times as many divisions. Versions 1.6.3 and 1.6.4+-- kept the number as a list of limbs of 32 bits and divided it by 58^5,+-- which was quicker than 1.6.0 for an address and slower from about 500+-- bytes up. This way is quicker than both at every length, by the benchmark+-- of this package, at @-O1@ as at @-O2@: about three times as fast as 1.6.0+-- for an address of 25 bytes, and about twelve times for 20,000 bytes.+--+-- The time still grows with the square of the length, as for+-- 'decodeBase58'. That does not matter for anything in Bitcoin, where the+-- longest input is an extended key of 82 bytes, but Base58 is not a format+-- for large data. encodeBase58 :: ByteString -> Base58 encodeBase58 bs =-  E.decodeLatin1 (B.replicate (B.length z) (b58 0) <> B.pack (map b58 (dropWhile (== 0) (groups (limbs b) []))))+  E.decodeLatin1 (B.replicate (B.length z) (b58 0) <> B.pack (map b58 (dropWhile (== 0) (groups (number b) []))))   where     (z, b) = B.span (== 0) bs-    -- the number, most significant limb first, each limb under 2^32-    limbs bytes =-      let padded = B.replicate ((4 - B.length bytes `mod` 4) `mod` 4) 0 <> bytes-       in [ B.foldl' (\acc w -> acc `shiftL` 8 .|. fromIntegral w) 0 (BU.unsafeTake 4 (BU.unsafeDrop k padded))-          | k <- [0, 4 .. B.length padded - 4]-          ]-    -- the digits, most significant first, five for each division-    groups ls !acc = case dropWhile (== 0) ls of-      [] -> acc-      live -> let (q, r) = divide live in groups q (five (5 :: Int) r acc)-    -- the number divided by 58^5, with the remainder; a remainder is under-    -- 2^30, so with a limb after it it fits in 64 bits-    divide = go 0 []-      where-        go !r qs [] = (reverse qs, r)-        go !r qs (x : xs) =-          let !cur = r `shiftL` 32 .|. x-              !q = cur `quot` chunk-           in go (cur `rem` chunk) (q : qs) xs-    chunk = 656356768 :: Word64-    five :: Int -> Word64 -> [Int] -> [Int]-    five 0 _ acc = acc-    five k !w acc = let !d = fromIntegral (w `rem` 58) in five (k - 1) (w `quot` 58) (d : acc)+    -- the bytes as a number, most significant first: the two halves are+    -- read on their own and joined, so that the big numbers are few+    number :: ByteString -> Integer+    number bytes+      | B.length bytes <= 8 = toInteger (B.foldl' (\acc w -> acc `shiftL` 8 .|. fromIntegral w) (0 :: Word64) bytes)+      | otherwise =+          let (h, l) = B.splitAt (B.length bytes `div` 2) bytes+           in number h `shiftL` (8 * B.length l) .|. number l+    -- the digits, most significant first, ten for each division; the+    -- first group starts with zeroes that are not digits of the number+    groups :: Integer -> [Int] -> [Int]+    groups 0 acc = acc+    groups n !acc = let (q, r) = n `quotRem` chunk in groups q (ten (10 :: Int) (fromInteger r) acc)+    chunk = 430804206899405824 :: Integer+    ten :: Int -> Word64 -> [Int] -> [Int]+    ten 0 _ acc = acc+    ten k !w acc = let !d = fromIntegral (w `rem` 58) in ten (k - 1) (w `quot` 58) (d : acc)  -- | Decode a 'Base58'-encoded 'Text' to a 'ByteString'. Returns 'Nothing' if -- the input contains any character outside the 'Base58' alphabet.
src/Haskoin/Block/Common.hs view
@@ -1,8 +1,8 @@-{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE ImportQualifiedPost #-}+{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoFieldSelectors #-} @@ -57,6 +57,7 @@ import Haskoin.Crypto.Hash import Haskoin.Network.Common import Haskoin.Transaction.Common+import Haskoin.Util.Direct (encodeDirect, getDirect, putDirect) import Haskoin.Util.Helpers import Text.Read qualified as R @@ -78,13 +79,17 @@     header <- deserialize     txs <- getVarIntList deserialize     return $ Block header txs+  {-# INLINEABLE deserialize #-}   serialize (Block h txs) = do     serialize h     putVarIntList serialize txs+  {-# INLINEABLE serialize #-} +-- | Through cereal a block is written and read on a buffer directly, like+-- its transactions: see the instance of 'Tx'. instance Serialize Block where-  get = deserialize-  put = serialize+  get = getDirect deserialize+  put b = putDirect (serialize b)  instance Binary Block where   get = deserialize@@ -107,8 +112,17 @@  -- | Block header hash. To be serialized reversed for display purposes. newtype BlockHash = BlockHash {get :: Hash256}-  deriving (Eq, Ord, Generic, Hashable, Serial, NFData)+  deriving (Eq, Ord, Generic, Hashable, NFData) +-- | The instance is written out so that it can be inlined: one derived from+-- that of 'Hash256' has no code that GHC can see from another module, and a+-- block hash was then read through a dictionary, at thirty times the cost.+instance Serial BlockHash where+  serialize (BlockHash h) = serialize h+  {-# INLINE serialize #-}+  deserialize = BlockHash <$> deserialize+  {-# INLINE deserialize #-}+ instance Serialize BlockHash where   put = serialize   get = deserialize@@ -249,6 +263,7 @@           bits = b,           nonce = n         }+  {-# INLINEABLE deserialize #-}   serialize (BlockHeader v p m bt bb n) = do     putWord32le v     serialize p@@ -256,18 +271,19 @@     putWord32le bt     putWord32le bb     putWord32le n+  {-# INLINEABLE serialize #-}  instance Binary BlockHeader where   put = serialize   get = deserialize  instance Serialize BlockHeader where-  put = serialize-  get = deserialize+  put h = putDirect (serialize h)+  get = getDirect deserialize  -- | Compute hash of 'BlockHeader'. headerHash :: BlockHeader -> BlockHash-headerHash = BlockHash . doubleSHA256 . runPutS . serialize+headerHash h = BlockHash (doubleSHA256 (encodeDirect (serialize h)))  -- | A block locator is a set of block headers, denser towards the best block -- and sparser towards the genesis block. It starts at the highest block known.
src/Haskoin/Crypto/Hash.hs view
@@ -5,6 +5,7 @@ {-# LANGUAGE ImportQualifiedPost #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE NoFieldSelectors #-} @@ -42,13 +43,16 @@ import Control.DeepSeq import Control.Monad (guard) import Crypto.Hash+import Crypto.Hash.IO (hashInternalContextSize, hashInternalFinalize, hashInternalInit, hashInternalUpdate) import Crypto.MAC.HMAC (HMAC, hmac) import Data.Binary (Binary (..)) import Data.Bits (shiftL, (.|.)) import Data.ByteArray (ByteArrayAccess, convert)+import Data.ByteArray qualified as BA import Data.ByteString (ByteString) import Data.ByteString qualified as B import Data.ByteString.Short (ShortByteString, fromShort, toShort)+import Data.ByteString.Short qualified as Short import Data.Bytes.Get import Data.Bytes.Put import Data.Bytes.Serial (Serial (..))@@ -58,10 +62,14 @@ import Data.String (IsString, fromString) import Data.String.Conversions (cs) import Data.Void (Void)-import Data.Word (Word32)+import Data.Word (Word32, Word8)+import Foreign.Marshal.Alloc (allocaBytesAligned)+import Foreign.Ptr (Ptr, castPtr, plusPtr) import GHC.Generics (Generic)+import Haskoin.Util.Direct (getShortBytes, putShortBytes) import Haskoin.Util.Helpers import Haskoin.Util.Marshal+import System.IO.Unsafe (unsafeDupablePerformIO) import Text.Read as R  -- | 'Word32' wrapped for type-safe 32-bit checksums.@@ -137,8 +145,10 @@       e = error "Could not decode hash from hex string"  instance Serial Hash512 where-  deserialize = Hash512 . toShort <$> getByteString 64-  serialize = putByteString . fromShort . (.get)+  deserialize = Hash512 <$> getShortBytes 64+  {-# INLINE deserialize #-}+  serialize = putShortBytes . (.get)+  {-# INLINE serialize #-}  instance Serialize Hash512 where   put = serialize@@ -154,8 +164,10 @@       e = error "Could not decode hash from hex string"  instance Serial Hash256 where-  deserialize = Hash256 . toShort <$> getByteString 32-  serialize = putByteString . fromShort . (.get)+  deserialize = Hash256 <$> getShortBytes 32+  {-# INLINE deserialize #-}+  serialize = putShortBytes . (.get)+  {-# INLINE serialize #-}  instance Serialize Hash256 where   put = serialize@@ -171,8 +183,10 @@       e = error "Could not decode hash from hex string"  instance Serial Hash160 where-  deserialize = Hash160 . toShort <$> getByteString 20-  serialize = putByteString . fromShort . (.get)+  deserialize = Hash160 <$> getShortBytes 20+  {-# INLINE deserialize #-}+  serialize = putShortBytes . (.get)+  {-# INLINE serialize #-}  instance Serialize Hash160 where   put = serialize@@ -188,7 +202,13 @@  -- | Calculate SHA256 hash. sha256 :: (ByteArrayAccess b) => b -> Hash256-sha256 = Hash256 . toShort . convert . hashWith SHA256+sha256 b =+  Hash256 . unsafeDupablePerformIO . BA.withByteArray b $ \input ->+    withSHA256 $ \context digest -> do+      hashSHA256 context input (BA.length b) digest+      Short.packCStringLen (castPtr digest, 32)+{-# INLINEABLE sha256 #-}+{-# SPECIALIZE sha256 :: ByteString -> Hash256 #-}  -- | Calculate RIPEMD160 hash. ripemd160 :: (ByteArrayAccess b) => b -> Hash160@@ -200,8 +220,46 @@  -- | Compute two rounds of SHA-256. doubleSHA256 :: (ByteArrayAccess b) => b -> Hash256-doubleSHA256 =-  Hash256 . toShort . convert . hashWith SHA256 . hashWith SHA256+doubleSHA256 b =+  Hash256 . unsafeDupablePerformIO . BA.withByteArray b $ \input ->+    withSHA256 $ \context digest -> do+      hashSHA256 context input (BA.length b) digest+      -- the first digest is read whole before the second is written over it+      hashSHA256 context digest 32 digest+      Short.packCStringLen (castPtr digest, 32)+{-# INLINEABLE doubleSHA256 #-}+{-# SPECIALIZE doubleSHA256 :: ByteString -> Hash256 #-}++-- | Memory for a SHA-256 context and, after it, for a digest of 32 bytes.+--+-- 'sha256' and 'doubleSHA256' hash every transaction and every block+-- header that a node sees, most of them a few hundred bytes long. The pure+-- interface of crypton allocates a context, copies it for every step, and+-- copies the digest twice on its way to a 'ShortByteString': about 1.5 kB+-- and 400 ns for each hash, more than the hashing of a short input takes.+-- These two functions call the same C code on memory that they hold for+-- the length of the call, and copy the digest once.+withSHA256 :: (Ptr (Context SHA256) -> Ptr Word8 -> IO a) -> IO a+withSHA256 action =+  allocaBytesAligned (size + 32) 16 $ \context -> action context (context `plusPtr` size)+  where+    size = hashInternalContextSize SHA256+{-# INLINE withSHA256 #-}++-- | Write the SHA-256 digest of that many bytes of input. The C code takes+-- a length of 32 bits, so a longer input is given to it in pieces.+hashSHA256 :: Ptr (Context SHA256) -> Ptr Word8 -> Int -> Ptr Word8 -> IO ()+hashSHA256 context input len digest = do+  hashInternalInit context+  update input len+  hashInternalFinalize context (castPtr digest)+  where+    update from left+      | left <= 0 = return ()+      | otherwise = do+          let piece = min left (fromIntegral (maxBound :: Word32))+          hashInternalUpdate context from (fromIntegral piece)+          update (from `plusPtr` piece) (left - piece)  -- | Compute SHA-256 followed by RIPMED-160. addressHash :: (ByteArrayAccess b) => b -> Hash160
src/Haskoin/Crypto/Keys/Common.hs view
@@ -80,18 +80,21 @@   }   deriving (Generic, Show, Read, Hashable, Eq, NFData) -instance MarshalJSON Ctx PublicKey where-  marshalValue ctx = String . encodeHex . runPutS . marshalPut ctx+instance ToJSON PublicKey where+  toJSON = String . encodeHex . runPutS . serialize -  marshalEncoding ctx = hexEncoding . runPutL . marshalPut ctx+  toEncoding = hexEncoding . runPutL . serialize -  unmarshalValue ctx =+instance FromJSON PublicKey where+  parseJSON =     withText "PublicKey" $ \t -> do       bs <- maybe (fail "Expected hex public key") return $ decodeHex t-      either fail return $ decodePubKey ctx bs+      either fail return $ decodePubKey bs -instance Marshal Ctx PublicKey where-  marshalGet ctx = do+instance Serial PublicKey where+  {-# INLINEABLE serialize #-}+  {-# INLINEABLE deserialize #-}+  deserialize = do     c <-       lookAhead $         getWord8 >>= \case@@ -100,13 +103,21 @@           0x04 -> return False           _ -> fail "Not a public key"     bs <- getByteString $ if c then 33 else 65-    case importPubKey ctx bs of+    case importPubKey bs of       Nothing -> fail "Could not decode public key"       Just k -> return $ PublicKey k c -  marshalPut ctx pk =-    putByteString $ exportPubKey ctx pk.compress pk.point+  serialize pk =+    putByteString $ exportPubKey pk.compress pk.point +instance Binary PublicKey where+  put = serialize+  get = deserialize++instance Serialize PublicKey where+  put = serialize+  get = deserialize+ -- | Wrap a public key from secp256k1 library adding information about compression. wrapPubKey :: Bool -> PubKey -> PublicKey wrapPubKey c p = PublicKey p c@@ -114,28 +125,28 @@ -- | Decode a public key from bytes that must hold the key and nothing else: -- 33 bytes starting with 0x02 or 0x03, or 65 bytes starting with 0x04. A key -- pushed in a script, a witness or a PSBT record is the whole item, so use--- this function, or 'unmarshal', for those. 'marshalGet' reads a key from the+-- this function, or 'decodeSerial', for those. 'deserialize' reads a key from the -- start of a longer stream and leaves the rest. -- -- A hybrid key, 65 bytes starting with 0x06 or 0x07, is refused. Consensus -- takes that form, but the relay rules of Bitcoin Core do not, and no wallet -- makes one.-decodePubKey :: Ctx -> ByteString -> Either String PublicKey-decodePubKey ctx = runGetS $ do-  k <- marshalGet ctx+decodePubKey :: ByteString -> Either String PublicKey+decodePubKey = runGetS $ do+  k <- deserialize   done <- isEmpty   unless done $ fail "Trailing bytes after public key"   return k  -- | Derives a public key from a private key. This function will preserve -- compression flag.-derivePublicKey :: Ctx -> PrivateKey -> PublicKey-derivePublicKey ctx (PrivateKey d c) = PublicKey (derivePubKey ctx d) c+derivePublicKey :: PrivateKey -> PublicKey+derivePublicKey (PrivateKey d c) = PublicKey (derivePubKey d) c  -- | Tweak a public key.-tweakPubKey :: Ctx -> PubKey -> Hash256 -> Maybe PubKey-tweakPubKey ctx p =-  tweakAddPubKey ctx p <=< tweak . runPutS . serialize+tweakPubKey :: PubKey -> Hash256 -> Maybe PubKey+tweakPubKey p =+  tweakAddPubKey p <=< tweak . runPutS . serialize  -- | Elliptic curve private key type with expected public key compression -- information. Compression information is stored in private key WIF formats and@@ -152,11 +163,12 @@ -- instance for the same reason: use 'toWif' and 'fromWif' to write a key -- out and read it back. ----- This protects a 'PrivateKey', not the 'SecKey' inside it. The 'Show'--- instance of 'SecKey' comes from the secp256k1 binding and prints the 32--- bytes in hex, so @show privateKey.key@ gives the secret away. A record of--- your own that holds a 'SecKey' and derives 'Show' prints it too. Keep keys--- in 'PrivateKey' or 'XPrvKey' where they may be shown.+-- The 'SecKey' inside is protected in the same way. Its 'Show' instance+-- comes from the secp256k1 binding and, since version 3.0.0 of it, prints+-- @SecKey \<redacted\>@, so @show privateKey.key@ and a record of your own+-- that holds a 'SecKey' and derives 'Show' do not give the secret away+-- either. 'Read' still parses the hex of a 'SecKey', so it is not the inverse+-- of 'Show' for that type. instance Show PrivateKey where   showsPrec d p =     showParen (d > 10) $@@ -199,9 +211,9 @@ decodeSecKey = secKey  -- | Tweak a private key.-tweakSecKey :: Ctx -> SecKey -> Hash256 -> Maybe SecKey-tweakSecKey ctx k =-  tweakAddSecKey ctx k <=< tweak . runPutS . serialize+tweakSecKey :: SecKey -> Hash256 -> Maybe SecKey+tweakSecKey k =+  tweakAddSecKey k <=< tweak . runPutS . serialize  -- | Decode a Casascius mini private key, as the Bitcoin wiki describes the -- format (<https://en.bitcoin.it/wiki/Mini_private_key_format>):
src/Haskoin/Crypto/Keys/Extended.hs view
@@ -121,12 +121,11 @@   ) import Data.Aeson.Encoding (Encoding, string, text) import Data.Aeson.Types (Parser)-import Data.Binary (Binary (get, put)) import Data.Bifunctor (first)+import Data.Binary (Binary (get, put)) import Data.Bits (clearBit, setBit, testBit) import Data.ByteString (ByteString) import Data.ByteString qualified as B-import Data.Char (isDigit) import Data.Bytes.Get   ( MonadGet       ( getByteString,@@ -144,6 +143,7 @@     runPutS,   ) import Data.Bytes.Serial (Serial (..))+import Data.Char (isDigit) import Data.Either (fromRight) import Data.Hashable (Hashable) import Data.List (foldl')@@ -210,8 +210,9 @@ -- must not reveal them. There is no 'Read' instance for the same reason: -- use 'xPrvExport' and 'xPrvImport' to write a key out and read it back. ----- The @key@ field is a 'SecKey', whose own 'Show' instance prints the secret--- in hex. Do not show that field by itself.+-- The @key@ field is a 'SecKey', whose own 'Show' instance prints+-- @SecKey \<redacted\>@ since secp256k1-haskell 3.0.0, so showing that field+-- by itself does not reveal the secret either. instance Show XPrvKey where   showsPrec d k =     showParen (d > 10) $@@ -268,8 +269,8 @@   }   deriving (Generic, Eq, Show, Read, Hashable, NFData) -instance Marshal (Network, Ctx) XPubKey where-  marshalGet (net, ctx) = do+instance Marshal Network XPubKey where+  marshalGet net = do     ver <- getWord32be     unless (ver == net.xPubPrefix) $       fail "Get: Invalid version for extended public key"@@ -277,36 +278,36 @@     p <- deserialize     i <- getWord32be     checkMasterFields d p i-    XPubKey d p i <$> deserialize <*> getCompressedPubKey ctx+    XPubKey d p i <$> deserialize <*> getCompressedPubKey -  marshalPut (net, ctx) k = do+  marshalPut net k = do     putWord32be net.xPubPrefix     putWord8 k.depth     serialize k.parent     putWord32be k.index     serialize k.chain-    marshalPut ctx $ wrapPubKey True k.key+    serialize $ wrapPubKey True k.key -instance MarshalJSON (Network, Ctx) XPubKey where-  unmarshalValue (net, ctx) =+instance MarshalJSON Network XPubKey where+  unmarshalValue net =     withText "XPubKey" $ \t ->-      case xPubImport net ctx t of+      case xPubImport net t of         Nothing -> fail "could not read xpub"         Just x -> return x -  marshalValue (net, ctx) = Aeson.String . xPubExport net ctx+  marshalValue net = Aeson.String . xPubExport net -  marshalEncoding (net, ctx) = text . xPubExport net ctx+  marshalEncoding net = text . xPubExport net  -- | Read the public key of an extended key. BIP32 serializes it in 33 bytes, -- the compressed form. The 65-byte form is refused, so that an extended key -- has one binary form of 78 bytes.-getCompressedPubKey :: (MonadGet m) => Ctx -> m PubKey-getCompressedPubKey ctx = do+getCompressedPubKey :: (MonadGet m) => m PubKey+getCompressedPubKey = do   bs <- getByteString 33   unless (B.head bs `elem` [0x02, 0x03]) $     fail "Extended key must hold a compressed public key"-  case importPubKey ctx bs of+  case importPubKey bs of     Nothing -> fail "Extended key holds an invalid public key"     Just k -> return k @@ -344,8 +345,8 @@ -- | Derive an extended public key from an extended private key. This function -- will preserve the depth, parent, index and chaincode fields of the extended -- private keys.-deriveXPubKey :: Ctx -> XPrvKey -> XPubKey-deriveXPubKey ctx (XPrvKey d p i c k) = XPubKey d p i c (derivePubKey ctx k)+deriveXPubKey :: XPrvKey -> XPubKey+deriveXPubKey (XPrvKey d p i c k) = XPubKey d p i c (derivePubKey k)  -- | Compute a private, soft child key derivation. A private soft derivation -- will allow the equivalent extended public key to derive the public key for@@ -357,52 +358,50 @@ -- and one of the extended child private keys as this would compromise the -- extended parent private key. prvSubKey ::-  Ctx ->   -- | extended parent private key   XPrvKey ->   -- | child derivation index   KeyIndex ->   -- | extended child private key   XPrvKey-prvSubKey ctx xkey child = orThrow (tryPrvSubKey ctx xkey child)+prvSubKey xkey child = orThrow (tryPrvSubKey xkey child)  -- | 'prvSubKey' with its failures as an error value.-tryPrvSubKey :: Ctx -> XPrvKey -> KeyIndex -> Either String XPrvKey-tryPrvSubKey ctx xkey child = do+tryPrvSubKey :: XPrvKey -> KeyIndex -> Either String XPrvKey+tryPrvSubKey xkey child = do   unless (child < 0x80000000) $ Left hardIndexError   depth <- nextDepth xkey.depth   k <-     maybeToEither "Invalid prvSubKey derivation" $-      tweakSecKey ctx xkey.key a-  return $ XPrvKey depth (xPrvFP ctx xkey) child c k+      tweakSecKey xkey.key a+  return $ XPrvKey depth (xPrvFP xkey) child c k   where-    pK = (deriveXPubKey ctx xkey).key-    m = B.append (exportPubKey ctx True pK) (runPutS (serialize child))+    pK = (deriveXPubKey xkey).key+    m = B.append (exportPubKey True pK) (runPutS (serialize child))     (a, c) = split512 $ hmac512 (runPutS $ serialize xkey.chain) m  -- | Compute a public, soft child key derivation. Given a parent key /M/ -- and a derivation index /i/, this function will compute /M\/i/. pubSubKey ::-  Ctx ->   -- | extended parent public key   XPubKey ->   -- | child derivation index   KeyIndex ->   -- | extended child public key   XPubKey-pubSubKey ctx xKey child = orThrow (tryPubSubKey ctx xKey child)+pubSubKey xKey child = orThrow (tryPubSubKey xKey child)  -- | 'pubSubKey' with its failures as an error value.-tryPubSubKey :: Ctx -> XPubKey -> KeyIndex -> Either String XPubKey-tryPubSubKey ctx xKey child = do+tryPubSubKey :: XPubKey -> KeyIndex -> Either String XPubKey+tryPubSubKey xKey child = do   unless (child < 0x80000000) $ Left hardIndexError   depth <- nextDepth xKey.depth   pK <-     maybeToEither "Invalid pubSubKey derivation" $-      tweakPubKey ctx xKey.key a-  return $ XPubKey depth (xPubFP ctx xKey) child c pK+      tweakPubKey xKey.key a+  return $ XPubKey depth (xPubFP xKey) child c pK   where-    m = B.append (exportPubKey ctx True xKey.key) (runPutS $ serialize child)+    m = B.append (exportPubKey True xKey.key) (runPutS $ serialize child)     (a, c) = split512 $ hmac512 (runPutS $ serialize xKey.chain) m  -- | Compute a hard child key derivation. Hard derivations can only be computed@@ -412,24 +411,23 @@ -- parent private key. Given a parent key /m/ and a derivation index /i/, this -- function will compute /m\/i'/. hardSubKey ::-  Ctx ->   -- | extended parent private key   XPrvKey ->   -- | child derivation index   KeyIndex ->   -- | extended child private key   XPrvKey-hardSubKey ctx xkey child = orThrow (tryHardSubKey ctx xkey child)+hardSubKey xkey child = orThrow (tryHardSubKey xkey child)  -- | 'hardSubKey' with its failures as an error value.-tryHardSubKey :: Ctx -> XPrvKey -> KeyIndex -> Either String XPrvKey-tryHardSubKey ctx xkey child = do+tryHardSubKey :: XPrvKey -> KeyIndex -> Either String XPrvKey+tryHardSubKey xkey child = do   unless (child < 0x80000000) $ Left hardIndexError   depth <- nextDepth xkey.depth   k <-     maybeToEither "Invalid hardSubKey derivation" $-      tweakSecKey ctx xkey.key a-  return $ XPrvKey depth (xPrvFP ctx xkey) i c k+      tweakSecKey xkey.key a+  return $ XPrvKey depth (xPrvFP xkey) i c k   where     i = setBit child 31     m = B.append (bsPadPrvKey xkey.key) (runPutS $ serialize i)@@ -480,70 +478,70 @@ xPubChild k = clearBit k.index 31  -- | Computes the key identifier of an extended private key.-xPrvID :: Ctx -> XPrvKey -> Hash160-xPrvID ctx = xPubID ctx . deriveXPubKey ctx+xPrvID :: XPrvKey -> Hash160+xPrvID = xPubID . deriveXPubKey  -- | Computes the key identifier of an extended public key.-xPubID :: Ctx -> XPubKey -> Hash160-xPubID ctx =+xPubID :: XPubKey -> Hash160+xPubID =   ripemd160     . runPutS     . serialize     . sha256-    . exportPubKey ctx True+    . exportPubKey True     . (.key)  -- | Computes the key fingerprint of an extended private key.-xPrvFP :: Ctx -> XPrvKey -> Fingerprint-xPrvFP ctx =+xPrvFP :: XPrvKey -> Fingerprint+xPrvFP =   fromRight err     . runGetS deserialize     . B.take 4     . runPutS     . serialize-    . xPrvID ctx+    . xPrvID   where     err = error "Could not decode xPrvFP"  -- | Computes the key fingerprint of an extended public key.-xPubFP :: Ctx -> XPubKey -> Fingerprint-xPubFP ctx =+xPubFP :: XPubKey -> Fingerprint+xPubFP =   fromRight err     . runGetS deserialize     . B.take 4     . runPutS     . serialize-    . xPubID ctx+    . xPubID   where     err = error "Could not decode xPubFP"  -- | Compute a standard P2PKH address for an extended public key.-xPubAddr :: Ctx -> XPubKey -> Address-xPubAddr ctx xkey = pubKeyAddr ctx (wrapPubKey True xkey.key)+xPubAddr :: XPubKey -> Address+xPubAddr xkey = pubKeyAddr (wrapPubKey True xkey.key)  -- | Compute a SegWit P2WPKH address for an extended public key. Extended -- public keys are always compressed, so the address always exists.-xPubWitnessAddr :: Ctx -> XPubKey -> Address-xPubWitnessAddr ctx xkey = p2wpkhAddr (xPubKeyHash ctx xkey)+xPubWitnessAddr :: XPubKey -> Address+xPubWitnessAddr xkey = p2wpkhAddr (xPubKeyHash xkey)  -- | Compute a backwards-compatible SegWit P2SH-P2WPKH address for an extended -- public key. Extended public keys are always compressed, so the address -- always exists.-xPubCompatWitnessAddr :: Ctx -> XPubKey -> Address-xPubCompatWitnessAddr ctx xkey =-  p2shP2wpkhAddr (xPubKeyHash ctx xkey)+xPubCompatWitnessAddr :: XPubKey -> Address+xPubCompatWitnessAddr xkey =+  p2shP2wpkhAddr (xPubKeyHash xkey)  -- | HASH160 of the compressed public key of an extended public key.-xPubKeyHash :: Ctx -> XPubKey -> Hash160-xPubKeyHash ctx xkey = addressHash (marshal ctx (wrapPubKey True xkey.key))+xPubKeyHash :: XPubKey -> Hash160+xPubKeyHash xkey = addressHash (encodeSerial (wrapPubKey True xkey.key))  -- | Exports an extended private key to the BIP32 key export format ('Base58'). xPrvExport :: Network -> XPrvKey -> Base58 xPrvExport net = encodeBase58Check . marshal net  -- | Exports an extended public key to the BIP32 key export format ('Base58').-xPubExport :: Network -> Ctx -> XPubKey -> Base58-xPubExport net ctx = encodeBase58Check . marshal (net, ctx)+xPubExport :: Network -> XPubKey -> Base58+xPubExport net = encodeBase58Check . marshal net  -- | Decodes a BIP32 encoded extended private key. This function will fail if -- invalid base 58 characters are detected, if the checksum fails, if the@@ -555,9 +553,9 @@ -- | Decodes a BIP32 encoded extended public key. This function will fail if -- invalid base 58 characters are detected, if the checksum fails, if the -- payload is not exactly 78 bytes, or if the key fails the checks of BIP32.-xPubImport :: Network -> Ctx -> Base58 -> Maybe XPubKey-xPubImport net ctx =-  eitherToMaybe . unmarshal (net, ctx) <=< decodeExtendedKey+xPubImport :: Network -> Base58 -> Maybe XPubKey+xPubImport net =+  eitherToMaybe . unmarshal net <=< decodeExtendedKey  -- | Size in bytes of a serialized extended key, without its checksum. extendedKeySize :: Int@@ -588,66 +586,66 @@  -- | Cyclic list of all private soft child key derivations of a parent key -- starting from an offset index.-prvSubKeys :: Ctx -> XPrvKey -> KeyIndex -> [(XPrvKey, KeyIndex)]-prvSubKeys ctx k = map (\i -> (prvSubKey ctx k i, i)) . cycleIndex+prvSubKeys :: XPrvKey -> KeyIndex -> [(XPrvKey, KeyIndex)]+prvSubKeys k = map (\i -> (prvSubKey k i, i)) . cycleIndex  -- | Cyclic list of all public soft child key derivations of a parent key -- starting from an offset index.-pubSubKeys :: Ctx -> XPubKey -> KeyIndex -> [(XPubKey, KeyIndex)]-pubSubKeys ctx k = map (\i -> (pubSubKey ctx k i, i)) . cycleIndex+pubSubKeys :: XPubKey -> KeyIndex -> [(XPubKey, KeyIndex)]+pubSubKeys k = map (\i -> (pubSubKey k i, i)) . cycleIndex  -- | Cyclic list of all hard child key derivations of a parent key starting -- from an offset index.-hardSubKeys :: Ctx -> XPrvKey -> KeyIndex -> [(XPrvKey, KeyIndex)]-hardSubKeys ctx k = map (\i -> (hardSubKey ctx k i, i)) . cycleIndex+hardSubKeys :: XPrvKey -> KeyIndex -> [(XPrvKey, KeyIndex)]+hardSubKeys k = map (\i -> (hardSubKey k i, i)) . cycleIndex  -- | Derive a standard address from an extended public key and an index.-deriveAddr :: Ctx -> XPubKey -> KeyIndex -> (Address, PubKey)-deriveAddr ctx k i =-  (xPubAddr ctx key, key.key)+deriveAddr :: XPubKey -> KeyIndex -> (Address, PubKey)+deriveAddr k i =+  (xPubAddr key, key.key)   where-    key = pubSubKey ctx k i+    key = pubSubKey k i  -- | Derive a SegWit P2WPKH address from an extended public key and an index.-deriveWitnessAddr :: Ctx -> XPubKey -> KeyIndex -> (Address, PubKey)-deriveWitnessAddr ctx k i =-  (xPubWitnessAddr ctx key, key.key)+deriveWitnessAddr :: XPubKey -> KeyIndex -> (Address, PubKey)+deriveWitnessAddr k i =+  (xPubWitnessAddr key, key.key)   where-    key = pubSubKey ctx k i+    key = pubSubKey k i  -- | Derive a backwards-compatible SegWit P2SH-P2WPKH address from an extended -- public key and an index.-deriveCompatWitnessAddr :: Ctx -> XPubKey -> KeyIndex -> (Address, PubKey)-deriveCompatWitnessAddr ctx k i =-  (xPubCompatWitnessAddr ctx key, key.key)+deriveCompatWitnessAddr :: XPubKey -> KeyIndex -> (Address, PubKey)+deriveCompatWitnessAddr k i =+  (xPubCompatWitnessAddr key, key.key)   where-    key = pubSubKey ctx k i+    key = pubSubKey k i  -- | Cyclic list of all addresses derived from a public key starting from an -- offset index.-deriveAddrs :: Ctx -> XPubKey -> KeyIndex -> [(Address, PubKey, KeyIndex)]-deriveAddrs ctx k =+deriveAddrs :: XPubKey -> KeyIndex -> [(Address, PubKey, KeyIndex)]+deriveAddrs k =   map f . cycleIndex   where-    f i = let (a, key) = deriveAddr ctx k i in (a, key, i)+    f i = let (a, key) = deriveAddr k i in (a, key, i)  -- | Cyclic list of all SegWit P2WPKH addresses derived from a public key -- starting from an offset index. deriveWitnessAddrs ::-  Ctx -> XPubKey -> KeyIndex -> [(Address, PubKey, KeyIndex)]-deriveWitnessAddrs ctx k =+  XPubKey -> KeyIndex -> [(Address, PubKey, KeyIndex)]+deriveWitnessAddrs k =   map f . cycleIndex   where-    f i = let (a, key) = deriveWitnessAddr ctx k i in (a, key, i)+    f i = let (a, key) = deriveWitnessAddr k i in (a, key, i)  -- | Cyclic list of all backwards-compatible SegWit P2SH-P2WPKH addresses -- derived from a public key starting from an offset index. deriveCompatWitnessAddrs ::-  Ctx -> XPubKey -> KeyIndex -> [(Address, PubKey, KeyIndex)]-deriveCompatWitnessAddrs ctx k =+  XPubKey -> KeyIndex -> [(Address, PubKey, KeyIndex)]+deriveCompatWitnessAddrs k =   map f . cycleIndex   where-    f i = let (a, key) = deriveCompatWitnessAddr ctx k i in (a, key, i)+    f i = let (a, key) = deriveCompatWitnessAddr k i in (a, key, i)  -- | Derive a pay-to-script-hash multisig address from a list of public keys, -- the number of required signatures /m/ and a derivation index. The@@ -661,32 +659,31 @@ -- spent. For 16 to 20 keys, build a pay-to-witness-script-hash address from -- the redeem script with 'payToWitnessScriptAddress'. deriveMSAddr ::-  Ctx -> [XPubKey] -> Int -> KeyIndex -> Either String (Address, RedeemScript)-deriveMSAddr ctx keys m i = do-  addr <- payToScriptAddress ctx rdm+  [XPubKey] -> Int -> KeyIndex -> Either String (Address, RedeemScript)+deriveMSAddr keys m i = do+  addr <- payToScriptAddress rdm   return (addr, rdm)   where-    rdm = sortMulSig ctx $ PayMulSig k m-    k = map (wrapPubKey True . (.key) . flip (pubSubKey ctx) i) keys+    rdm = sortMulSig $ PayMulSig k m+    k = map (wrapPubKey True . (.key) . flip pubSubKey i) keys  -- | Cyclic list of all multisig addresses derived from a list of public keys, -- a number of required signatures /m/ and starting from an offset index. The -- derivation type is a public, soft derivation. Fails as 'deriveMSAddr' does. deriveMSAddrs ::-  Ctx ->   [XPubKey] ->   Int ->   KeyIndex ->   Either String [(Address, RedeemScript, KeyIndex)]-deriveMSAddrs ctx keys m start = do+deriveMSAddrs keys m start = do   -- Whether an address can be made depends on the number of keys and on m,   -- not on the index. One check therefore covers the whole list, which stays   -- lazy and endless.-  _ <- deriveMSAddr ctx keys m start+  _ <- deriveMSAddr keys m start   return     [ (a, rdm, i)-      | i <- cycleIndex start,-        Right (a, rdm) <- [deriveMSAddr ctx keys m i]+    | i <- cycleIndex start,+      Right (a, rdm) <- [deriveMSAddr keys m i]     ]  -- | Helper function to go through derivation indices. Throws@@ -917,35 +914,35 @@ -- 'DerivationException' when the path cannot be followed, for example when it -- leads below depth 255. Use 'tryDerivePath' for a path that comes from -- outside, such as the path of a PSBT record.-derivePath :: Ctx -> DerivPathI t -> XPrvKey -> XPrvKey-derivePath ctx path = orThrow . tryDerivePath ctx path+derivePath :: DerivPathI t -> XPrvKey -> XPrvKey+derivePath path = orThrow . tryDerivePath path  -- | Derive a public key from a soft derivation path. Throws -- 'DerivationException' when the path cannot be followed. Use -- 'tryDerivePubPath' for a path that comes from outside.-derivePubPath :: Ctx -> SoftPath -> XPubKey -> XPubKey-derivePubPath ctx path = orThrow . tryDerivePubPath ctx path+derivePubPath :: SoftPath -> XPubKey -> XPubKey+derivePubPath path = orThrow . tryDerivePubPath path  -- | Derive a private key from a derivation path, with an error value when the -- path cannot be followed. BIP32 stores the depth of a key in one byte, so a -- path that leads below depth 255 has no key. That is checked before any key -- is derived, so a path that is far too long costs nothing.-tryDerivePath :: Ctx -> DerivPathI t -> XPrvKey -> Either String XPrvKey-tryDerivePath ctx path key = do+tryDerivePath :: DerivPathI t -> XPrvKey -> Either String XPrvKey+tryDerivePath path key = do   checkPathDepth key.depth steps   foldM step key steps   where     steps = pathSteps path     step k (hard, i)-      | hard = tryHardSubKey ctx k i-      | otherwise = tryPrvSubKey ctx k i+      | hard = tryHardSubKey k i+      | otherwise = tryPrvSubKey k i  -- | Derive a public key from a soft derivation path, with an error value when -- the path cannot be followed. See 'tryDerivePath'.-tryDerivePubPath :: Ctx -> SoftPath -> XPubKey -> Either String XPubKey-tryDerivePubPath ctx path key = do+tryDerivePubPath :: SoftPath -> XPubKey -> Either String XPubKey+tryDerivePubPath path key = do   checkPathDepth key.depth steps-  foldM (tryPubSubKey ctx) key (map snd steps)+  foldM tryPubSubKey key (map snd steps)   where     steps = pathSteps path @@ -1187,59 +1184,57 @@ -- path starts with /M/, a public key will be returned. Private derivations on a -- public key, public derivations with a hard segment, and a path that leads -- below depth 255 return an error value. The function does not throw.-applyPath :: Ctx -> ParsedPath -> XKey -> Either String XKey-applyPath ctx path key =+applyPath :: ParsedPath -> XKey -> Either String XKey+applyPath path key =   first ("applyPath: " <>) $     case (path, key) of       (ParsedPrv _, XPrv k n) -> (`XPrv` n) <$> derivePrv k       (ParsedPrv _, XPub {}) -> Left "Invalid public key"-      (ParsedPub _, XPrv k n) -> (`XPub` n) . deriveXPubKey ctx <$> derivePrv k+      (ParsedPub _, XPrv k n) -> (`XPub` n) . deriveXPubKey <$> derivePrv k       (ParsedPub _, XPub k n) -> (`XPub` n) <$> derivePub k       -- For empty parsed paths, we take a hint from the provided key       (ParsedEmpty _, XPrv k n) -> (`XPrv` n) <$> derivePrv k       (ParsedEmpty _, XPub k n) -> (`XPub` n) <$> derivePub k   where-    derivePrv = tryDerivePath ctx path.get+    derivePrv = tryDerivePath path.get     derivePub k = do       soft <- maybeToEither "Invalid hard derivation" (toSoft path.get)-      tryDerivePubPath ctx soft k+      tryDerivePubPath soft k  {- Helpers for derivation paths and addresses -}  -- | Derive an address from a given parent path.-derivePathAddr :: Ctx -> XPubKey -> SoftPath -> KeyIndex -> (Address, PubKey)-derivePathAddr ctx key path = deriveAddr ctx (derivePubPath ctx path key)+derivePathAddr :: XPubKey -> SoftPath -> KeyIndex -> (Address, PubKey)+derivePathAddr key path = deriveAddr (derivePubPath path key)  -- | Cyclic list of all addresses derived from a given parent path and starting -- from the given offset index. derivePathAddrs ::-  Ctx -> XPubKey -> SoftPath -> KeyIndex -> [(Address, PubKey, KeyIndex)]-derivePathAddrs ctx key path = deriveAddrs ctx (derivePubPath ctx path key)+  XPubKey -> SoftPath -> KeyIndex -> [(Address, PubKey, KeyIndex)]+derivePathAddrs key path = deriveAddrs (derivePubPath path key)  -- | Derive a multisig address from a given parent path. The number of required -- signatures (m in m of n) is also needed. Fails as 'deriveMSAddr' does. derivePathMSAddr ::-  Ctx ->   [XPubKey] ->   SoftPath ->   Int ->   KeyIndex ->   Either String (Address, RedeemScript)-derivePathMSAddr ctx keys path =-  deriveMSAddr ctx $ map (derivePubPath ctx path) keys+derivePathMSAddr keys path =+  deriveMSAddr $ map (derivePubPath path) keys  -- | Cyclic list of all multisig addresses derived from a given parent path and -- starting from the given offset index. The number of required signatures -- (m in m of n) is also needed. Fails as 'deriveMSAddr' does. derivePathMSAddrs ::-  Ctx ->   [XPubKey] ->   SoftPath ->   Int ->   KeyIndex ->   Either String [(Address, RedeemScript, KeyIndex)]-derivePathMSAddrs ctx keys path =-  deriveMSAddrs ctx $ map (derivePubPath ctx path) keys+derivePathMSAddrs keys path =+  deriveMSAddrs $ map (derivePubPath path) keys  {- Utilities for extended keys -} 
src/Haskoin/Crypto/Keys/Extended/Internal.hs view
@@ -20,9 +20,9 @@   ) import Data.Aeson.Encoding (text) import Data.Binary (Binary (..))+import Data.ByteString qualified as B import Data.Bytes.Get (getWord32be) import Data.Bytes.Put (putWord32be)-import Data.ByteString qualified as B import Data.Bytes.Serial (Serial (..)) import Data.Hashable (Hashable) import Data.Serialize (Serialize (..))
src/Haskoin/Crypto/Keys/Slip39.hs view
@@ -641,7 +641,10 @@     (g : ms) | length ms == groupCount -> Right (g, ms)     _ ->       Left $-        "A scheme of " <> show groupCount <> " groups takes " <> show (groupCount + 1)+        "A scheme of "+          <> show groupCount+          <> " groups takes "+          <> show (groupCount + 1)           <> " sets of random values: one for the split among the groups, then one per group"   groupShares <- splitSecret scheme.groupThreshold groupCount ems.ciphertext groupRandom   forM (zip3 scheme.groups groupShares memberRandoms) $ \((threshold, members), (gi, groupSecret), random) -> do@@ -658,7 +661,7 @@             memberThreshold = threshold,             value = v           }-        | (mi, v) <- memberShares+      | (mi, v) <- memberShares       ]   where     groupCount = length scheme.groups
src/Haskoin/Crypto/Signature.hs view
@@ -54,15 +54,17 @@     e = error "Could not convert 32-byte hash to secp256k1 message"  -- | Sign a 256-bit hash using secp256k1 elliptic curve.-signHash :: Ctx -> SecKey -> Hash256 -> Sig-signHash ctx k = signMsg ctx k . hashToMsg+signHash :: SecKey -> Hash256 -> Sig+signHash k = signMsg k . hashToMsg  -- | Verify an ECDSA signature for a 256-bit hash.-verifyHashSig :: Ctx -> Hash256 -> Sig -> PubKey -> Bool-verifyHashSig ctx h s p = verifySig ctx p (normalizeSig ctx s) (hashToMsg h)+verifyHashSig :: Hash256 -> Sig -> PubKey -> Bool+verifyHashSig h s p = verifySig p (normalizeSig s) (hashToMsg h) -instance Marshal Ctx Sig where-  marshalGet ctx = do+instance Serial Sig where+  {-# INLINEABLE serialize #-}+  {-# INLINEABLE deserialize #-}+  deserialize = do     l <- lookAhead $ do       t <- getWord8       -- 0x30 is DER sequence type@@ -74,21 +76,31 @@       when (l >= 0x80) $ fail "Multi-octect length not supported"       return $ fromIntegral l     bs <- getByteString $ l + 2-    case decodeStrictSig ctx bs of+    case decodeStrictSig bs of       Just s -> return s       Nothing -> fail "Invalid signature" -  marshalPut ctx s = putByteString $ exportSig ctx s+  serialize s = putByteString $ exportSig s -instance MarshalJSON Ctx Sig where-  marshalValue ctx = String . encodeHex . exportSig ctx-  marshalEncoding ctx = hexEncoding . L.fromStrict . exportSig ctx+instance Binary Sig where+  put = serialize+  get = deserialize++instance Serialize Sig where+  put = serialize+  get = deserialize++instance ToJSON Sig where+  toJSON = String . encodeHex . exportSig+  toEncoding = hexEncoding . L.fromStrict . exportSig++instance FromJSON Sig where   -- Decoding applies the same rules as the binary form, 'decodeStrictSig'.   -- The error message does not repeat the text. The text comes from outside   -- and can be of any length.-  unmarshalValue ctx =+  parseJSON =     withText "Sig" $ \t ->-      case decodeHex t >>= decodeStrictSig ctx of+      case decodeHex t >>= decodeStrictSig of         Nothing -> fail "Could not decode signature"         Just s -> return s @@ -98,7 +110,7 @@ -- rule, so a block may hold a signature with a high s. The decoders of this -- module do not apply it. Check it with this function where the relay rules -- matter. 'signHash' always makes a signature that passes.-isCanonicalHalfOrder :: Ctx -> Sig -> Bool+isCanonicalHalfOrder :: Sig -> Bool isCanonicalHalfOrder = isLowS  -- | Decode a signature from its strict DER encoding, the encoding that BIP 66@@ -111,7 +123,7 @@ -- -- A high s is accepted, since BIP 66 allows it and such signatures are in the -- block chain. Use 'isCanonicalHalfOrder' for the low-S relay rule.-decodeStrictSig :: Ctx -> ByteString -> Maybe Sig+decodeStrictSig :: ByteString -> Maybe Sig decodeStrictSig = importSig  -- | Verify a Schnorr signature of Bitcoin Cash: 64 bytes, @r@ then @s@,@@ -134,29 +146,29 @@ -- Node, and the tests hold it to the test vectors of that code. It only -- verifies: nothing here is secret, so it is not written to run in -- constant time.-verifyCashSchnorr :: Ctx -> PubKey -> ByteString -> Hash256 -> Bool-verifyCashSchnorr ctx pub sig h+verifyCashSchnorr :: PubKey -> ByteString -> Hash256 -> Bool+verifyCashSchnorr pub sig h   | BS.length sig /= 64 = False   | r >= fieldP || s >= orderN = False   | otherwise = case combined of       Nothing -> False       Just point ->-        let (x, y) = BS.splitAt 32 (BS.drop 1 (exportPubKey ctx False point))+        let (x, y) = BS.splitAt 32 (BS.drop 1 (exportPubKey False point))          in bsToInteger x == r && isSquare (bsToInteger y)   where     (rBytes, sBytes) = BS.splitAt 32 sig     r = bsToInteger rBytes     s = bsToInteger sBytes     digest = runPutS (serialize h)-    e = bsToInteger (runPutS (serialize (sha256 (rBytes <> exportPubKey ctx True pub <> digest)))) `mod` orderN+    e = bsToInteger (runPutS (serialize (sha256 (rBytes <> exportPubKey True pub <> digest)))) `mod` orderN     -- s*G, when s is not zero-    sG = derivePubKey ctx <$> secKey (word256 s)+    sG = derivePubKey <$> secKey (word256 s)     -- -e*P, when e is not zero-    eP = tweak (word256 ((orderN - e) `mod` orderN)) >>= tweakMulPubKey ctx pub+    eP = tweak (word256 ((orderN - e) `mod` orderN)) >>= tweakMulPubKey pub     -- their sum, which is nothing when it is the point at infinity     combined = case catMaybes [sG, eP] of       [] -> Nothing-      points -> combinePubKeys ctx points+      points -> combinePubKeys points     -- Euler's criterion     isSquare y = powMod y ((fieldP - 1) `div` 2) fieldP == 1     word256 n = let b = integerToBS n in BS.replicate (32 - BS.length b) 0 <> b
src/Haskoin/Network/Bloom.hs view
@@ -44,7 +44,6 @@ import Control.Applicative ((<|>)) import Control.DeepSeq import Control.Monad (guard, when)-import Crypto.Secp256k1 (Ctx) import Data.Binary (Binary (..)) import Data.Bits import Data.ByteString (ByteString)@@ -336,17 +335,14 @@ -- with 02 or 03, or of 65 bytes that starts with 04, 06 or 07. It does not -- have to be a point of the curve. Non-standard scripts are scanned like any -- other. An empty filter matches every transaction and gets no outpoints.------ The context is not used. It is kept so that callers do not have to change. bloomRelevantUpdate ::-  Ctx ->   -- | Bloom filter   BloomFilter ->   -- | transaction to test   Tx ->   -- | the filter, updated, when the transaction is relevant   Maybe BloomFilter-bloomRelevantUpdate _ b tx+bloomRelevantUpdate b tx   | S.null b.array = Just b   | hashFound || outputFound = Just updated   | any inputMatches tx.inputs = Just b
src/Haskoin/Network/Common.hs view
@@ -82,12 +82,12 @@ import Control.Monad (forM_, liftM2, unless, when) import Data.Binary (Binary (..)) import Data.Bits (shiftL, shiftR, (.&.), (.|.))-import Data.Int (Int32, Int64) import Data.ByteString (ByteString) import Data.ByteString qualified as B import Data.Bytes.Get import Data.Bytes.Put import Data.Bytes.Serial+import Data.Int (Int32, Int64) import Data.Serialize (Serialize (..)) import Data.String import Data.String.Conversions (cs)@@ -805,6 +805,7 @@               show n ++ "-byte encoding of",               show x             ]+  {-# INLINEABLE deserialize #-}    serialize (VarInt x)     | x < 0xfd =@@ -818,6 +819,7 @@     | otherwise = do         putWord8 0xff         putWord64le x+  {-# INLINEABLE serialize #-}  instance Binary VarInt where   put = serialize@@ -829,6 +831,7 @@  putVarInt :: (MonadPut m, Integral a) => a -> m () putVarInt = serialize . VarInt . fromIntegral+{-# INLINE putVarInt #-}  -- | Largest number of elements that a serialized list may announce, and -- largest number of bytes that a serialized string may announce. Bitcoin Core@@ -845,6 +848,7 @@   when (count > maxListSize) $     fail ("List count too large: " ++ show count)   getElements count element+{-# INLINEABLE getVarIntList #-}  -- | Read the given number of elements, in a loop that keeps nothing but the -- elements read so far.@@ -855,6 +859,7 @@     go n acc = do       x <- element       go (n - 1) (x : acc)+{-# INLINEABLE getElements #-}  -- | Read a list like 'getVarIntList', and fail when its count is above the -- given limit. The count is checked right after it is read, before any@@ -865,6 +870,7 @@   when (count > limit) $     fail (name ++ ": too many entries: " ++ show count ++ ", the limit is " ++ show limit)   getElements count element+{-# INLINEABLE getVarIntListMax #-}  -- | Largest number of entries in an @inv@ or a @getdata@ message. Bitcoin -- Core and Bitcoin Cash Node punish a peer that sends more (@MAX_INV_SZ@).@@ -896,6 +902,7 @@ putVarIntList element xs = do   putVarInt (length xs)   mapM_ element xs+{-# INLINEABLE putVarIntList #-}  -- | Read bytes that start with their count as a 'VarInt'. A count above -- 'maxListSize' fails the parse. A count of zero gives the one shared empty@@ -909,12 +916,14 @@   if count == 0     then return B.empty     else getByteString (fromIntegral count)+{-# INLINEABLE getVarIntBytes #-}  -- | Write bytes with their count as a 'VarInt' in front. putVarIntBytes :: (MonadPut m) => ByteString -> m () putVarIntBytes bs = do   putVarInt (B.length bs)   putByteString bs+{-# INLINEABLE putVarIntBytes #-}  -- | Data type for serialization of variable-length strings. newtype VarString = VarString {get :: ByteString}
src/Haskoin/Network/Data.hs view
@@ -134,4 +134,4 @@ getNetworkTx net   | net.segWit = deserialize   | otherwise = parseLegacyTx-+{-# INLINE getNetworkTx #-}
src/Haskoin/Network/Message.hs view
@@ -45,6 +45,7 @@ import Haskoin.Network.CompactBlock import Haskoin.Network.Data import Haskoin.Transaction.Common+import Haskoin.Util.Direct (decodeDirect, encodeDirect)  -- | Data type representing the header of a 'Message'. All messages sent between -- nodes contain a message header.@@ -214,7 +215,14 @@   unless     (checkSum32 payload == chk)     (fail $ "get: Invalid message checksum: " ++ show chk)-  either fail return (runGetS (getPayload net cmd len) payload)+  -- Blocks and transactions are nearly all the bytes that a node+  -- downloads. Their payload is whole here, so it is read where it is, with+  -- 'decodeDirect', which gives what 'runGetS' gives. The parsers of the+  -- other messages are not compiled for that, and stay with cereal.+  let parse+        | cmd == MCBlock || cmd == MCTx = decodeDirect (getPayload net cmd len)+        | otherwise = runGetS (getPayload net cmd len)+  either fail return (parse payload)  getPayload :: (MonadGet m) => Network -> MessageCommand -> Word32 -> m Message getPayload net cmd len =@@ -273,8 +281,8 @@           MNotFound m -> (MCNotFound, runPutS $ serialize m)           MGetBlocks m -> (MCGetBlocks, runPutS $ serialize m)           MGetHeaders m -> (MCGetHeaders, runPutS $ serialize m)-          MTx m -> (MCTx, runPutS $ serialize m)-          MBlock m -> (MCBlock, runPutS $ serialize m)+          MTx m -> (MCTx, encodeDirect (serialize m))+          MBlock m -> (MCBlock, encodeDirect (serialize m))           MMerkleBlock m -> (MCMerkleBlock, runPutS $ serialize m)           MHeaders m -> (MCHeaders, runPutS $ serialize m)           MGetAddr -> (MCGetAddr, B.empty)
src/Haskoin/Script/Common.hs view
@@ -76,6 +76,8 @@   toEncoding = hexEncoding . runPutL . serialize  instance Serial Script where+  {-# INLINEABLE serialize #-}+  {-# INLINEABLE deserialize #-}   deserialize =     Script <$> getScriptOps     where@@ -262,6 +264,8 @@ pattern OP_CHECKSIGADD = OP_CHECKDATASIG  instance Serial ScriptOp where+  {-# INLINEABLE serialize #-}+  {-# INLINEABLE deserialize #-}   deserialize = go . fromIntegral =<< getWord8     where       go op
src/Haskoin/Script/SigHash.hs view
@@ -413,17 +413,17 @@   | i < 0 || i >= length tx.inputs =       Left "txSigHashForkId: input index out of range"   | otherwise = Right . doubleSHA256 . runPutS $ do-    putWord32le tx.version-    serialize hashPrevouts-    serialize hashSequence-    serialize (tx.inputs !! i).outpoint-    putByteString prefix-    putScript out-    putWord64le v-    putWord32le (tx.inputs !! i).sequence-    serialize hashOutputs-    putWord32le tx.locktime-    putWord32le $ fromIntegral hashType+      putWord32le tx.version+      serialize hashPrevouts+      serialize hashSequence+      serialize (tx.inputs !! i).outpoint+      putByteString prefix+      putScript out+      putWord64le v+      putWord32le (tx.inputs !! i).sequence+      serialize hashOutputs+      putWord32le tx.locktime+      putWord32le $ fromIntegral hashType   where     hashType = case net.sigHashForkId of       Just forkId -> sigHashAddForkId sh forkId@@ -546,19 +546,19 @@   | TxSignatureEmpty   deriving (Eq, Show, Read, Generic, NFData) -instance Marshal (Network, Ctx) TxSignature where-  marshalPut (net, ctx) TxSignatureEmpty = return ()-  marshalPut (net, ctx) (TxSignature sig (SigHash n)) = do-    marshalPut ctx sig+instance Marshal Network TxSignature where+  marshalPut net TxSignatureEmpty = return ()+  marshalPut net (TxSignature sig (SigHash n)) = do+    serialize sig     putWord8 (fromIntegral n) -  marshalGet (net, ctx) =+  marshalGet net =     bool decode empty =<< isEmpty     where       empty = return TxSignatureEmpty       decode = do-        sig <- marshalGet ctx-        unless (isCanonicalHalfOrder ctx sig) $+        sig <- deserialize+        unless (isCanonicalHalfOrder sig) $           fail "Non-canonical signature: S value is unnecessarily high"         sh <- fromIntegral <$> getWord8         when (isSigHashUnknown sh) $@@ -569,30 +569,30 @@           fail "Non-canonical signature: SIGHASH_FORKID is required on this network"         return $ TxSignature sig sh -instance MarshalJSON (Network, Ctx) TxSignature where-  marshalValue (net, ctx) = String . encodeHex . encodeTxSig net ctx+instance MarshalJSON Network TxSignature where+  marshalValue net = String . encodeHex . encodeTxSig net   marshalEncoding s = hexEncoding . runPutL . marshalPut s-  unmarshalValue (net, ctx) =+  unmarshalValue net =     withText "TxSignature" $ \t ->       case decodeHex t of         Nothing -> fail "Cannot decode hex signature"-        Just b -> case decodeTxSig net ctx b of+        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 -> Ctx -> TxSignature -> ByteString-encodeTxSig net ctx = runPutS . marshalPut (net, ctx)+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, and the fork id -- flag that the network asks for. The empty string is 'TxSignatureEmpty'. A -- signature that is valid by consensus alone does not decode.-decodeTxSig :: Network -> Ctx -> ByteString -> Either String TxSignature-decodeTxSig net ctx =+decodeTxSig :: Network -> ByteString -> Either String TxSignature+decodeTxSig net =   runGetS $ do-    sig <- marshalGet (net, ctx)+    sig <- marshalGet net     e <- isEmpty     unless e $       fail "Non-canonical signature: multiple hashtype bytes"
src/Haskoin/Script/Standard.hs view
@@ -60,9 +60,10 @@ import Control.DeepSeq import Control.Monad (guard, unless) import Crypto.Secp256k1-import Data.Aeson (ToJSON (..), Value (..), withText)+import Data.Aeson (FromJSON (..), ToJSON (..), Value (..), withText) import Data.Aeson.Encoding (Encoding, text) import Data.Aeson.Types (Parser)+import Data.Binary (Binary (..)) import Data.ByteString (ByteString) import Data.ByteString qualified as B import Data.Bytes.Get@@ -71,6 +72,7 @@ import Data.Function (on) import Data.Hashable import Data.List (sortBy)+import Data.Serialize (Serialize (..)) import Data.Word (Word8) import GHC.Generics (Generic) import Haskoin.Crypto.Hash@@ -111,16 +113,17 @@     DataCarrier {pushes :: ![ByteString]}   deriving (Eq, Show, Read, Generic, NFData) -instance MarshalJSON Ctx ScriptOutput where-  unmarshalValue ctx =+instance FromJSON ScriptOutput where+  parseJSON =     withText "ScriptOutput" $ \t ->       case decodeHex t of         Nothing -> fail "Could not decode hex script"-        Just bs -> either fail return $ unmarshal ctx bs+        Just bs -> either fail return $ decodeSerial bs -  marshalValue ctx = String . encodeHex . marshal ctx+instance ToJSON ScriptOutput where+  toJSON = String . encodeHex . encodeSerial -  marshalEncoding ctx = hexEncoding . runPutL . marshalPut ctx+  toEncoding = hexEncoding . runPutL . serialize  -- | Is script a pay-to-public-key output? isPayPK :: ScriptOutput -> Bool@@ -232,11 +235,11 @@ -- On Bitcoin Cash, an output that holds tokens starts with the token prefix -- byte 0xef and is not decoded. See 'Haskoin.Script.SigHash.txSigHashForkId' -- for what is not supported on that network.-decodeOutput :: Ctx -> Script -> Either String ScriptOutput-decodeOutput ctx s = case s.ops of+decodeOutput :: Script -> Either String ScriptOutput+decodeOutput s = case s.ops of   -- Pay to PubKey   [OP_PUSHDATA bs OPCODE, OP_CHECKSIG] ->-    PayPK <$> decodePubKey ctx bs+    PayPK <$> decodePubKey bs   -- Pay to PubKey Hash   [OP_DUP, OP_HASH160, OP_PUSHDATA bs OPCODE, OP_EQUALVERIFY, OP_CHECKSIG]     | B.length bs == 20 ->@@ -269,7 +272,7 @@   OP_RETURN : rest     | Just ds <- mapM pushOpData rest -> Right $ DataCarrier ds   -- Pay to MultiSig Keys-  _ -> case matchPayMulSig ctx s of+  _ -> case matchPayMulSig s of     Right x -> return x     Left _ -> Left "decodeOutput: Non-standard output" @@ -294,66 +297,77 @@ -- and a 'PayWitness' whose version is not 1 to 16 or whose program is not 2 -- to 40 bytes long. A version 0 program is a 'PayWitnessPKHash' or a -- 'PayWitnessScriptHash'.-encodeOutput :: Ctx -> ScriptOutput -> Either String Script-encodeOutput ctx s = Script <$> case s of-  -- Pay to PubKey-  (PayPK k) -> Right [opPushData $ marshal ctx k, OP_CHECKSIG]-  -- Pay to PubKey Hash Address-  (PayPKHash h) ->-    Right-      [ OP_DUP,-        OP_HASH160,-        opPushData $ runPutS $ serialize h,-        OP_EQUALVERIFY,-        OP_CHECKSIG-      ]-  -- Pay to MultiSig Keys-  (PayMulSig ps r)-    | r < 1 ->-        Left "encodeOutput: multisig must require at least one signature"-    | r > n ->-        Left "encodeOutput: multisig requires more signatures than it has keys"-    | n > maxMultisigKeys ->-        Left "encodeOutput: multisig has more than 20 keys"-    | otherwise ->-        let keys = map (opPushData . marshal ctx) ps-         in Right $ multisigCountOp r : keys ++ [multisigCountOp n, OP_CHECKMULTISIG]-    where-      n = length ps-  -- Pay to Script Hash Address-  (PayScriptHash h) ->-    Right [OP_HASH160, opPushData $ runPutS $ serialize h, OP_EQUAL]-  -- Pay to 256-bit Script Hash Address-  (PayScript32Hash h) ->-    Right [OP_HASH256, opPushData $ runPutS $ serialize h, OP_EQUAL]-  -- Pay to Witness PubKey Hash Address-  (PayWitnessPKHash h) ->-    Right [OP_0, opPushData $ runPutS $ serialize h]-  (PayWitnessScriptHash h) ->-    Right [OP_0, opPushData $ runPutS $ serialize h]-  (PayWitness v h)-    | v == 0 ->-        Left "encodeOutput: a version 0 witness output is PayWitnessPKHash or PayWitnessScriptHash"-    | B.length h < minWitnessProgramLength || B.length h > maxWitnessProgramLength ->-        Left "encodeOutput: witness program must be 2 to 40 bytes long"-    | Just c <- witnessVersionOp v ->-        Right [c, opPushData h]-    | otherwise ->-        Left "encodeOutput: witness version must be 16 or less"-  -- Provably unspendable output-  (DataCarrier ds) -> Right $ OP_RETURN : map opPushData ds+encodeOutput :: ScriptOutput -> Either String Script+encodeOutput s =+  Script <$> case s of+    -- Pay to PubKey+    (PayPK k) -> Right [opPushData $ encodeSerial k, OP_CHECKSIG]+    -- Pay to PubKey Hash Address+    (PayPKHash h) ->+      Right+        [ OP_DUP,+          OP_HASH160,+          opPushData $ runPutS $ serialize h,+          OP_EQUALVERIFY,+          OP_CHECKSIG+        ]+    -- Pay to MultiSig Keys+    (PayMulSig ps r)+      | r < 1 ->+          Left "encodeOutput: multisig must require at least one signature"+      | r > n ->+          Left "encodeOutput: multisig requires more signatures than it has keys"+      | n > maxMultisigKeys ->+          Left "encodeOutput: multisig has more than 20 keys"+      | otherwise ->+          let keys = map (opPushData . encodeSerial) ps+           in Right $ multisigCountOp r : keys ++ [multisigCountOp n, OP_CHECKMULTISIG]+      where+        n = length ps+    -- Pay to Script Hash Address+    (PayScriptHash h) ->+      Right [OP_HASH160, opPushData $ runPutS $ serialize h, OP_EQUAL]+    -- Pay to 256-bit Script Hash Address+    (PayScript32Hash h) ->+      Right [OP_HASH256, opPushData $ runPutS $ serialize h, OP_EQUAL]+    -- Pay to Witness PubKey Hash Address+    (PayWitnessPKHash h) ->+      Right [OP_0, opPushData $ runPutS $ serialize h]+    (PayWitnessScriptHash h) ->+      Right [OP_0, opPushData $ runPutS $ serialize h]+    (PayWitness v h)+      | v == 0 ->+          Left "encodeOutput: a version 0 witness output is PayWitnessPKHash or PayWitnessScriptHash"+      | B.length h < minWitnessProgramLength || B.length h > maxWitnessProgramLength ->+          Left "encodeOutput: witness program must be 2 to 40 bytes long"+      | Just c <- witnessVersionOp v ->+          Right [c, opPushData h]+      | otherwise ->+          Left "encodeOutput: witness version must be 16 or less"+    -- Provably unspendable output+    (DataCarrier ds) -> Right $ OP_RETURN : map opPushData ds  -- | The 'Script' of a 'ScriptOutput' is the binary form. Writing a value that--- 'encodeOutput' rejects fails with an 'error' call, since 'marshalPut'+-- 'encodeOutput' rejects fails with an 'error' call, since 'serialize' -- cannot report a failure.-instance Marshal Ctx ScriptOutput where-  marshalGet ctx = do+instance Serial ScriptOutput where+  {-# INLINEABLE serialize #-}+  {-# INLINEABLE deserialize #-}+  deserialize = do     script <- deserialize-    case decodeOutput ctx script of+    case decodeOutput script of       Left e -> fail e       Right o -> return o-  marshalPut ctx = either error serialize . encodeOutput ctx+  serialize = either error serialize . encodeOutput +instance Binary ScriptOutput where+  put = serialize+  get = deserialize++instance Serialize ScriptOutput where+  put = serialize+  get = deserialize+ -- | The pay-to-script-hash output of a redeem script. Fails for a script -- longer than 'maxRedeemScriptSize' bytes, which could never be spent. toP2SH :: Script -> Either String ScriptOutput@@ -399,8 +413,8 @@  -- | Match @[OP_M, PubKey1, ..., PubKeyN, OP_N, OP_CHECKMULTISIG]@ with M and N -- from 1 to 'maxMultisigKeys' and M at most N.-matchPayMulSig :: Ctx -> Script -> Either String ScriptOutput-matchPayMulSig ctx (Script ops) = case splitAt (length ops - 2) ops of+matchPayMulSig :: Script -> Either String ScriptOutput+matchPayMulSig (Script ops) = case splitAt (length ops - 2) ops of   (m : xs, [n, OP_CHECKMULTISIG]) -> do     intM <- maybeToEither "matchPayMulSig: invalid M parameter" $ opMultisigCount m     intN <- maybeToEither "matchPayMulSig: invalid N parameter" $ opMultisigCount n@@ -410,7 +424,7 @@     return $ PayMulSig keys intM   _ -> Left "matchPayMulSig: script did not match output template"   where-    key (OP_PUSHDATA bs _) = decodePubKey ctx bs+    key (OP_PUSHDATA bs _) = decodePubKey bs     key _ = Left "matchPayMulSig: invalid multisig opcode"  -- | The count that a multisig opcode stands for: @OP_1@ to @OP_16@, or a@@ -434,11 +448,11 @@ -- | Sort the public keys of a multisig output in ascending order by comparing -- their serialized representations. Refer to BIP-67, which defines the order -- for compressed keys. Any other output is returned unchanged.-sortMulSig :: Ctx -> ScriptOutput -> ScriptOutput-sortMulSig ctx out = case out of+sortMulSig :: ScriptOutput -> ScriptOutput+sortMulSig out = case out of   PayMulSig keys r ->     PayMulSig-      (sortBy (compare `on` marshal ctx) keys)+      (sortBy (compare `on` encodeSerial) keys)       r   _ -> out @@ -518,29 +532,29 @@  -- | The signature that a script element stands for: an empty push is -- 'TxSignatureEmpty', any other push must decode as a signature.-sigOp :: Network -> Ctx -> ScriptOp -> Maybe TxSignature-sigOp net ctx op = do+sigOp :: Network -> ScriptOp -> Maybe TxSignature+sigOp net op = do   bs <- pushOpData op   if B.null bs     then return TxSignatureEmpty-    else eitherToMaybe $ decodeTxSig net ctx bs+    else eitherToMaybe $ decodeTxSig net bs  -- | Heuristic to decode an input script into one of the standard types, when -- the output it spends is not known. A single empty push is read as a -- 'SpendPK' with an empty signature, although it is also the form of a -- 'SpendMulSig' without signatures.-decodeSimpleInput :: Network -> Ctx -> Script -> Either String SimpleInput-decodeSimpleInput net ctx (Script ops) =+decodeSimpleInput :: Network -> Script -> Either String SimpleInput+decodeSimpleInput net (Script ops) =   maybeToEither errMsg $ matchPK ops <|> matchPKHash ops <|> matchMulSig ops   where     matchPK [op] = SpendPK <$> f op     matchPK _ = Nothing     matchPKHash [op, OP_PUSHDATA pub _] =-      SpendPKHash <$> f op <*> eitherToMaybe (decodePubKey ctx pub)+      SpendPKHash <$> f op <*> eitherToMaybe (decodePubKey pub)     matchPKHash _ = Nothing     matchMulSig (OP_0 : xs) = SpendMulSig <$> mapM f xs     matchMulSig _ = Nothing-    f = sigOp net ctx+    f = sigOp net     errMsg = "decodeInput: Could not decode script input"  -- | Decode the input of a pay-to-script-hash output as the redeem script@@ -548,15 +562,15 @@ -- 'PayPKHash', and @OP_0@ followed by the signatures, possibly none, for -- 'PayMulSig'. Other redeem scripts have no standard input. decodeSimpleInputFor ::-  Network -> Ctx -> RedeemScript -> [ScriptOp] -> Maybe SimpleInput-decodeSimpleInputFor net ctx rdm ops = case (rdm, ops) of+  Network -> RedeemScript -> [ScriptOp] -> Maybe SimpleInput+decodeSimpleInputFor net rdm ops = case (rdm, ops) of   (PayPK _, [op]) -> SpendPK <$> f op   (PayPKHash _, [op, OP_PUSHDATA pub _]) ->-    SpendPKHash <$> f op <*> eitherToMaybe (decodePubKey ctx pub)+    SpendPKHash <$> f op <*> eitherToMaybe (decodePubKey pub)   (PayMulSig _ _, OP_0 : xs) -> SpendMulSig <$> mapM f xs   _ -> Nothing   where-    f = sigOp net ctx+    f = sigOp net  -- | Heuristic to decode a 'ScriptInput' from a 'Script'. This function fails if -- the script can not be parsed as a standard script input.@@ -588,27 +602,27 @@ --   the only element of the script. BIP 141 makes any other form invalid by --   consensus: "the scriptSig must be exactly a push of the BIP16 --   redeemScript".-decodeInput :: Network -> Ctx -> Script -> Either String ScriptInput-decodeInput net ctx s@(Script ops) =+decodeInput :: Network -> Script -> Either String ScriptInput+decodeInput net s@(Script ops) =   maybeToEither errMsg $ matchSimpleInput <|> matchPayScriptHash   where     matchSimpleInput =-      RegularInput <$> eitherToMaybe (decodeSimpleInput net ctx s)+      RegularInput <$> eitherToMaybe (decodeSimpleInput net s)     matchPayScriptHash =       case splitAt (length s.ops - 1) ops of         (is, [OP_PUSHDATA bs pushType]) -> do-          rdm <- eitherToMaybe $ unmarshal ctx bs+          rdm <- eitherToMaybe $ decodeSerial bs           guard (canonical rdm bs)           case (is, rdm) of             ([], PayWitnessPKHash _) -> nested pushType rdm             ([], PayWitnessScriptHash _) -> nested pushType rdm             _ -> do-              inp <- decodeSimpleInputFor net ctx rdm is+              inp <- decodeSimpleInputFor net rdm is               return $ ScriptHashInput inp rdm         _ -> Nothing     -- The redeem script, written back, gives the bytes that were pushed.     canonical rdm bs =-      fmap (runPutS . serialize) (encodeOutput ctx rdm) == Right bs+      fmap (runPutS . serialize) (encodeOutput rdm) == Right bs     -- A witness program is 22 or 34 bytes, so its only valid push is the     -- direct one.     nested pushType rdm = do@@ -616,30 +630,30 @@       return (NestedWitnessInput rdm)     errMsg = "decodeInput: Could not decode script input" -instance Marshal (Network, Ctx) ScriptInput where-  marshalGet (net, ctx) =-    deserialize >>= either fail return . decodeInput net ctx+instance Marshal Network ScriptInput where+  marshalGet net =+    deserialize >>= either fail return . decodeInput net -  marshalPut (net, ctx) =-    serialize . encodeInput net ctx+  marshalPut net =+    serialize . encodeInput net  -- | Encode a standard input into a script.-encodeInput :: Network -> Ctx -> ScriptInput -> Script-encodeInput net ctx s = case s of-  RegularInput ri -> encodeSimpleInput net ctx ri+encodeInput :: Network -> ScriptInput -> Script+encodeInput net s = case s of+  RegularInput ri -> encodeSimpleInput net ri   ScriptHashInput i o ->-    Script $ (encodeSimpleInput net ctx i).ops ++ [opPushData $ marshal ctx o]+    Script $ (encodeSimpleInput net i).ops ++ [opPushData $ encodeSerial o]   NestedWitnessInput o ->-    Script [opPushData $ marshal ctx o]+    Script [opPushData $ encodeSerial o]  -- | Encode a standard 'SimpleInput' into opcodes as an input 'Script'.-encodeSimpleInput :: Network -> Ctx -> SimpleInput -> Script-encodeSimpleInput net ctx s =+encodeSimpleInput :: Network -> SimpleInput -> Script+encodeSimpleInput net s =   Script $     case s of       SpendPK ts -> [f ts]-      SpendPKHash ts p -> [f ts, opPushData $ marshal ctx p]+      SpendPKHash ts p -> [f ts, opPushData $ encodeSerial p]       SpendMulSig xs -> OP_0 : map f xs   where     f TxSignatureEmpty = OP_0-    f ts = opPushData $ encodeTxSig net ctx ts+    f ts = opPushData $ encodeTxSig net ts
src/Haskoin/Transaction/Builder.hs view
@@ -524,11 +524,12 @@ -- transaction with either, and so does 'verifyStdTx' for the second. -- -- Nothing is added for change: what the outputs do not spend is the fee.-buildAddrTx :: Network -> Ctx -> [OutPoint] -> [(Text, Word64)] -> Either String Tx-buildAddrTx net ctx ops rcps = do+buildAddrTx :: Network -> [OutPoint] -> [(Text, Word64)] -> Either String Tx+buildAddrTx net ops rcps = do   when (any ((> net.maxSatoshi) . snd) rcps) $-    Left $ "buildAddrTx: An amount is above the maximum of " <> show net.maxSatoshi <> " satoshi"-  buildTx ctx ops <$> mapM f rcps+    Left $+      "buildAddrTx: An amount is above the maximum of " <> show net.maxSatoshi <> " satoshi"+  buildTx ops <$> mapM f rcps   where     f (aTxt, v) =       maybeToEither ("buildAddrTx: Invalid address " <> cs aTxt) $ do@@ -540,12 +541,12 @@ -- and a list of 'ScriptOutput' and amounts as outputs. It has no network -- to check against, so it builds what it is given, whatever the amounts. -- 'buildAddrTx' refuses an amount above the maximum of its network.-buildTx :: Ctx -> [OutPoint] -> [(ScriptOutput, Word64)] -> Tx-buildTx ctx ops rcpts =+buildTx :: [OutPoint] -> [(ScriptOutput, Word64)] -> Tx+buildTx ops rcpts =   Tx 1 (toIn <$> ops) (toOut <$> rcpts) [] 0   where     toIn op = TxIn op B.empty maxBound-    toOut (o, v) = TxOut v $ marshal ctx o+    toOut (o, v) = TxOut v $ encodeSerial o  -- | Sign a transaction by providing the 'SigInput' signing parameters and a -- list of private keys. The signature is computed deterministically as defined@@ -579,15 +580,14 @@ -- Example: P2WPKH -- -- > sigIn = SigInput (PayWitnessPKHash h) 100000 op sigHashAll Nothing--- > signedTx = signTx btc ctx unsignedTx [sigIn] [key]+-- > signedTx = signTx btc unsignedTx [sigIn] [key] -- -- Example: P2SH-P2WSH multisig -- -- > sigIn = SigInput (PayWitnessScriptHash h) 100000 op sigHashAll (Just $ PayMulSig [p1,p2,p3] 2)--- > signedTx = signNestedWitnessTx btc ctx unsignedTx [sigIn] [k1,k3]+-- > signedTx = signNestedWitnessTx btc unsignedTx [sigIn] [k1,k3] signTx ::   Network ->-  Ctx ->   -- | transaction to sign   Tx ->   -- | signing parameters@@ -596,7 +596,7 @@   [SecKey] ->   -- | signed transaction   Either String Tx-signTx net ctx tx si = Sign.signTx net ctx tx $ notNested <$> si+signTx net tx si = Sign.signTx net tx $ notNested <$> si   where     notNested s = (s, False) @@ -604,7 +604,6 @@ -- P2SH-nested.  Use the same signing parameters for segwit inputs as in 'signTx'. signNestedWitnessTx ::   Network ->-  Ctx ->   -- | transaction to sign   Tx ->   -- | signing parameters@@ -613,7 +612,7 @@   [SecKey] ->   -- | signed transaction   Either String Tx-signNestedWitnessTx net ctx tx si = Sign.signTx net ctx tx $ nested <$> si+signNestedWitnessTx net tx si = Sign.signTx net tx $ nested <$> si   where     -- NOTE: the nesting flag is ignored for non-segwit inputs     nested s = (s, True)@@ -622,15 +621,15 @@ -- Taproot input is signed with 'signTaprootInput' instead, since its -- digest needs the output every input spends. signInput ::-  Network -> Ctx -> Tx -> Int -> SigInput -> PrivateKey -> Either String Tx-signInput net ctx tx i si =-  Sign.signInput net ctx tx i (si, False)+  Network -> Tx -> Int -> SigInput -> PrivateKey -> Either String Tx+signInput net tx i si =+  Sign.signInput net tx i (si, False)  -- | Like 'signInput' but treat segwit inputs as nested signNestedInput ::-  Network -> Ctx -> Tx -> Int -> SigInput -> PrivateKey -> Either String Tx-signNestedInput net ctx tx i si =-  Sign.signInput net ctx tx i (si, True)+  Network -> Tx -> Int -> SigInput -> PrivateKey -> Either String Tx+signNestedInput net tx i si =+  Sign.signInput net tx i (si, True)  -- | Order the 'SigInput' with respect to the transaction inputs. This allows -- the user to provide the 'SigInput' in any order. Users can also provide only@@ -648,16 +647,15 @@ -- signers took their copies stays signed. mergeTxs ::   Network ->-  Ctx ->   [Tx] ->   [(ScriptOutput, Word64, OutPoint)] ->   Either String Tx-mergeTxs net ctx txs os = case txs of+mergeTxs net txs os = case txs of   [] -> Left "Transaction list is empty"   [tx] -> return tx   tx : _     | length (nub emptyTxs) /= 1 -> Left "Transactions do not match"-    | otherwise -> foldM (mergeTxInput net ctx txs) (clearAll tx) (outs tx)+    | otherwise -> foldM (mergeTxInput net txs) (clearAll tx) (outs tx)   where     zipOp tx = zip (matchTemplate os tx.inputs f) [0 ..]     outs tx =@@ -678,12 +676,11 @@ -- is kept. mergeTxInput ::   Network ->-  Ctx ->   [Tx] ->   Tx ->   ((ScriptOutput, Word64), Int) ->   Either String Tx-mergeTxInput net ctx txs tx ((so, val), i) = do+mergeTxInput net txs tx ((so, val), i) = do   when (i < 0 || any ((<= i) . length . (.inputs)) (tx : txs)) $     Left "mergeTxInput: input index out of range"   -- Ignore transactions with empty inputs@@ -693,7 +690,7 @@     [] -> return tx     (_, rdm) : _ -> do       unless (all ((== rdm) . snd) sigRes) $ Left "Redeem scripts do not match"-      si <- marshal (net, ctx) <$> go (nub $ concatMap fst sigRes) so rdm+      si <- marshal net <$> go (nub $ concatMap fst sigRes) so rdm       let ins' = updateIndex i tx.inputs (\TxIn {..} -> TxIn {script = si, ..})       return $ Tx tx.version ins' tx.outputs tx.witness tx.locktime   where@@ -714,15 +711,15 @@             _ -> Left "Invalid output script type"         _ -> Left "Invalid output script type"     extractSigs si =-      case unmarshal (net, ctx) si of+      case unmarshal net si of         Right (RegularInput (SpendMulSig sigs)) ->           Right (sigs, Nothing)         Right (ScriptHashInput (SpendMulSig sigs) rdm) ->           Right (sigs, Just rdm)         _ -> Left "Invalid script input type"     f out (TxSignature x sh) p =-      either (const False) (\h -> verifyHashSig ctx h x p.point) $-        encodeOutput ctx out >>= \s -> txSigHash net tx s val i sh+      either (const False) (\h -> verifyHashSig h x p.point) $+        encodeOutput out >>= \s -> txSigHash net tx s val i sh     f _ TxSignatureEmpty _ = False  {- Tx verification -}@@ -739,15 +736,15 @@ -- other script, valid or not. For those kinds it follows consensus: it -- does not answer 'True' for an input that no block can contain. verifyStdTx ::-  Network -> Ctx -> Tx -> [(ScriptOutput, Word64, OutPoint)] -> Bool-verifyStdTx net ctx tx coins =+  Network -> Tx -> [(ScriptOutput, Word64, OutPoint)] -> Bool+verifyStdTx net tx coins =   not (null tx.inputs)     && Map.size (Map.fromList [(i.outpoint, ()) | i <- tx.inputs]) == length tx.inputs-    && all (verifyInput net ctx tx spent) [0 .. length tx.inputs - 1]+    && all (verifyInput net tx spent) [0 .. length tx.inputs - 1]     && maybe False (\outs -> toSpend <= sum (map (toInteger . snd) outs)) (sequence spent.coins)   where     -- The coins are looked up once for the whole transaction-    spent = spentCoins ctx tx coins+    spent = spentCoins tx coins     toSpend = sum (map (toInteger . (.value)) tx.outputs)  -- | The coin of each input of a transaction, and the outputs that the@@ -760,11 +757,11 @@     outputs :: Maybe [TxOut]   } -spentCoins :: Ctx -> Tx -> [(ScriptOutput, Word64, OutPoint)] -> SpentCoins-spentCoins ctx tx given =+spentCoins :: Tx -> [(ScriptOutput, Word64, OutPoint)] -> SpentCoins+spentCoins tx given =   SpentCoins     { coins = found,-      outputs = map (\(so, val) -> TxOut val (marshal ctx so)) <$> sequence found+      outputs = map (\(so, val) -> TxOut val (encodeSerial so)) <$> sequence found     }   where     -- The first coin given for an outpoint is its coin@@ -810,12 +807,12 @@ -- -- An uncompressed key in a SegWit input is accepted, since a block may -- hold it, although nodes do not relay it.-verifyStdInput :: Network -> Ctx -> Tx -> [(ScriptOutput, Word64, OutPoint)] -> Int -> Bool-verifyStdInput net ctx tx coins = verifyInput net ctx tx (spentCoins ctx tx coins)+verifyStdInput :: Network -> Tx -> [(ScriptOutput, Word64, OutPoint)] -> Int -> Bool+verifyStdInput net tx coins = verifyInput net tx (spentCoins tx coins)  -- | 'verifyStdInput' on coins that are looked up already-verifyInput :: Network -> Ctx -> Tx -> SpentCoins -> Int -> Bool-verifyInput net ctx tx spent i+verifyInput :: Network -> Tx -> SpentCoins -> Int -> Bool+verifyInput net tx spent i   | i < 0 || i >= length tx.inputs = False   | otherwise = case spent.coins !! i of       Nothing -> False@@ -827,16 +824,16 @@         | otherwise ->             or $               rights-                [ (\si -> null ws && verifyLegacyInput so0 val si) <$> unmarshal (net, ctx) inp,+                [ (\si -> null ws && verifyLegacyInput so0 val si) <$> unmarshal net inp,                   nestedScriptOutput >>= \so -> verifyNestedInput so0 so val <$> wp so                 ]   where     inp = (tx.inputs !! i).script-    theTxSigHash so val = Sign.makeSigHash net ctx tx i so val+    theTxSigHash so val = Sign.makeSigHash net tx i so val      -- A signature verifies only when its digest could be computed.     checkSig :: Either String Hash256 -> Sig -> PubKey -> Bool-    checkSig h sig pub = either (const False) (\m -> verifyHashSig ctx m sig pub) h+    checkSig h sig pub = either (const False) (\m -> verifyHashSig m sig pub) h      ws :: WitnessStack     ws@@ -844,14 +841,14 @@       | otherwise = []      wp :: ScriptOutput -> Either String (Maybe ScriptOutput, SimpleInput)-    wp so = decodeWitnessInput net ctx =<< viewWitnessProgram net ctx so ws+    wp so = decodeWitnessInput net =<< viewWitnessProgram net so ws      -- The witness program of an input script that is its push and nothing     -- else, on a network that has SegWit     nestedScriptOutput :: Either String ScriptOutput-    nestedScriptOutput = case unmarshal (net, ctx) inp of+    nestedScriptOutput = case unmarshal net inp of       Right (NestedWitnessInput so)-        | net.segWit && inp == marshal (net, ctx) (NestedWitnessInput so) -> Right so+        | net.segWit && inp == marshal net (NestedWitnessInput so) -> Right so       _ -> Left "nestedScriptOutput: not a nested output"      -- OP_CHECKMULTISIG takes the signatures the script requires from the@@ -863,20 +860,20 @@     multisigVerifies :: (SigHash -> Either String Hash256) -> [PubKey] -> Int -> [TxSignature] -> Bool     multisigVerifies hashfun pubs r sigs =       -- With exactly r items, r of them verify only when none is empty-      length sigs == r && countMulSig' ctx hashfun pubs sigs == r+      length sigs == r && countMulSig' hashfun pubs sigs == r      verifyLegacyInput :: ScriptOutput -> Word64 -> ScriptInput -> Bool     verifyLegacyInput so val si = case (so, si) of       (PayPK pub, RegularInput (SpendPK (TxSignature sig sh))) ->         checkSig (theTxSigHash so val sh Nothing) sig pub.point       (PayPKHash h, RegularInput (SpendPKHash (TxSignature sig sh) pub)) ->-        pubKeyAddr ctx pub == p2pkhAddr h+        pubKeyAddr pub == p2pkhAddr h           && checkSig (theTxSigHash so val sh Nothing) sig pub.point       (PayMulSig pubs r, RegularInput (SpendMulSig sigs)) ->         either (const False) (\out -> multisigVerifies (txSigHash net tx out val i) ((.point) <$> pubs) r sigs) $-          encodeOutput ctx so+          encodeOutput so       (PayScriptHash h, ScriptHashInput si' rdm) ->-        payToScriptAddress ctx rdm == Right (p2shAddr h) && verifyLegacyInput rdm val (RegularInput si')+        payToScriptAddress rdm == Right (p2shAddr h) && verifyLegacyInput rdm val (RegularInput si')       _ -> False      verifySegwitInput ::@@ -888,7 +885,7 @@         ) ->           -- Compare the key hash only. An uncompressed key is non-standard           -- here but still valid by consensus, so verification accepts it.-          let keytest = pubKeyAddr ctx pub == p2pkhAddr h+          let keytest = pubKeyAddr pub == p2pkhAddr h               sighash = theTxSigHash so val sh Nothing               pkpoint = pub.point               verify = checkSig sighash sig pkpoint@@ -897,7 +894,7 @@         Just rdm'@(PayPK pub),         SpendPK (TxSignature sig sh)         ) ->-          let keytest = payToWitnessScriptAddress ctx rdm' == Right (p2wshAddr h)+          let keytest = payToWitnessScriptAddress rdm' == Right (p2wshAddr h)               sighash = theTxSigHash so val sh $ Just rdm'               pkpoint = pub.point               verify = checkSig sighash sig pkpoint@@ -906,8 +903,8 @@         Just rdm'@(PayPKHash kh),         SpendPKHash (TxSignature sig sh) pub         ) ->-          let keytest = payToWitnessScriptAddress ctx rdm' == Right (p2wshAddr h)-              addrtest = addressHash (marshal ctx pub) == kh+          let keytest = payToWitnessScriptAddress rdm' == Right (p2wshAddr h)+              addrtest = addressHash (encodeSerial pub) == kh               pkpoint = pub.point               sighash = theTxSigHash so val sh $ Just rdm'               verify = checkSig sighash sig pkpoint@@ -916,7 +913,7 @@         Just rdm'@(PayMulSig pubs r),         SpendMulSig sigs         ) ->-          let keytest = payToWitnessScriptAddress ctx rdm' == Right (p2wshAddr h)+          let keytest = payToWitnessScriptAddress rdm' == Right (p2wshAddr h)               pkpoints = (.point) <$> pubs               hashfun sh = theTxSigHash so val sh $ Just rdm'               verify = multisigVerifies hashfun pkpoints r sigs@@ -926,13 +923,13 @@     verifyNestedInput ::       ScriptOutput -> ScriptOutput -> Word64 -> (Maybe RedeemScript, SimpleInput) -> Bool     verifyNestedInput so so' val x = case so of-      PayScriptHash h -> payToScriptAddress ctx so' == Right (p2shAddr h) && verifySegwitInput so' val x+      PayScriptHash h -> payToScriptAddress so' == Right (p2shAddr h) && verifySegwitInput so' val x       _ -> False      verifyTaprootInput :: ScriptOutput -> Bool     verifyTaprootInput so = fromRight False $ do       outKey <- case so of-        PayWitness 1 program -> maybe (Left "not an output key") Right (importXOnlyPubKey ctx program)+        PayWitness 1 program -> maybe (Left "not an output key") Right (importXOnlyPubKey program)         _ -> Left "not a Taproot output"       -- The outputs every input spends, in order, which the Taproot digest       -- commits to@@ -941,16 +938,16 @@             TaprootSignature sig sh <- decodeTaprootSig sigBytes             h <- taprootSigHash tx spentOutputs i sh annex leaf             return (sig, h)-      case viewTaprootWitness ctx ws of+      case viewTaprootWitness ws of         Just (KeyPathSpend sigBytes annex) -> do           (sig, h) <- schnorr sigBytes annex Nothing-          return (verifySchnorr ctx outKey sig (hashToMsg h))+          return (verifySchnorr outKey sig (hashToMsg h))         Just (ScriptPathSpend spd) -> case (spd.script.ops, spd.stack) of           ([OP_PUSHDATA keyBytes OPCODE, OP_CHECKSIG], [sigBytes])             | spd.leafVersion == tapscriptLeafVersion -> do-                leafKey <- maybe (Left "not an x-only key") Right (importXOnlyPubKey ctx keyBytes)+                leafKey <- maybe (Left "not an x-only key") Right (importXOnlyPubKey keyBytes)                 (sig, h) <- schnorr sigBytes spd.annex (Just (leafHash spd.leafVersion spd.script, 0xffffffff))-                return (verifyScriptPathData ctx outKey spd && verifySchnorr ctx leafKey sig (hashToMsg h))+                return (verifyScriptPathData outKey spd && verifySchnorr leafKey sig (hashToMsg h))           -- The multisig of Taproot, @multi_a@ of the output descriptors:           -- a key and OP_CHECKSIG, then a key and OP_CHECKSIGADD for each           -- other key, the number of signatures asked for, and@@ -966,13 +963,13 @@                     signs keyBytes sigBytes                       | B.null sigBytes = Right False                       | otherwise = do-                          key <- maybe (Left "not an x-only key") Right (importXOnlyPubKey ctx keyBytes)+                          key <- maybe (Left "not an x-only key") Right (importXOnlyPubKey keyBytes)                           (sig, h) <- schnorr sigBytes spd.annex leaf-                          if verifySchnorr ctx key sig (hashToMsg h)+                          if verifySchnorr key sig (hashToMsg h)                             then Right True                             else Left "a signature that does not verify"                 signed <- sequence (zipWith signs keys (reverse items))-                return (verifyScriptPathData ctx outKey spd && length (filter id signed) == asked)+                return (verifyScriptPathData outKey spd && length (filter id signed) == asked)           _ -> Left "script path spends other than key checks are not verified"         Nothing -> Left "not a Taproot witness" @@ -1015,8 +1012,8 @@ -- ('txSigHashCashToken'). Inputs of those kinds are 'InputVerified' here -- and not by 'verifyStdInput'. A multisig is never 'InputForged': one -- that does not verify is 'InputUndecided'.-judgeInputs :: Network -> Ctx -> Tx -> [Maybe TxOut] -> [InputVerdict]-judgeInputs net ctx tx given = zipWith judge [0 ..] decoded+judgeInputs :: Network -> Tx -> [Maybe TxOut] -> [InputVerdict]+judgeInputs net tx given = zipWith judge [0 ..] decoded   where     prevs = take (length tx.inputs) (given <> repeat Nothing)     forked = net.sigHashForkId /= Nothing@@ -1026,7 +1023,7 @@     decoded = map (>>= decode) prevs     decode o = do       (prefix, script) <- split o.script-      so <- eitherToMaybe (unmarshal ctx script)+      so <- eitherToMaybe (decodeSerial script)       return (prefix, so, o.value)     spent =       SpentCoins@@ -1036,7 +1033,7 @@     judge :: Int -> Maybe (B.ByteString, ScriptOutput, Word64) -> InputVerdict     judge _ Nothing = InputUndecided     judge i (Just (prefix, so, val))-      | B.null prefix && verifyInput net ctx tx spent i = InputVerified+      | B.null prefix && verifyInput net tx spent i = InputVerified       | otherwise = case so of           PayPKHash h             | null ws, Just [sig, pub] <- pushes -> keyed (addressHash pub == h) sig pub legacy@@ -1048,7 +1045,7 @@             | net.segWit,               Just [program] <- pushes,               addressHash program == h,-              Right nested@(PayWitnessPKHash kh) <- unmarshal ctx program,+              Right nested@(PayWitnessPKHash kh) <- decodeSerial program,               [sig, pub] <- ws ->                 keyed (addressHash pub == kh) sig pub (segwit nested)           PayWitness 1 program@@ -1060,7 +1057,7 @@               null ws,               Just items@(_ : _ : _) <- pushes,               addressHash (last items) == h,-              Right redeem@(PayMulSig keys asked) <- unmarshal ctx (last items),+              Right redeem@(PayMulSig keys asked) <- decodeSerial (last items),               bits : sigs <- init items ->                 cashMultisig redeem keys asked bits sigs           _ -> InputUndecided@@ -1076,14 +1073,14 @@           OP_PUSHDATA d _ -> Just d           op -> B.singleton . fromIntegral <$> eitherToMaybe (scriptOpToInt op)         legacy sh = do-          script <- encodeOutput ctx so+          script <- encodeOutput so           if forked then txSigHashCashToken net tx prefix script val i sh else txSigHash net tx script val i sh-        segwit out sh = Sign.makeSigHash net ctx tx i out val sh Nothing+        segwit out sh = Sign.makeSigHash net tx i out val sh Nothing         -- a coin that names the hash of its key: another key does not         -- open it, whatever it signed         keyed named sig pub digest           | not named = InputForged-          | otherwise = maybe InputUndecided (\k -> signed sig k digest) (importPubKey ctx pub)+          | otherwise = maybe InputUndecided (\k -> signed sig k digest) (importPubKey pub)         -- Forged is said of the hash type "all" only. With another hash         -- type a signature that verifies is verified, and one that does         -- not is left alone.@@ -1093,8 +1090,8 @@               Left _ -> InputUndecided               Right m                 -- on Bitcoin Cash a signature of 64 bytes is a Schnorr one-                | forked && B.length body == 64 -> sure (verifyCashSchnorr ctx key body m)-                | otherwise -> maybe InputUndecided (\s -> sure (verifyHashSig ctx m s key)) (decodeStrictSig ctx body)+                | forked && B.length body == 64 -> sure (verifyCashSchnorr key body m)+                | otherwise -> maybe InputUndecided (\s -> sure (verifyHashSig m s key)) (decodeStrictSig body)           where             body = B.init sig             sure ok@@ -1130,16 +1127,16 @@                 && readable (B.last sig)                 && either                   (const False)-                  (verifyCashSchnorr ctx key.point (B.init sig))-                  (encodeOutput ctx script >>= \code -> cashDigest code (fromIntegral (B.last sig)))+                  (verifyCashSchnorr key.point (B.init sig))+                  (encodeOutput script >>= \code -> cashDigest code (fromIntegral (B.last sig)))             cashDigest code = txSigHashCashToken net tx prefix code val i         taproot program sig = fromRight InputUndecided $ do-          key <- maybe (Left "not a key") Right (importXOnlyPubKey ctx program)+          key <- maybe (Left "not a key") Right (importXOnlyPubKey program)           outs <- maybe (Left "a spent output is missing") Right spent.outputs           TaprootSignature s sh <- decodeTaprootSig sig           unless (sh == sigHashDefault || sh == sigHashAll) $ Left "another hash type"           m <- taprootSigHash tx outs i sh Nothing Nothing-          return (verdict (verifySchnorr ctx key s (hashToMsg m)))+          return (verdict (verifySchnorr key s (hashToMsg m)))         verdict ok = if ok then InputVerified else InputForged  -- | The keys of a Taproot multisig script and the number of signatures it@@ -1173,7 +1170,6 @@ -- item, can count enough signatures and still fail @OP_CHECKMULTISIG@. countMulSig ::   Network ->-  Ctx ->   Tx ->   Script ->   Word64 ->@@ -1181,17 +1177,17 @@   [PubKey] ->   [TxSignature] ->   Int-countMulSig net ctx tx out val i =-  countMulSig' ctx h+countMulSig net tx out val i =+  countMulSig' h   where     h = txSigHash net tx out val i -countMulSig' :: Ctx -> (SigHash -> Either String Hash256) -> [PubKey] -> [TxSignature] -> Int-countMulSig' _ _ [] _ = 0-countMulSig' _ _ _ [] = 0-countMulSig' ctx h (_ : pubs) (TxSignatureEmpty : sigs) =-  countMulSig' ctx h pubs sigs-countMulSig' ctx h (pub : pubs) sigs@(TxSignature sig sh : sigs')-  | either (const False) (\m -> verifyHashSig ctx m sig pub) (h sh) =-      1 + countMulSig' ctx h pubs sigs'-  | otherwise = countMulSig' ctx h pubs sigs+countMulSig' :: (SigHash -> Either String Hash256) -> [PubKey] -> [TxSignature] -> Int+countMulSig' _ [] _ = 0+countMulSig' _ _ [] = 0+countMulSig' h (_ : pubs) (TxSignatureEmpty : sigs) =+  countMulSig' h pubs sigs+countMulSig' h (pub : pubs) sigs@(TxSignature sig sh : sigs')+  | either (const False) (\m -> verifyHashSig m sig pub) (h sh) =+      1 + countMulSig' h pubs sigs'+  | otherwise = countMulSig' h pubs sigs
src/Haskoin/Transaction/Builder/Sign.hs view
@@ -87,36 +87,37 @@   }   deriving (Show, Read, Eq, Generic, NFData) -instance MarshalJSON Ctx SigInput where-  marshalValue ctx (SigInput s v o h r) =+instance ToJSON SigInput where+  toJSON (SigInput s v o h r) =     object $-      [ "pkscript" .= marshalValue ctx s,+      [ "pkscript" .= toJSON s,         "value" .= v,         "outpoint" .= o,         "sighash" .= h       ]-        ++ [ "redeem" .= marshalValue ctx r+        ++ [ "redeem" .= toJSON r            | r <- maybeToList r            ] -  marshalEncoding ctx (SigInput s v o h r) =+  toEncoding (SigInput s v o h r) =     pairs $       mconcat-        [ "pkscript" `pair` marshalEncoding ctx s,+        [ "pkscript" `pair` toEncoding s,           "value" `pair` word64 v,           "outpoint" `pair` toEncoding o,           "sighash" `pair` toEncoding h,-          maybe mempty (pair "redeem" . marshalEncoding ctx) r+          maybe mempty (pair "redeem" . toEncoding) r         ] -  unmarshalValue ctx =+instance FromJSON SigInput where+  parseJSON =     withObject "SigInput" $ \o ->       SigInput-        <$> (unmarshalValue ctx =<< o .: "pkscript")+        <$> (parseJSON =<< o .: "pkscript")         <*> o .: "value"         <*> o .: "outpoint"         <*> o .: "sighash"-        <*> (mapM (unmarshalValue ctx) =<< o .:? "redeem")+        <*> (mapM parseJSON =<< o .:? "redeem")  -- | Sign a transaction by providing the 'SigInput' signing parameters and a -- list of private keys. The signature is computed deterministically as defined@@ -135,7 +136,6 @@ -- is given. signTx ::   Network ->-  Ctx ->   -- | transaction to sign   Tx ->   -- | signing parameters, with nesting flag@@ -144,31 +144,31 @@   [SecKey] ->   -- | signed transaction   Either String Tx-signTx net ctx otx sigis allKeys+signTx net otx sigis allKeys   | null ti = Left "signTx: Transaction has no inputs"   | otherwise = foldM go otx $ findInputIndex ((.outpoint) . fst) sigis ti   where     ti = otx.inputs     -- The public keys of the secret keys are derived once for the whole     -- transaction, not once per input-    index = keyIndex ctx allKeys+    index = keyIndex allKeys     go tx (sigi@(SigInput so _ _ sh rdmM, _), i) = do       keys <- indexedSigKeys index so rdmM       if isTaprootOutput so         then do           unless net.segWit $ Left "signTx: this network has no Taproot"           spent <- spentOutputs-          foldM (\t k -> signTaprootInput ctx t spent i sh k.key) tx keys-        else foldM (\t k -> signInput net ctx t i sigi k) tx keys+          foldM (\t k -> signTaprootInput t spent i sh k.key) tx keys+        else foldM (\t k -> signInput net t i sigi k) tx keys     -- The outputs every input spends, which a Taproot signature commits     -- to: a nested SegWit program is spent as its P2SH wrapper     spentOutputs =       forM ti $ \txin ->         case find ((== txin.outpoint) . (.outpoint) . fst) sigis of-          Just (s, nested) -> (\so -> TxOut s.value (marshal ctx so)) <$> coinScript s nested+          Just (s, nested) -> (\so -> TxOut s.value (encodeSerial so)) <$> coinScript s nested           Nothing -> Left "signTx: a Taproot signature needs the output every input spends"     coinScript s nested-      | nested && isSegwit s.script = toP2SH =<< encodeOutput ctx s.script+      | nested && isSegwit s.script = toP2SH =<< encodeOutput s.script       | otherwise = Right s.script  -- | Whether the output is a Taproot output: a witness program of version 1@@ -190,7 +190,6 @@ -- key of that output: a signature of another key would make a transaction -- that no node accepts. signTaprootInput ::-  Ctx ->   Tx ->   -- | outputs spent, one per input   [TxOut] ->@@ -200,15 +199,15 @@   -- | the secret key of the output key   SecKey ->   Either String Tx-signTaprootInput ctx tx spent i sh secret = do+signTaprootInput tx spent i sh secret = do   -- The digest checks the index and the number of spent outputs   h <- taprootSigHash tx spent i sh Nothing Nothing   outputKey <- case B.unpack (spent !! i).script of     0x51 : 0x20 : program | length program == 32 -> Right (B.pack program)     _ -> Left "signTaprootInput: the output spent is not a Taproot output"-  unless (exportXOnlyPubKey ctx (derivePubKey ctx secret) == outputKey) $+  unless (exportXOnlyPubKey (derivePubKey secret) == outputKey) $     Left "signTaprootInput: the key is not the key of the output"-  signature <- taprootSignature (signSchnorr ctx secret (hashToMsg h)) sh+  signature <- taprootSignature (signSchnorr secret (hashToMsg h)) sh   let stacks         | null tx.witness = replicate (length tx.inputs) []         | otherwise = tx.witness@@ -227,25 +226,24 @@ -- purpose, which 'signTx' refuses. signInput ::   Network ->-  Ctx ->   Tx ->   Int ->   -- | boolean flag: nest input   (SigInput, Bool) ->   PrivateKey ->   Either String Tx-signInput net ctx tx i (sigIn@(SigInput so val _ _ rdmM), nest) key = do+signInput net tx i (sigIn@(SigInput so val _ _ rdmM), nest) key = do   when (isTaprootOutput so) $     Left "signInput: a Taproot input is signed with signTaprootInput"-  let pub = derivePublicKey ctx key-  unless (keyOfCoin ctx so rdmM pub) $+  let pub = derivePublicKey key+  unless (keyOfCoin so rdmM pub) $     Left "signInput: the key is not a key of the coin"-  sig <- makeSignature net ctx tx i sigIn key-  si <- buildInput net ctx tx i so val rdmM sig pub-  w <- updatedWitnessData net ctx tx i so si+  sig <- makeSignature net tx i sigIn key+  si <- buildInput net tx i so val rdmM sig pub+  w <- updatedWitnessData net tx i so si   return tx {inputs = nextTxIn so si, witness = w}   where-    f si TxIn {..} = TxIn {script = marshal (net, ctx) si, ..}+    f si TxIn {..} = TxIn {script = marshal net si, ..}     g so' = f (NestedWitnessInput so')     nextTxIn so' si       | isSegwit so' && nest = updateIndex i tx.inputs (g so')@@ -253,32 +251,31 @@       | otherwise = updateIndex i tx.inputs (f si)  -- | Whether the public key is one that the coin asks a signature of-keyOfCoin :: Ctx -> ScriptOutput -> Maybe RedeemScript -> PublicKey -> Bool-keyOfCoin ctx so rdmM pub = case (so, rdmM) of+keyOfCoin :: ScriptOutput -> Maybe RedeemScript -> PublicKey -> Bool+keyOfCoin so rdmM pub = case (so, rdmM) of   (PayPK p, Nothing) -> p == pub   (PayPKHash h, Nothing) -> keyHash == h   (PayMulSig ps _, Nothing) -> pub `elem` ps-  (PayScriptHash _, Just rdm) -> keyOfCoin ctx rdm Nothing pub+  (PayScriptHash _, Just rdm) -> keyOfCoin rdm Nothing pub   (PayWitnessPKHash h, _) -> keyHash == h-  (PayWitnessScriptHash _, Just rdm) -> keyOfCoin ctx rdm Nothing pub+  (PayWitnessScriptHash _, Just rdm) -> keyOfCoin rdm Nothing pub   _ -> False   where-    keyHash = addressHash (marshal ctx pub)+    keyHash = addressHash (encodeSerial pub)  -- | Add the witness data of the transaction given segwit parameters for an input. -- -- @since 0.11.0.0 updatedWitnessData ::   Network ->-  Ctx ->   Tx ->   Int ->   ScriptOutput ->   ScriptInput ->   Either String WitnessData-updatedWitnessData net ctx tx i so si+updatedWitnessData net tx i so si   | isSegwit so =-      updateWitness . toWitnessStack net ctx =<< calcWitnessProgram net ctx so si+      updateWitness . toWitnessStack net =<< calcWitnessProgram net so si   | otherwise =       return tx.witness   where@@ -286,7 +283,7 @@       | null tx.witness = return $ updateIndex i defaultStack (const w)       | length tx.witness /= n = Left "Invalid number of witness stacks"       | otherwise = return $ updateIndex i tx.witness (const w)-    defaultStack = replicate n $ toWitnessStack net ctx EmptyWitnessProgram+    defaultStack = replicate n $ toWitnessStack net EmptyWitnessProgram     n = length tx.inputs  -- | Associate an input index to each value in a list@@ -316,12 +313,11 @@ -- result is an error, because nodes do not relay such a spend -- (@SCRIPT_VERIFY_WITNESS_PUBKEYTYPE@ in Bitcoin Core). sigKeys ::-  Ctx ->   ScriptOutput ->   Maybe RedeemScript ->   [SecKey] ->   Either String [PrivateKey]-sigKeys ctx so rdmM keys = indexedSigKeys (keyIndex ctx keys) so rdmM+sigKeys so rdmM keys = indexedSigKeys (keyIndex keys) so rdmM  -- | The secret keys of a signer with what is derived from them, so that it -- is derived once for a whole transaction@@ -335,23 +331,23 @@     outputKeys :: [[(B.ByteString, SecKey)]]   } -keyIndex :: Ctx -> [SecKey] -> KeyIndex-keyIndex ctx keys =+keyIndex :: [SecKey] -> KeyIndex+keyIndex keys =   KeyIndex     { forms =-        [ (PrivateKey k compressed, pub, addressHash (marshal ctx pub))+        [ (PrivateKey k compressed, pub, addressHash (encodeSerial pub))         | k <- keys,-          let point = derivePubKey ctx k,+          let point = derivePubKey k,           compressed <- [True, False],           let pub = PublicKey point compressed         ],       outputKeys =-        [ (xOnly k, k) : [(xOnly tweaked, tweaked) | Just tweaked <- [taprootOutputSecKey ctx k Nothing]]+        [ (xOnly k, k) : [(xOnly tweaked, tweaked) | Just tweaked <- [taprootOutputSecKey k Nothing]]         | k <- keys         ]     }   where-    xOnly = exportXOnlyPubKey ctx . derivePubKey ctx+    xOnly = exportXOnlyPubKey . derivePubKey  -- | 'sigKeys' on keys that are indexed already indexedSigKeys :: KeyIndex -> ScriptOutput -> Maybe RedeemScript -> Either String [PrivateKey]@@ -381,7 +377,6 @@ -- about the previous output. buildInput ::   Network ->-  Ctx ->   -- | transaction where input will be added   Tx ->   -- | input index where signature will go@@ -395,7 +390,7 @@   TxSignature ->   PublicKey ->   Either String ScriptInput-buildInput net ctx tx i so val rdmM sig pub = do+buildInput net tx i so val rdmM sig pub = do   when (i < 0 || i >= length tx.inputs) $ Left "buildInput: Invalid input index"   when (isTaprootOutput so) $ Left "buildInput: a Taproot input has no input script"   case (so, rdmM) of@@ -414,25 +409,25 @@       PayPKHash _ -> return $ RegularInput $ SpendPKHash sig pub       PayMulSig msPubs r -> do         let mSigs = take r $ catMaybes $ matchTemplate allSigs msPubs f-            allSigs = nub $ sig : parseExistingSigs net ctx tx so i+            allSigs = nub $ sig : parseExistingSigs net tx so i         return $ RegularInput $ SpendMulSig mSigs       _ -> Left "buildInput: Invalid output/redeem script combination"     buildScriptHashInput rdm = do       inp <- buildRegularInput rdm       return $ ScriptHashInput inp.get rdm     f (TxSignature x sh) p =-      either (const False) (\m -> verifyHashSig ctx m x p.point) $-        makeSigHash net ctx tx i so val sh rdmM+      either (const False) (\m -> verifyHashSig m x p.point) $+        makeSigHash net tx i so val sh rdmM     f TxSignatureEmpty _ = False  -- | Apply heuristics to extract the signatures for a particular input that are -- embedded in the transaction. -- -- @since 0.11.0.0-parseExistingSigs :: Network -> Ctx -> Tx -> ScriptOutput -> Int -> [TxSignature]-parseExistingSigs net ctx tx so i = insSigs <> witSigs+parseExistingSigs :: Network -> Tx -> ScriptOutput -> Int -> [TxSignature]+parseExistingSigs net tx so i = insSigs <> witSigs   where-    insSigs = case unmarshal (net, ctx) scp of+    insSigs = case unmarshal net scp of       Right (ScriptHashInput (SpendMulSig xs) _) -> xs       Right (RegularInput (SpendMulSig xs)) -> xs       _ -> []@@ -440,7 +435,7 @@     witSigs       | not $ isSegwit so = []       | length tx.witness <= i = []-      | otherwise = rights $ decodeTxSig net ctx <$> (tx.witness !! i)+      | otherwise = rights $ decodeTxSig net <$> (tx.witness !! i)  -- | Produce a structured representation of a deterministic (RFC-6979) -- signature over an input. On a network with a fork id, such as Bitcoin@@ -472,21 +467,24 @@ -- coin in that case, so those are signed. -- -- The key is not checked against the coin here: 'signInput' does that.-makeSignature :: Network -> Ctx -> Tx -> Int -> SigInput -> PrivateKey -> Either String TxSignature-makeSignature net ctx tx i (SigInput so val _ sh rdmM) key = do+makeSignature :: Network -> Tx -> Int -> SigInput -> PrivateKey -> Either String TxSignature+makeSignature net tx i (SigInput so val _ sh rdmM) key = do   when (isSegwit so && not net.segWit) $     Left "makeSignature: this network has no SegWit"   when (sh > 0xff) $-    Left $ "makeSignature: the hash type " <> shown <> " does not fit in the one byte of a signature"+    Left $+      "makeSignature: the hash type " <> shown <> " does not fit in the one byte of a signature"   when (isNothing net.sigHashForkId && hasForkIdFlag sh) $-    Left $ "makeSignature: the hash type " <> shown <> " has the fork id flag, which this network does not use"+    Left $+      "makeSignature: the hash type " <> shown <> " has the fork id flag, which this network does not use"   when (isSigHashUnknown sh') $-    Left $ "makeSignature: the hash type " <> shown <> " is not one a node accepts"+    Left $+      "makeSignature: the hash type " <> shown <> " is not one a node accepts"   committedScript-  m <- makeSigHash net ctx tx i so val sh' rdmM+  m <- makeSigHash net tx i so val sh' rdmM   when (signsConstantDigest && i >= length tx.outputs) $     Left "makeSignature: SIGHASH_SINGLE without an output at the input index"-  return $ TxSignature (signHash ctx key.key m) sh'+  return $ TxSignature (signHash key.key m) sh'   where     shown = show (toInteger sh)     sh'@@ -497,12 +495,12 @@     -- A coin that commits to a script is signed only with that script     committedScript = case (so, rdmM) of       (PayScriptHash h, Just rdm) -> do-        committed <- p2shScriptHash =<< encodeOutput ctx rdm+        committed <- p2shScriptHash =<< encodeOutput rdm         unless (committed == h) $ Left "makeSignature: the redeem script does not hash to the coin"       (PayScriptHash _, Nothing) ->         Left "makeSignature: a pay-to-script-hash coin needs its redeem script"       (PayWitnessScriptHash h, Just rdm) -> do-        committed <- p2wshScriptHash =<< encodeOutput ctx rdm+        committed <- p2wshScriptHash =<< encodeOutput rdm         unless (committed == h) $ Left "makeSignature: the witness script does not hash to the coin"       (PayWitnessScriptHash _, Nothing) ->         Left "makeSignature: a pay-to-witness-script-hash coin needs its witness script"@@ -513,7 +511,6 @@ -- @since 0.11.0.0 makeSigHash ::   Network ->-  Ctx ->   Tx ->   Int ->   ScriptOutput ->@@ -521,10 +518,10 @@   SigHash ->   Maybe RedeemScript ->   Either String Hash256-makeSigHash net ctx tx i so val sh rdmM = do+makeSigHash net tx i so val sh rdmM = do   when (isTaprootOutput so) $     Left "makeSigHash: the digest of a Taproot input is taprootSigHash"-  script <- encodeOutput ctx so'+  script <- encodeOutput so'   h net tx script val i sh   where     so' = case so of
src/Haskoin/Transaction/Common.hs view
@@ -65,6 +65,7 @@ import GHC.Generics (Generic) import Haskoin.Crypto.Hash import Haskoin.Network.Common+import Haskoin.Util.Direct (decodeDirect, encodeDirect, getDirect, putDirect, sizeDirect) import Haskoin.Util.Helpers import Text.Read as R @@ -78,7 +79,9 @@  instance Serial TxHash where   serialize (TxHash h) = serialize h+  {-# INLINE serialize #-}   deserialize = TxHash <$> deserialize+  {-# INLINE deserialize #-}  instance Serialize TxHash where   put = serialize@@ -115,7 +118,7 @@ -- signatures go in the input scripts or in the witness. nosigTxHash :: Tx -> TxHash nosigTxHash Tx {..} =-  TxHash . doubleSHA256 . runPutS $ serialize tx+  TxHash (doubleSHA256 (encodeDirect (serialize tx)))   where     tx = Tx {inputs = map clr inputs, witness = [], ..}     clr TxIn {..} = TxIn {script = B.empty, ..}@@ -163,19 +166,19 @@ -- | Compute transaction hash: the transaction id, which leaves the witness -- out. txHash :: Tx -> TxHash-txHash tx = TxHash . doubleSHA256 . runPutS $ serialize tx {witness = []}+txHash tx = TxHash (doubleSHA256 (encodeDirect (putLegacyTx tx)))  -- | The witness transaction id of BIP 141: the hash of the transaction with -- its witness. It is the same as 'txHash' when the transaction has no -- witness, as @GetWitnessHash@ gives it in Bitcoin Core. txWitnessHash :: Tx -> TxHash-txWitnessHash = TxHash . doubleSHA256 . runPutS . serialize+txWitnessHash tx = TxHash (doubleSHA256 (encodeDirect (serialize tx)))  -- | The weight of the transaction in weight units, as BIP 141 defines it:--- three times the size without the witness, plus the size with it.+-- three times the size without the witness, plus the size with it. The+-- sizes are counted, and the transaction is not written to get them. txWeight :: Tx -> Int-txWeight tx =-  3 * B.length (runPutS (serialize tx {witness = []})) + B.length (runPutS (serialize tx))+txWeight tx = 3 * sizeDirect (putLegacyTx tx) + sizeDirect (serialize tx)  -- | The virtual size of the transaction in virtual bytes, as BIP 141 -- defines it: the weight divided by four, rounded up. Fees are charged by@@ -202,7 +205,7 @@ -- and so it does not notice bytes that follow. Use this function for a -- transaction that arrives on its own. decodeTx :: ByteString -> Either String Tx-decodeTx = runGetS $ do+decodeTx = decodeDirect $ do   tx <- deserialize   done <- isEmpty   unless done $ fail "Trailing bytes after transaction"@@ -224,22 +227,30 @@       Just 0x00 -> parseLegacyTx       Just 0x01 -> parseWitnessTx       Just other -> fail $ "Unknown transaction optional data: flags " ++ show other+  {-# INLINEABLE deserialize #-}   serialize tx     | hasWitness tx = putWitnessTx tx     | otherwise = putLegacyTx tx+  {-# INLINEABLE serialize #-}  instance Binary Tx where   put = serialize   get = deserialize +-- | Through cereal a transaction is written and read on a buffer directly,+-- with the functions of "Haskoin.Util.Direct": a node hashes, stores and+-- loads transactions all day, and the builder and the continuations of+-- cereal took several times as long as the bytes themselves. The bytes and+-- the errors are those of the 'Serial' instance. instance Serialize Tx where-  put = serialize-  get = deserialize+  put tx = putDirect (serialize tx)+  get = getDirect deserialize  putInOut :: (MonadPut m) => Tx -> m () putInOut tx = do   putVarIntList serialize tx.inputs   putVarIntList serialize tx.outputs+{-# INLINEABLE putInOut #-}  -- | Non-SegWit transaction serializer. putLegacyTx :: (MonadPut m) => Tx -> m ()@@ -247,6 +258,7 @@   putWord32le tx.version   putInOut tx   putWord32le tx.locktime+{-# INLINEABLE putLegacyTx #-}  -- | Witness transaction serializer. One stack is written per input: an -- input without a stack gets an empty one, and stacks beyond the inputs@@ -261,6 +273,7 @@   putWord32le tx.locktime   where     n = length tx.inputs+{-# INLINEABLE putWitnessTx #-}  -- | The flags byte of the extended format of BIP 144, when the transaction -- has one: the byte after an input count of zero, as @UnserializeTransaction@@@ -275,6 +288,7 @@   if marker == 0x00     then Just <$> getWord8     else return Nothing+{-# INLINEABLE witnessFlags #-}  -- | Non-SegWit transaction deserializer: the old format, without the -- marker, flags and witness of BIP 144. Use it where the bytes are known@@ -290,6 +304,7 @@   outputs <- getVarIntList deserialize   locktime <- getWord32le   return Tx {witness = [], ..}+{-# INLINEABLE parseLegacyTx #-}  -- | Witness transaction deserializer. A transaction with the witness marker -- must have a witness: one whose stacks are all empty fails, as it does in@@ -307,14 +322,17 @@     fail "Superfluous witness record"   locktime <- getWord32le   return Tx {..}+{-# INLINEABLE parseWitnessTx #-}  -- | Witness data deserializer. Requires count of inputs. parseWitnessData :: (MonadGet m) => Int -> m WitnessData parseWitnessData n = replicateM n (getVarIntList getVarIntBytes)+{-# INLINEABLE parseWitnessData #-}  -- | Witness data serializer. putWitnessData :: (MonadPut m) => WitnessData -> m () putWitnessData = mapM_ (putVarIntList putVarIntBytes)+{-# INLINEABLE putWitnessData #-}  -- | The witness of the JSON form has one stack per input, or none at all: -- a stack without an input would not be part of the transaction.@@ -366,19 +384,21 @@ instance Serial TxIn where   deserialize =     TxIn <$> deserialize <*> getVarIntBytes <*> getWord32le+  {-# INLINEABLE deserialize #-}    serialize (TxIn o s q) = do     serialize o     putVarIntBytes s     putWord32le q+  {-# INLINEABLE serialize #-}  instance Binary TxIn where   get = deserialize   put = serialize  instance Serialize TxIn where-  get = deserialize-  put = serialize+  get = getDirect deserialize+  put x = putDirect (serialize x)  instance FromJSON TxIn where   parseJSON =@@ -414,18 +434,23 @@  instance Serial TxOut where   deserialize = TxOut <$> getWord64le <*> getVarIntBytes+  {-# INLINEABLE deserialize #-}    serialize (TxOut o s) = do     putWord64le o     putVarIntBytes s+  {-# INLINEABLE serialize #-}  instance Binary TxOut where   put = serialize   get = deserialize +-- | Read on a buffer directly, like a transaction. Written through the+-- builder of cereal: for a value of two or three fields that costs less than+-- a buffer of its own, which 'putDirect' would allocate and then copy. instance Serialize TxOut where   put = serialize-  get = deserialize+  get = getDirect deserialize  instance FromJSON TxOut where   parseJSON =@@ -458,15 +483,19 @@   deserialize = do     (h, i) <- liftM2 (,) deserialize getWord32le     return $ OutPoint h i+  {-# INLINEABLE deserialize #-}   serialize (OutPoint h i) = serialize h >> putWord32le i+  {-# INLINEABLE serialize #-}  instance Binary OutPoint where   put = serialize   get = deserialize +-- | Read on a buffer directly, and written through the builder of cereal,+-- like a 'TxOut'. instance Serialize OutPoint where   put = serialize-  get = deserialize+  get = getDirect deserialize  instance FromJSON OutPoint where   parseJSON =
src/Haskoin/Transaction/Psbt.hs view
@@ -4,9 +4,9 @@ {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE ImportQualifiedPost #-} {-# LANGUAGE LambdaCase #-}-{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE NoFieldSelectors #-} @@ -187,13 +187,13 @@ import Control.DeepSeq (NFData) import Control.Monad (ap, forM, forM_, guard, replicateM, unless, when, zipWithM) import Crypto.Hash (Digest, SHA256, digestFromByteString)-import Crypto.Secp256k1 (Ctx, PubKey, SecKey, derivePubKey, exportXOnlyPubKey, importXOnlyPubKey, signSchnorr, verifySchnorr)+import Crypto.Secp256k1 (PubKey, SecKey, derivePubKey, exportXOnlyPubKey, importPubKey, importXOnlyPubKey, signSchnorr, verifySchnorr)+import Data.Base64.Types (extractBase64) import Data.Bifunctor (first) import Data.Bits (complement, shiftL, testBit, (.&.), (.|.)) import Data.ByteArray qualified as BA import Data.ByteString (ByteString) import Data.ByteString qualified as B-import Data.Base64.Types (extractBase64) import Data.ByteString.Base64 (decodeBase64Untyped, encodeBase64') import Data.Char (toUpper) import Data.List (find, nubBy, stripPrefix)@@ -967,10 +967,8 @@ -- | Whether the bytes are a public key, compressed or not: they have the -- length and the first byte of one, and are a point of the curve, as -- Bitcoin Core requires of the keys of a PSBT (@IsFullyValid@ in psbt.h).--- The point is checked through the 'Read' instance of the binding, which--- parses the hexadecimal form of a key without a context. isPublicKeyBytes :: ByteString -> Bool-isPublicKeyBytes bytes = shaped && isJust (readMaybe (show (encodeHex bytes)) :: Maybe PubKey)+isPublicKeyBytes bytes = shaped && isJust (importPubKey bytes)   where     shaped = case B.unpack (B.take 1 bytes) of       [0x02] -> B.length bytes == 33@@ -1216,46 +1214,46 @@  -- | The records of the type whose keys are public keys, in the order of -- the map, with their values decoded-publicKeyRecords :: Word8 -> Ctx -> (ByteString -> Either String a) -> PsbtMap -> Either String [(PublicKey, a)]-publicKeyRecords t ctx decodeValue m =+publicKeyRecords :: Word8 -> (ByteString -> Either String a) -> PsbtMap -> Either String [(PublicKey, a)]+publicKeyRecords t decodeValue m =   forM [(key, value) | (key, value) <- Map.toAscList m, key.keyType == t] $ \(key, value) -> do-    public <- first (const ("The key " <> showKey key <> " is not a public key")) (unmarshal ctx key.keyData)+    public <- first (const ("The key " <> showKey key <> " is not a public key")) (decodeSerial key.keyData)     decoded <- first (("The value of the key " <> showKey key <> " ") <>) (decodeValue value)     return (public, decoded) -derivationsOf :: Word8 -> Ctx -> PsbtMap -> Either String [(PublicKey, Derivation)]-derivationsOf t ctx = publicKeyRecords t ctx decodeDerivation+derivationsOf :: Word8 -> PsbtMap -> Either String [(PublicKey, Derivation)]+derivationsOf t = publicKeyRecords t decodeDerivation -insertDerivation :: Word8 -> Ctx -> PublicKey -> Derivation -> PsbtMap -> PsbtMap-insertDerivation t ctx public derivation = Map.insert (Key t (marshal ctx public)) (encodeDerivation derivation)+insertDerivation :: Word8 -> PublicKey -> Derivation -> PsbtMap -> PsbtMap+insertDerivation t public derivation = Map.insert (Key t (encodeSerial public)) (encodeDerivation derivation)  -- | The derivations of the keys of an input: PSBT_IN_BIP32_DERIVATION-inputDerivations :: Ctx -> PsbtMap -> Either String [(PublicKey, Derivation)]+inputDerivations :: PsbtMap -> Either String [(PublicKey, Derivation)] inputDerivations = derivationsOf inDerivationType -insertInputDerivation :: Ctx -> PublicKey -> Derivation -> PsbtMap -> PsbtMap+insertInputDerivation :: PublicKey -> Derivation -> PsbtMap -> PsbtMap insertInputDerivation = insertDerivation inDerivationType  -- | The derivations of the keys of an output: PSBT_OUT_BIP32_DERIVATION. -- A record is a claim of whoever wrote the PSBT. To treat an output as -- change, derive the key and compare it with the script of the output.-outputDerivations :: Ctx -> PsbtMap -> Either String [(PublicKey, Derivation)]+outputDerivations :: PsbtMap -> Either String [(PublicKey, Derivation)] outputDerivations = derivationsOf outDerivationType -insertOutputDerivation :: Ctx -> PublicKey -> Derivation -> PsbtMap -> PsbtMap+insertOutputDerivation :: PublicKey -> Derivation -> PsbtMap -> PsbtMap insertOutputDerivation = insertDerivation outDerivationType  -- | The extended public keys of the global map, with their derivations: -- PSBT_GLOBAL_XPUB. Those of another network, by their version bytes, are -- left aside.-xpubRecords :: Network -> Ctx -> PsbtMap -> Either String [(XPubKey, Derivation)]-xpubRecords net ctx m =+xpubRecords :: Network -> PsbtMap -> Either String [(XPubKey, Derivation)]+xpubRecords net m =   fmap catMaybes . forM [(key, value) | (key, value) <- Map.toAscList m, key.keyType == xpubType] $ \(key, value) -> do     derivation <- first (("The value of the key " <> showKey key <> " ") <>) (decodeDerivation value)-    return $ (\xpub -> (xpub, derivation)) <$> eitherToMaybe (unmarshal (net, ctx) key.keyData)+    return $ (\xpub -> (xpub, derivation)) <$> eitherToMaybe (unmarshal net key.keyData) -insertXpubRecord :: Network -> Ctx -> XPubKey -> Derivation -> PsbtMap -> PsbtMap-insertXpubRecord net ctx xpub derivation = Map.insert (Key xpubType (marshal (net, ctx) xpub)) (encodeDerivation derivation)+insertXpubRecord :: Network -> XPubKey -> Derivation -> PsbtMap -> PsbtMap+insertXpubRecord net xpub derivation = Map.insert (Key xpubType (marshal net xpub)) (encodeDerivation derivation)  {- The fields of an input and of an output -} @@ -1286,15 +1284,15 @@ -- | The signatures of the input that are not final, by the public key each -- is of, in the order of the map: PSBT_IN_PARTIAL_SIG. A signature is as -- it goes in a script, with its sighash byte last.-partialSignatures :: Ctx -> PsbtMap -> Either String [(PublicKey, ByteString)]-partialSignatures ctx = publicKeyRecords partialSigType ctx Right+partialSignatures :: PsbtMap -> Either String [(PublicKey, ByteString)]+partialSignatures = publicKeyRecords partialSigType Right  -- | Whether the input carries a signature that is not final hasPartialSignatures :: PsbtMap -> Bool hasPartialSignatures = any ((== partialSigType) . (.keyType)) . Map.keys -insertPartialSignature :: Ctx -> PublicKey -> ByteString -> PsbtMap -> PsbtMap-insertPartialSignature ctx public = Map.insert (Key partialSigType (marshal ctx public))+insertPartialSignature :: PublicKey -> ByteString -> PsbtMap -> PsbtMap+insertPartialSignature public = Map.insert (Key partialSigType (encodeSerial public))  -- | The map without its signatures that are not final, as a finalizer -- leaves it@@ -1375,18 +1373,18 @@  -- | The script path signatures of a Taproot input, each by the x-only key -- and the leaf hash it is for: PSBT_IN_TAP_SCRIPT_SIG-tapScriptSigs :: Ctx -> PsbtMap -> Either String [((PubKey, Digest SHA256), TaprootSignature)]-tapScriptSigs ctx m =+tapScriptSigs :: PsbtMap -> Either String [((PubKey, Digest SHA256), TaprootSignature)]+tapScriptSigs m =   forM [(key, value) | (key, value) <- Map.toAscList m, key.keyType == tapScriptSigType] $ \(key, value) -> do     let (keyBytes, leafBytes) = B.splitAt 32 key.keyData-    leafKey <- maybe (Left ("The key " <> showKey key <> " is not an x-only public key and a leaf hash")) Right $ importXOnlyPubKey ctx keyBytes+    leafKey <- maybe (Left ("The key " <> showKey key <> " is not an x-only public key and a leaf hash")) Right $ importXOnlyPubKey keyBytes     leaf <- maybe (Left ("The key " <> showKey key <> " is not an x-only public key and a leaf hash")) Right $ digestOf leafBytes     signature <- first (("The value of the key " <> showKey key <> " ") <>) (decodeTaprootSig value)     return ((leafKey, leaf), signature) -insertTapScriptSig :: Ctx -> PubKey -> Digest SHA256 -> TaprootSignature -> PsbtMap -> PsbtMap-insertTapScriptSig ctx leafKey leaf signature =-  Map.insert (Key tapScriptSigType (exportXOnlyPubKey ctx leafKey <> BA.convert leaf)) (encodeTaprootSig signature)+insertTapScriptSig :: PubKey -> Digest SHA256 -> TaprootSignature -> PsbtMap -> PsbtMap+insertTapScriptSig leafKey leaf signature =+  Map.insert (Key tapScriptSigType (exportXOnlyPubKey leafKey <> BA.convert leaf)) (encodeTaprootSig signature)  -- | A leaf script a Taproot input may be spent with, and the control -- block that commits it to the output key: PSBT_IN_TAP_LEAF_SCRIPT@@ -1400,10 +1398,10 @@  -- | The leaf scripts of a Taproot input, with their control blocks: -- PSBT_IN_TAP_LEAF_SCRIPT-tapLeafScripts :: Ctx -> PsbtMap -> Either String [TapLeafScript]-tapLeafScripts ctx m =+tapLeafScripts :: PsbtMap -> Either String [TapLeafScript]+tapLeafScripts m =   forM [(key, value) | (key, value) <- Map.toAscList m, key.keyType == tapLeafScriptType] $ \(key, value) -> do-    _ <- first (const ("The key " <> showKey key <> " is not a control block")) (decodeControlBlock ctx key.keyData)+    _ <- first (const ("The key " <> showKey key <> " is not a control block")) (decodeControlBlock key.keyData)     when (B.null value) $ Left ("The value of the key " <> showKey key <> " has no leaf version")     script <- first (("The value of the key " <> showKey key <> " ") <>) (decodeScript (B.init value))     return (TapLeafScript key.keyData script (B.last value))@@ -1438,47 +1436,47 @@       derivation <- either refuse return (decodeDerivation rest)       return (TapDerivation leaves derivation) -tapDerivationsOf :: Word8 -> Ctx -> PsbtMap -> Either String [(PubKey, TapDerivation)]-tapDerivationsOf t ctx m =+tapDerivationsOf :: Word8 -> PsbtMap -> Either String [(PubKey, TapDerivation)]+tapDerivationsOf t m =   forM [(key, value) | (key, value) <- Map.toAscList m, key.keyType == t] $ \(key, value) -> do-    public <- maybe (Left ("The key " <> showKey key <> " is not an x-only public key")) Right (importXOnlyPubKey ctx key.keyData)+    public <- maybe (Left ("The key " <> showKey key <> " is not an x-only public key")) Right (importXOnlyPubKey key.keyData)     decoded <- first (("The value of the key " <> showKey key <> " ") <>) (decodeTapDerivation value)     return (public, decoded) -insertTapDerivation :: Word8 -> Ctx -> PubKey -> TapDerivation -> PsbtMap -> PsbtMap-insertTapDerivation t ctx public d = Map.insert (Key t (exportXOnlyPubKey ctx public)) (encodeTapDerivation d)+insertTapDerivation :: Word8 -> PubKey -> TapDerivation -> PsbtMap -> PsbtMap+insertTapDerivation t public d = Map.insert (Key t (exportXOnlyPubKey public)) (encodeTapDerivation d)  -- | The derivations of the x-only keys of a Taproot input, each with the -- leaves it appears in: PSBT_IN_TAP_BIP32_DERIVATION. The key is the -- point of even y with that x coordinate.-inputTapDerivations :: Ctx -> PsbtMap -> Either String [(PubKey, TapDerivation)]+inputTapDerivations :: PsbtMap -> Either String [(PubKey, TapDerivation)] inputTapDerivations = tapDerivationsOf inTapDerivationType -insertInputTapDerivation :: Ctx -> PubKey -> TapDerivation -> PsbtMap -> PsbtMap+insertInputTapDerivation :: PubKey -> TapDerivation -> PsbtMap -> PsbtMap insertInputTapDerivation = insertTapDerivation inTapDerivationType  -- | The derivations of the x-only keys of a Taproot output: -- PSBT_OUT_TAP_BIP32_DERIVATION. A record is a claim of whoever wrote the -- PSBT, as for 'outputDerivations'.-outputTapDerivations :: Ctx -> PsbtMap -> Either String [(PubKey, TapDerivation)]+outputTapDerivations :: PsbtMap -> Either String [(PubKey, TapDerivation)] outputTapDerivations = tapDerivationsOf outTapDerivationType -insertOutputTapDerivation :: Ctx -> PubKey -> TapDerivation -> PsbtMap -> PsbtMap+insertOutputTapDerivation :: PubKey -> TapDerivation -> PsbtMap -> PsbtMap insertOutputTapDerivation = insertTapDerivation outTapDerivationType -xOnlyKeyField :: Word8 -> String -> Ctx -> PsbtMap -> Either String (Maybe PubKey)-xOnlyKeyField t what ctx = optionalField what t (maybe (Left "is not an x-only public key") Right . importXOnlyPubKey ctx)+xOnlyKeyField :: Word8 -> String -> PsbtMap -> Either String (Maybe PubKey)+xOnlyKeyField t what = optionalField what t (maybe (Left "is not an x-only public key") Right . importXOnlyPubKey) -insertXOnlyKeyField :: Word8 -> Ctx -> PubKey -> PsbtMap -> PsbtMap-insertXOnlyKeyField t ctx = insertPlainField t . exportXOnlyPubKey ctx+insertXOnlyKeyField :: Word8 -> PubKey -> PsbtMap -> PsbtMap+insertXOnlyKeyField t = insertPlainField t . exportXOnlyPubKey  -- | The internal key of the Taproot coin an input spends: -- PSBT_IN_TAP_INTERNAL_KEY. The key is the point of even y with that x -- coordinate.-inputTapInternalKey :: Ctx -> PsbtMap -> Either String (Maybe PubKey)+inputTapInternalKey :: PsbtMap -> Either String (Maybe PubKey) inputTapInternalKey = xOnlyKeyField inTapInternalKeyType "The internal key" -insertInputTapInternalKey :: Ctx -> PubKey -> PsbtMap -> PsbtMap+insertInputTapInternalKey :: PubKey -> PsbtMap -> PsbtMap insertInputTapInternalKey = insertXOnlyKeyField inTapInternalKeyType  -- | The root of the script tree of the Taproot coin an input spends:@@ -1490,10 +1488,10 @@ insertInputTapMerkleRoot = insertPlainField tapMerkleRootType . BA.convert  -- | The internal key of a Taproot output: PSBT_OUT_TAP_INTERNAL_KEY-outputTapInternalKey :: Ctx -> PsbtMap -> Either String (Maybe PubKey)+outputTapInternalKey :: PsbtMap -> Either String (Maybe PubKey) outputTapInternalKey = xOnlyKeyField outTapInternalKeyType "The internal key" -insertOutputTapInternalKey :: Ctx -> PubKey -> PsbtMap -> PsbtMap+insertOutputTapInternalKey :: PubKey -> PsbtMap -> PsbtMap insertOutputTapInternalKey = insertXOnlyKeyField outTapInternalKeyType  -- | The script tree of a Taproot output, as its leaves depth first:@@ -1662,7 +1660,7 @@ -- 'sigHashAll'. The other types leave part of the transaction out of the -- signature, so a PSBT written by someone else may not ask for them on its -- own; a signer that agrees to them lists them, for example--- @(keySigner ctx key) {acceptedSigHashes = sigHashNone : defaultSigHashes}@.+-- @(keySigner key) {acceptedSigHashes = sigHashNone : defaultSigHashes}@. defaultSigHashes :: [SigHash] defaultSigHashes = [sigHashDefault, sigHashAll] @@ -1680,14 +1678,14 @@ -- previous transaction of a SegWit version 0 coin ('requirePreviousTx'). -- A caller that has checked the amounts of its coins another way, for -- example against its own records, turns that off with--- @(keySigner ctx key) {requirePreviousTx = False}@.-keySigner :: Ctx -> SecKey -> Signer-keySigner ctx secret =+-- @(keySigner key) {requirePreviousTx = False}@.+keySigner :: SecKey -> Signer+keySigner secret =   Signer     { keyOfRecord = \public _ -> do-        guard (public.point == derivePubKey ctx secret)+        guard (public.point == derivePubKey secret)         return secret,-      keyOfHash = \h -> find ((== h) . addressHash . marshal ctx . derivePublicKey ctx) [PrivateKey secret True, PrivateKey secret False],+      keyOfHash = \h -> find ((== h) . addressHash . encodeSerial . derivePublicKey) [PrivateKey secret True, PrivateKey secret False],       acceptedSigHashes = defaultSigHashes,       requirePreviousTx = True     }@@ -1701,24 +1699,25 @@ -- below a key that cannot derive it, names no key. It has no key for a -- hash, since it cannot know which path to derive. Like 'keySigner', it -- wants the previous transaction of a SegWit version 0 coin.-xPrvSigner :: Ctx -> XPrvKey -> Maybe Derivation -> Signer-xPrvSigner ctx xprv originM =+xPrvSigner :: XPrvKey -> Maybe Derivation -> Signer+xPrvSigner xprv originM =   Signer     { keyOfRecord = \public derivation -> do         path <- relative derivation-        secret <- (.key) <$> eitherToMaybe (tryDerivePath ctx path xprv)-        guard (public.point == derivePubKey ctx secret)+        secret <- (.key) <$> eitherToMaybe (tryDerivePath path xprv)+        guard (public.point == derivePubKey secret)         return secret,       keyOfHash = const Nothing,       acceptedSigHashes = defaultSigHashes,       requirePreviousTx = True     }   where-    own = xPubFP ctx (deriveXPubKey ctx xprv)+    own = xPubFP (deriveXPubKey xprv)     relative :: Derivation -> Maybe DerivPath     relative derivation       | derivation.fingerprint == own = Just derivation.path-      | Just origin <- originM, derivation.fingerprint == origin.fingerprint =+      | Just origin <- originM,+        derivation.fingerprint == origin.fingerprint =           listToPath <$> stripPrefix (pathToList origin.path) (pathToList derivation.path)       | otherwise = Nothing @@ -1765,15 +1764,15 @@ -- An input without its coin, with a final script already, with a coin, -- redeem script or witness script that is no standard template, or for -- which the signer holds no key, is left as it is.-signPsbt :: Network -> Ctx -> Signer -> Psbt -> Either String Psbt-signPsbt net ctx signer psbt = do+signPsbt :: Network -> Signer -> Psbt -> Either String Psbt+signPsbt net signer psbt = do   coins <- spentOutputs psbt   let allCoins = mapM (fmap fst) coins   signed <- forM (zip3 [0 ..] (zip tx.inputs psbt.inputs) coins) $ \(i, (input, m), coinM) ->     first (("Input " <> show i <> ": ") <>) $ case coinM of       Just (coin, witnessOnly)         | not (isFinal m),-          Right coinScript <- unmarshal ctx coin.script -> do+          Right coinScript <- decodeSerial coin.script -> do             sighashM <- sigHashType m             if isTaprootCoin coinScript               then signTaproot i m coinScript sighashM allCoins@@ -1790,11 +1789,11 @@       checkEcdsaSigHash net sighash       unless (acceptsSigHash signer sighash) $         Left (notAcceptedSigHash sighash)-      scriptsM <- inputScripts ctx coinScript m+      scriptsM <- inputScripts coinScript m       case scriptsM of         Nothing -> return (m, [])         Just scripts -> do-          keys <- heldKeys m (maybe [] (scriptKeyHashes ctx) scripts.signedScript)+          keys <- heldKeys m (maybe [] scriptKeyHashes scripts.signedScript)           if null keys             then return (m, [])             else do@@ -1808,9 +1807,9 @@                 Left "a SegWit version 0 coin may not be signed with an uncompressed key"               let sigInput = signingInput input coin sighash scripts               signatures <- forM keys $ \key -> do-                signature <- makeSignature net ctx tx i sigInput key-                return (derivePublicKey ctx key, encodeTxSig net ctx signature)-              return (foldr (\(public, sig) -> insertPartialSignature ctx public sig) m signatures, [sighash])+                signature <- makeSignature net tx i sigInput key+                return (derivePublicKey key, encodeTxSig net signature)+              return (foldr (\(public, sig) -> insertPartialSignature public sig) m signatures, [sighash])      -- The keys the signer holds among those whose hashes the script that     -- is signed names. The signer is asked for the key of a derivation@@ -1822,11 +1821,11 @@     heldKeys m named = do       let namedRecords = [(key, value) | (key, value) <- Map.toAscList m, key.keyType == inDerivationType, addressHash key.keyData `elem` named]       recordKeys <- forM namedRecords $ \(key, value) -> do-        public <- first (const ("The key " <> showKey key <> " is not a public key")) (unmarshal ctx key.keyData)+        public <- first (const ("The key " <> showKey key <> " is not a public key")) (decodeSerial key.keyData)         derivation <- first (("The value of the key " <> showKey key <> " ") <>) (decodeDerivation value)-        return [PrivateKey secret public.compress | Just secret <- [signer.keyOfRecord public derivation], derivePubKey ctx secret == public.point]-      let hashKeys = [key | h <- named, Just key <- [signer.keyOfHash h], addressHash (marshal ctx (derivePublicKey ctx key)) == h]-      return $ nubBy (\a b -> derivePublicKey ctx a == derivePublicKey ctx b) (concat recordKeys <> hashKeys)+        return [PrivateKey secret public.compress | Just secret <- [signer.keyOfRecord public derivation], derivePubKey secret == public.point]+      let hashKeys = [key | h <- named, Just key <- [signer.keyOfHash h], addressHash (encodeSerial (derivePublicKey key)) == h]+      return $ nubBy (\a b -> derivePublicKey a == derivePublicKey b) (concat recordKeys <> hashKeys)      -- A key path signature, and one per leaf that is a single key check,     -- for a Taproot coin@@ -1838,22 +1837,22 @@         Left (notAcceptedSigHash sighash)       spent <- maybe (Left "a Taproot signature needs the output every input spends") Right allCoins       program <- taprootProgram coinScript-      internalM <- inputTapInternalKey ctx m+      internalM <- inputTapInternalKey m       rootM <- inputTapMerkleRoot m-      records <- inputTapDerivations ctx m-      leaves <- tapLeafScripts ctx m+      records <- inputTapDerivations m+      leaves <- tapLeafScripts m       -- The secret key of an x-only key, by a record of that key which       -- the test accepts, or by the hash of the key. A key the signer       -- gives is kept only when it is the key that was asked for.       let heldXOnly accepts public =-            listToMaybe . filter (sameX public . derivePubKey ctx) . catMaybes $+            listToMaybe . filter (sameX public . derivePubKey) . catMaybes $               [signer.keyOfRecord (PublicKey candidate True) d.derivation | (recordKey, d) <- records, sameX recordKey public, accepts d, candidate <- bothParities public]-                <> [(.key) <$> signer.keyOfHash (addressHash (marshal ctx (PublicKey candidate True))) | candidate <- bothParities public]+                <> [(.key) <$> signer.keyOfHash (addressHash (encodeSerial (PublicKey candidate True))) | candidate <- bothParities public]       keySig <- case internalM of         Nothing -> return []         Just internal -> do-          let expected = taprootOutputKey ctx (TaprootOutput internal (MASTCommitment <$> rootM))-          unless (exportXOnlyPubKey ctx expected == program) $+          let expected = taprootOutputKey (TaprootOutput internal (MASTCommitment <$> rootM))+          unless (exportXOnlyPubKey expected == program) $             Left "the internal key and the Merkle root do not give the output key of the coin"           -- Any record of the internal key will do: BIP 371 lists in a           -- record the leaves the key is in, and the internal key may be@@ -1861,30 +1860,30 @@           case heldXOnly (const True) internal of             Nothing -> return []             Just secret -> do-              tweaked <- maybe (Left "the key cannot be tweaked") Right (taprootOutputSecKey ctx secret (MASTCommitment <$> rootM))+              tweaked <- maybe (Left "the key cannot be tweaked") Right (taprootOutputSecKey secret (MASTCommitment <$> rootM))               h <- taprootSigHash tx spent i sighash Nothing Nothing-              signature <- taprootSignature (signSchnorr ctx tweaked (hashToMsg h)) sighash+              signature <- taprootSignature (signSchnorr tweaked (hashToMsg h)) sighash               return [insertTapKeySig signature]-      scriptSigs <- fmap concat . forM leaves $ \leaf -> case singleKeyLeaf ctx leaf of+      scriptSigs <- fmap concat . forM leaves $ \leaf -> case singleKeyLeaf leaf of         Just leafKey           -- Only a leaf of the coin is signed: its control block must           -- commit it to the output key-          | Just outKey <- importXOnlyPubKey ctx program,-            commitsLeaf ctx outKey leaf,+          | Just outKey <- importXOnlyPubKey program,+            commitsLeaf outKey leaf,             Just secret <- heldXOnly ((hashOfLeaf `elem`) . (.leafHashes)) leafKey -> do               h <- taprootSigHash tx spent i sighash Nothing (Just (hashOfLeaf, 0xffffffff))-              signature <- taprootSignature (signSchnorr ctx secret (hashToMsg h)) sighash-              return [insertTapScriptSig ctx leafKey hashOfLeaf signature]+              signature <- taprootSignature (signSchnorr secret (hashToMsg h)) sighash+              return [insertTapScriptSig leafKey hashOfLeaf signature]           where             hashOfLeaf = leafHash leaf.leafVersion leaf.script         _ -> return []       let inserts = keySig <> scriptSigs       return (foldr ($) m inserts, [sighash | not (null inserts)]) -    sameX a b = exportXOnlyPubKey ctx a == exportXOnlyPubKey ctx b+    sameX a b = exportXOnlyPubKey a == exportXOnlyPubKey b     -- The two points with the x coordinate of the key     bothParities public =-      mapMaybe (\prefix -> (.point) <$> eitherToMaybe (unmarshal ctx (B.cons prefix (exportXOnlyPubKey ctx public)) :: Either String PublicKey)) [0x02, 0x03]+      mapMaybe (\prefix -> (.point) <$> eitherToMaybe (decodeSerial (B.cons prefix (exportXOnlyPubKey public)) :: Either String PublicKey)) [0x02, 0x03]  -- | The sighash type of an ECDSA signature for an input that asks for -- none: SIGHASH_ALL, with the fork id flag on a network that has one@@ -1895,28 +1894,28 @@  -- | The hashes of the keys a script names: the keys a coin of that script -- is signed with-scriptKeyHashes :: Ctx -> ScriptOutput -> [Hash160]-scriptKeyHashes ctx = \case-  PayPK public -> [addressHash (marshal ctx public)]+scriptKeyHashes :: ScriptOutput -> [Hash160]+scriptKeyHashes = \case+  PayPK public -> [addressHash (encodeSerial public)]   PayPKHash h -> [h]   PayWitnessPKHash h -> [h]-  PayMulSig publics _ -> map (addressHash . marshal ctx) publics+  PayMulSig publics _ -> map (addressHash . encodeSerial) publics   _ -> []  -- | The leaf key of a leaf script that is a single key check, @<key> -- OP_CHECKSIG@ of leaf version 0xc0-singleKeyLeaf :: Ctx -> TapLeafScript -> Maybe PubKey-singleKeyLeaf ctx leaf = case leaf.script.ops of+singleKeyLeaf :: TapLeafScript -> Maybe PubKey+singleKeyLeaf leaf = case leaf.script.ops of   [OP_PUSHDATA keyBytes OPCODE, OP_CHECKSIG]-    | leaf.leafVersion == tapscriptLeafVersion -> importXOnlyPubKey ctx keyBytes+    | leaf.leafVersion == tapscriptLeafVersion -> importXOnlyPubKey keyBytes   _ -> Nothing  -- | Whether the control block of a leaf script commits the leaf to the -- output key of the coin-commitsLeaf :: Ctx -> PubKey -> TapLeafScript -> Bool-commitsLeaf ctx outKey leaf = case decodeControlBlock ctx leaf.controlBlock of+commitsLeaf :: PubKey -> TapLeafScript -> Bool+commitsLeaf outKey leaf = case decodeControlBlock leaf.controlBlock of   Right (v, internalKey, proof) ->-    verifyScriptPathData ctx outKey (ScriptPathData Nothing [] leaf.script (odd v) (v .&. 0xfe) internalKey proof Nothing)+    verifyScriptPathData outKey (ScriptPathData Nothing [] leaf.script (odd v) (v .&. 0xfe) internalKey proof Nothing)   Left _ -> False  -- | The error for a sighash type the signer does not accept@@ -2060,12 +2059,12 @@ -- one that does not is reported in 'mismatch'. 'Nothing' when the script -- that names the keys is no standard template: the library cannot sign or -- finalize such an input, and leaves it to others.-inputScripts :: Ctx -> ScriptOutput -> PsbtMap -> Either String (Maybe InputScripts)-inputScripts ctx coinScript m = do+inputScripts :: ScriptOutput -> PsbtMap -> Either String (Maybe InputScripts)+inputScripts coinScript m = do   redeemM <- inputRedeemScript m   witnessM <- inputWitnessScript m-  let redeemOutM = decodeOutput ctx <$> redeemM-      witnessOutM = decodeOutput ctx <$> witnessM+  let redeemOutM = decodeOutput <$> redeemM+      witnessOutM = decodeOutput <$> witnessM       -- A SegWit coin, nested in P2SH or not, is signed against its witness       -- program; any other against its own script       program = case redeemOutM of@@ -2137,19 +2136,19 @@ -- other input stays as it is: one without enough signatures, one whose -- scripts are no standard template, and a legacy coin known from its -- witness output only, which Bitcoin Core does not finalize either.-finalizePsbt :: Network -> Ctx -> Psbt -> Either String Psbt-finalizePsbt net ctx psbt = do+finalizePsbt :: Network -> Psbt -> Either String Psbt+finalizePsbt net psbt = do   coins <- spentOutputs psbt   let allCoins = mapM (fmap fst) coins   inputs <- forM (zip3 [0 ..] (zip tx.inputs psbt.inputs) coins) $ \(i, (input, m), coinM) ->     first (("Input " <> show i <> ": ") <>) $ case coinM of       Just (output :: TxOut, witnessOnly)         | not (isFinal m),-          Right coinScript <- unmarshal ctx output.script -> do+          Right coinScript <- decodeSerial output.script -> do             finals <-               if isTaprootCoin coinScript-                then finalTaprootScripts ctx tx allCoins i m coinScript-                else finalScripts net ctx tx i input output witnessOnly coinScript m+                then finalTaprootScripts tx allCoins i m coinScript+                else finalScripts net tx i input output witnessOnly coinScript m             return $ case finals of               Just (scriptSig, stack) ->                 foldr ($) (cleared m) $@@ -2167,10 +2166,10 @@ -- | The final script and witness of an input signed with ECDSA, from the -- partial signatures of the keys its script names, when they suffice. -- Each of those signatures is verified first.-finalScripts :: Network -> Ctx -> Tx -> Int -> TxIn -> TxOut -> Bool -> ScriptOutput -> PsbtMap -> Either String (Maybe (ByteString, WitnessStack))-finalScripts net ctx tx i input output witnessOnly coinScript m = do+finalScripts :: Network -> Tx -> Int -> TxIn -> TxOut -> Bool -> ScriptOutput -> PsbtMap -> Either String (Maybe (ByteString, WitnessStack))+finalScripts net tx i input output witnessOnly coinScript m = do   sighashM <- sigHashType m-  scriptsM <- inputScripts ctx coinScript m+  scriptsM <- inputScripts coinScript m   case scriptsM of     Nothing -> return Nothing     Just scripts@@ -2185,17 +2184,17 @@                     Just _ -> " does not use the sighash type of the input"                     Nothing -> " does not use SIGHASH_ALL, and the input names no sighash type"               sigInput = signingInput input output asked scripts-              named = maybe [] (namedSignatures ctx m) scripts.signedScript+              named = maybe [] (namedSignatures m) scripts.signedScript           -- The signatures of the keys the script names: each is a           -- signature, of the sighash type asked, by a key the coin may be           -- spent with           checked <- forM named $ \(public, bytes) -> do-            (sig, sh) <- case decodeTxSig net ctx bytes of+            (sig, sh) <- case decodeTxSig net bytes of               Right (TxSignature sig sh) -> return (sig, sh)-              _ -> Left ("the signature of the key " <> quoted (marshal ctx public) <> " is not a valid signature")-            unless (sh == asked) $ otherType (marshal ctx public)+              _ -> Left ("the signature of the key " <> quoted (encodeSerial public) <> " is not a valid signature")+            unless (sh == asked) $ otherType (encodeSerial public)             when (isSegwit scripts.program && not public.compress) $-              Left ("the signature of the key " <> quoted (marshal ctx public) <> " is of an uncompressed key, which a SegWit version 0 coin may not be spent with")+              Left ("the signature of the key " <> quoted (encodeSerial public) <> " is of an uncompressed key, which a SegWit version 0 coin may not be spent with")             return (public, sig)           -- Every other signature of the input uses that sighash type too:           -- its last byte tells, and nothing else of it is looked at@@ -2205,10 +2204,10 @@             then return Nothing             else do               -- One digest serves every signature, since all use one type-              digest <- makeSigHash net ctx tx i sigInput.script output.value asked sigInput.redeem+              digest <- makeSigHash net tx i sigInput.script output.value asked sigInput.redeem               forM_ checked $ \(public, sig) ->-                unless (verifyHashSig ctx digest sig public.point) $-                  Left ("the signature of the key " <> quoted (marshal ctx public) <> " does not verify")+                unless (verifyHashSig digest sig public.point) $+                  Left ("the signature of the key " <> quoted (encodeSerial public) <> " does not verify")               return (assemble scripts named)   where     quoted = show . encodeHex@@ -2242,27 +2241,27 @@       PayWitnessPKHash h -> withKey <$> ofHash named h       _ -> Nothing     ofHash :: [(PublicKey, ByteString)] -> Hash160 -> Maybe (PublicKey, ByteString)-    ofHash named h = listToMaybe [(public, signature) | (public, signature) <- named, addressHash (marshal ctx public) == h]+    ofHash named h = listToMaybe [(public, signature) | (public, signature) <- named, addressHash (encodeSerial public) == h]     enough :: [(PublicKey, ByteString)] -> [PublicKey] -> Int -> Maybe [ByteString]     enough named keys n = let found = mapMaybe (`lookup` named) keys in if length found >= n then Just (take n found) else Nothing     withKey :: (PublicKey, ByteString) -> [ByteString]-    withKey (public, signature) = [signature, marshal ctx public]+    withKey (public, signature) = [signature, encodeSerial public]     scriptOf = S.encode . Script . map opPushData  -- | The partial signatures of an input whose keys the script names, in -- the order of the map. A key is named by a script of public keys when it -- is one of them, and by a script of a key hash when it has that hash. -- The others are not looked at, so their number costs nothing.-namedSignatures :: Ctx -> PsbtMap -> ScriptOutput -> [(PublicKey, ByteString)]-namedSignatures ctx m script =+namedSignatures :: PsbtMap -> ScriptOutput -> [(PublicKey, ByteString)]+namedSignatures m script =   [ (public, sig)   | (key, sig) <- Map.toAscList m,     key.keyType == partialSigType,     addressHash key.keyData `elem` named,-    Right public <- [unmarshal ctx key.keyData]+    Right public <- [decodeSerial key.keyData]   ]   where-    named = scriptKeyHashes ctx script+    named = scriptKeyHashes script  -- | The final witness of a Taproot input: its key path signature, or the -- signature of the first leaf script that is a single key check with the@@ -2270,14 +2269,14 @@ -- against the output key and the digest of its leaf. A signature must -- use the sighash type the input names, and SIGHASH_DEFAULT when it names -- none, as Bitcoin Core requires.-finalTaprootScripts :: Ctx -> Tx -> Maybe [TxOut] -> Int -> PsbtMap -> ScriptOutput -> Either String (Maybe (ByteString, WitnessStack))-finalTaprootScripts ctx tx allCoins i m coinScript = do+finalTaprootScripts :: Tx -> Maybe [TxOut] -> Int -> PsbtMap -> ScriptOutput -> Either String (Maybe (ByteString, WitnessStack))+finalTaprootScripts tx allCoins i m coinScript = do   program <- taprootProgram coinScript-  outKey <- maybe (Left "the coin is not a Taproot output") Right (importXOnlyPubKey ctx program)+  outKey <- maybe (Left "the coin is not a Taproot output") Right (importXOnlyPubKey program)   sighashM <- sigHashType m   keySigM <- tapKeySig m-  scriptSigs <- tapScriptSigs ctx m-  leaves <- tapLeafScripts ctx m+  scriptSigs <- tapScriptSigs m+  leaves <- tapLeafScripts m   let sameType :: TaprootSignature -> Either String ()       sameType signature = case sighashM of         Just asked -> unless (signature.hash == asked) $ Left "a Taproot signature does not use the sighash type of the input"@@ -2288,25 +2287,25 @@     Just signature -> do       spent <- maybe (Left "a Taproot signature needs the output every input spends") Right allCoins       digest <- taprootSigHash tx spent i signature.hash Nothing Nothing-      unless (verifySchnorr ctx outKey signature.sig (hashToMsg digest)) $+      unless (verifySchnorr outKey signature.sig (hashToMsg digest)) $         Left "the key path signature does not verify"       return (Just (B.empty, [encodeTaprootSig signature]))     Nothing -> do       let candidates =             [ (leaf, leafKey, signature)             | leaf <- leaves,-              Just leafKey <- [singleKeyLeaf ctx leaf],+              Just leafKey <- [singleKeyLeaf leaf],               Just signature <- [lookup (leafKey, leafHash leaf.leafVersion leaf.script) [((k, h), sig) | ((k, h), sig) <- scriptSigs, sameX k leafKey]]             ]       case candidates of         [] -> return Nothing         (leaf, leafKey, signature) : _ -> do           spent <- maybe (Left "a Taproot signature needs the output every input spends") Right allCoins-          unless (commitsLeaf ctx outKey leaf) $+          unless (commitsLeaf outKey leaf) $             Left "the control block of the leaf does not commit it to the output key"           digest <- taprootSigHash tx spent i signature.hash Nothing (Just (leafHash leaf.leafVersion leaf.script, 0xffffffff))-          unless (verifySchnorr ctx leafKey signature.sig (hashToMsg digest)) $+          unless (verifySchnorr leafKey signature.sig (hashToMsg digest)) $             Left "the script path signature does not verify"           return (Just (B.empty, [encodeTaprootSig signature, S.encode leaf.script, leaf.controlBlock]))   where-    sameX a b = exportXOnlyPubKey ctx a == exportXOnlyPubKey ctx b+    sameX a b = exportXOnlyPubKey a == exportXOnlyPubKey b
src/Haskoin/Transaction/Segwit.hs view
@@ -64,10 +64,10 @@ -- | Encode a witness program -- -- @since 0.11.0.0-toWitnessStack :: Network -> Ctx -> WitnessProgram -> WitnessStack-toWitnessStack net ctx = \case+toWitnessStack :: Network -> WitnessProgram -> WitnessStack+toWitnessStack net = \case   P2WPKH (WitnessProgramPKH sig key) ->-    [encodeTxSig net ctx sig, marshal ctx key]+    [encodeTxSig net sig, encodeSerial key]   P2WSH (WitnessProgramSH stack scr) ->     stack <> [runPutS (serialize scr)]   EmptyWitnessProgram ->@@ -96,14 +96,13 @@ -- @since 0.11.0.0 viewWitnessProgram ::   Network ->-  Ctx ->   ScriptOutput ->   WitnessStack ->   Either String WitnessProgram-viewWitnessProgram net ctx so witness = case so of+viewWitnessProgram net so witness = case so of   PayWitnessPKHash _ | length witness == 2 -> do-    sig <- decodeTxSig net ctx (head witness)-    pubkey <- decodePubKey ctx $ witness !! 1+    sig <- decodeTxSig net (head witness)+    pubkey <- decodePubKey $ witness !! 1     return . P2WPKH $ WitnessProgramPKH sig pubkey   PayWitnessScriptHash _ | not (null witness) -> do     redeemScript <- runGetS deserialize $ last witness@@ -117,23 +116,22 @@ -- @since 0.11.0.0 decodeWitnessInput ::   Network ->-  Ctx ->   WitnessProgram ->   Either String (Maybe ScriptOutput, SimpleInput)-decodeWitnessInput net ctx = \case+decodeWitnessInput net = \case   P2WPKH (WitnessProgramPKH sig key) -> return (Nothing, SpendPKHash sig key)   P2WSH (WitnessProgramSH st scr) -> do-    so <- decodeOutput ctx scr+    so <- decodeOutput scr     fmap (Just so,) $ case (so, st) of       (PayPK _, [sigBS]) ->-        SpendPK <$> decodeTxSig net ctx sigBS+        SpendPK <$> decodeTxSig net sigBS       (PayPKHash _, [sigBS, keyBS]) ->         SpendPKHash-          <$> decodeTxSig net ctx sigBS-          <*> decodePubKey ctx keyBS+          <$> decodeTxSig net sigBS+          <*> decodePubKey keyBS       (PayMulSig _ _, "" : sigsBS) ->         SpendMulSig-          <$> traverse (decodeTxSig net ctx) sigsBS+          <$> traverse (decodeTxSig net) sigsBS       _ -> Left "decodeWitnessInput: Non-standard script output"   EmptyWitnessProgram -> Left "decodeWitnessInput: Empty witness program" @@ -142,11 +140,10 @@ -- @since 0.11.0.0 calcWitnessProgram ::   Network ->-  Ctx ->   ScriptOutput ->   ScriptInput ->   Either String WitnessProgram-calcWitnessProgram net ctx so si = case (so, si) of+calcWitnessProgram net so si = case (so, si) of   (PayWitnessPKHash {}, RegularInput (SpendPKHash sig pk)) ->     Right $ p2wpkh sig pk   (PayScriptHash {}, RegularInput (SpendPKHash sig pk)) ->@@ -160,16 +157,16 @@     p2wpkh sig =       P2WPKH . WitnessProgramPKH sig     p2wsh i o =-      P2WSH . WitnessProgramSH (simpleInputStack net ctx i) <$> encodeOutput ctx o+      P2WSH . WitnessProgramSH (simpleInputStack net i) <$> encodeOutput o  -- | Create the witness stack required to spend a standard P2WSH input -- -- @since 0.11.0.0-simpleInputStack :: Network -> Ctx -> SimpleInput -> [ByteString]-simpleInputStack net ctx = \case+simpleInputStack :: Network -> SimpleInput -> [ByteString]+simpleInputStack net = \case   SpendPK sig -> [f sig]-  SpendPKHash sig k -> [f sig, marshal ctx k]+  SpendPKHash sig k -> [f sig, encodeSerial k]   SpendMulSig sigs -> "" : fmap f sigs   where     f TxSignatureEmpty = ""-    f sig = encodeTxSig net ctx sig+    f sig = encodeTxSig net sig
src/Haskoin/Transaction/Taproot.hs view
@@ -82,11 +82,12 @@ import Crypto.Secp256k1 import Data.Aeson   ( FromJSON (parseJSON),-    ToJSON (toJSON),+    ToJSON (toEncoding, toJSON),     Value (String),     withText,   ) import Data.Aeson.Types (Parser, Value)+import Data.Binary (Binary (..)) import Data.Bits ((.&.), (.|.)) import Data.Bool (bool) import Data.ByteArray qualified as BA@@ -97,6 +98,7 @@ import Data.Bytes.Serial (Serial (..), deserialize, serialize) import Data.Foldable (foldl') import Data.Maybe (fromMaybe, maybeToList)+import Data.Serialize (Serialize (..)) import Data.Word (Word32, Word8) import GHC.Records (HasField (..)) import Haskoin.Crypto.Hash@@ -124,34 +126,45 @@     where       f = BS.take 32 . (.get) -instance Marshal Ctx XOnlyPubKey where-  marshalPut ctx (XOnlyPubKey pk) =-    putByteString (exportXOnlyPubKey ctx pk)+instance Serial XOnlyPubKey where+  {-# INLINEABLE serialize #-}+  {-# INLINEABLE deserialize #-}+  serialize (XOnlyPubKey pk) =+    putByteString (exportXOnlyPubKey pk) -  marshalGet ctx =+  deserialize =     maybe (fail "Not an x-only public key") (pure . XOnlyPubKey)-      . importXOnlyPubKey ctx+      . importXOnlyPubKey       =<< getBytes 32 -instance MarshalJSON Ctx XOnlyPubKey where+instance Binary XOnlyPubKey where+  put = serialize+  get = deserialize++instance Serialize XOnlyPubKey where+  put = serialize+  get = deserialize++instance FromJSON XOnlyPubKey where   -- The hex must hold the 32 bytes of the key and nothing else. A longer   -- value, such as a 33-byte compressed key, is another kind of key.-  unmarshalValue ctx =-    withText "XOnlyPubKey" $ either fail pure . (unmarshal ctx <=< hex)+  parseJSON =+    withText "XOnlyPubKey" $ either fail pure . (decodeSerial <=< hex)     where       hex = maybe (Left "Unable to decode hex") Right . decodeHex -  marshalValue ctx =-    String . encodeHex . marshal ctx+instance ToJSON XOnlyPubKey where+  toJSON =+    String . encodeHex . encodeSerial -  marshalEncoding ctx =-    hexEncoding . runPutL . marshalPut ctx+  toEncoding =+    hexEncoding . runPutL . serialize  -- | The parity of the y coordinate of a key: 0 when it is even, 1 when it -- is odd. It is the parity bit of a control block.-keyParity :: Ctx -> PubKey -> Word8-keyParity ctx key =-  case BS.unpack . marshal ctx $ PublicKey key True of+keyParity :: PubKey -> Word8+keyParity key =+  case BS.unpack . encodeSerial $ PublicKey key True of     0x02 : _ -> 0x00     _ -> 0x01 @@ -352,13 +365,13 @@ --   'Nothing' in the same case. -- -- @since 0.21.0-taprootOutputKey :: Ctx -> TaprootOutput -> PubKey-taprootOutputKey ctx TaprootOutput {..} =+taprootOutputKey :: TaprootOutput -> PubKey+taprootOutputKey TaprootOutput {..} =   fromMaybe keyFail $-    tweak commitment >>= tweakAddXOnlyPubKey ctx internalKey+    tweak commitment >>= tweakAddXOnlyPubKey internalKey   where     commitment =-      taprootCommitment ctx internalKey $+      taprootCommitment internalKey $         mastCommitment <$> mast     keyFail = error "haskoin-core taprootOutputKey: key derivation failed" @@ -366,20 +379,20 @@ -- key given: the secret key, negated when its public key has an odd y -- coordinate, plus the tweak of 'taprootOutputKey'. 'Nothing' in the -- negligible case where the tweak gives no key.-taprootOutputSecKey :: Ctx -> SecKey -> Maybe MAST -> Maybe SecKey-taprootOutputSecKey ctx secret mast =-  tweak commitment >>= tweakAddXOnlySecKey ctx secret+taprootOutputSecKey :: SecKey -> Maybe MAST -> Maybe SecKey+taprootOutputSecKey secret mast =+  tweak commitment >>= tweakAddXOnlySecKey secret   where     commitment =-      taprootCommitment ctx (derivePubKey ctx secret) $+      taprootCommitment (derivePubKey secret) $         mastCommitment <$> mast -taprootCommitment :: Ctx -> PubKey -> Maybe (Digest SHA256) -> ByteString-taprootCommitment ctx internalKey merkleRoot =+taprootCommitment :: PubKey -> Maybe (Digest SHA256) -> ByteString+taprootCommitment internalKey merkleRoot =   BA.convert     . hashFinalize     . maybe id (flip hashUpdate) merkleRoot-    . (`hashUpdate` exportXOnlyPubKey ctx internalKey)+    . (`hashUpdate` exportXOnlyPubKey internalKey)     $ initTaggedHash "TapTweak"  -- | The output script of a Taproot output: witness version 1 and the@@ -387,13 +400,13 @@ -- too. Check a script tree with 'checkTapTree' before you pay to it. -- -- @since 0.21.0-taprootScriptOutput :: Ctx -> TaprootOutput -> ScriptOutput-taprootScriptOutput ctx =+taprootScriptOutput :: TaprootOutput -> ScriptOutput+taprootScriptOutput =   PayWitness 0x01     . runPutS-    . marshalPut ctx+    . serialize     . XOnlyPubKey-    . taprootOutputKey ctx+    . taprootOutputKey  {- Witnesses -} @@ -447,21 +460,21 @@ -- | The control block of a script path spend: the leaf version with the -- parity bit of the output key, the x-only internal key, and the proof -- of the leaf-encodeControlBlock :: Ctx -> Word8 -> PubKey -> [Digest SHA256] -> ByteString-encodeControlBlock ctx versionAndParity internalKey proof =-  BS.concat (BS.singleton versionAndParity : exportXOnlyPubKey ctx internalKey : map BA.convert proof)+encodeControlBlock :: Word8 -> PubKey -> [Digest SHA256] -> ByteString+encodeControlBlock versionAndParity internalKey proof =+  BS.concat (BS.singleton versionAndParity : exportXOnlyPubKey internalKey : map BA.convert proof)  -- | The parts of a control block, which must be 33 bytes plus 32 per node -- of the proof, with at most 'maxControlBlockNodes' nodes, as BIP 341 -- requires-decodeControlBlock :: Ctx -> ByteString -> Either String (Word8, PubKey, [Digest SHA256])-decodeControlBlock ctx bytes+decodeControlBlock :: ByteString -> Either String (Word8, PubKey, [Digest SHA256])+decodeControlBlock bytes   | len < 33 || (len - 33) `mod` 32 /= 0 =       Left ("decodeControlBlock: a control block is 33 bytes plus 32 per node, not " <> show len)   | nodeCount > maxControlBlockNodes =       Left ("decodeControlBlock: more than " <> show maxControlBlockNodes <> " nodes")   | otherwise = do-      internalKey <- maybe (Left "decodeControlBlock: the internal key is not an x-only public key") Right $ importXOnlyPubKey ctx (BS.take 32 (BS.drop 1 bytes))+      internalKey <- maybe (Left "decodeControlBlock: the internal key is not an x-only public key") Right $ importXOnlyPubKey (BS.take 32 (BS.drop 1 bytes))       proof <- traverse node (chunks (BS.drop 33 bytes))       return (BS.head bytes, internalKey, proof)   where@@ -480,12 +493,12 @@ -- witness and for a control block that 'decodeControlBlock' refuses. -- -- @since 0.21.0-viewTaprootWitness :: Ctx -> WitnessStack -> Maybe TaprootWitness-viewTaprootWitness ctx witnessStack =+viewTaprootWitness :: WitnessStack -> Maybe TaprootWitness+viewTaprootWitness witnessStack =   case reverse items of     [sig] -> Just (KeyPathSpend sig annex)     controlBytes : scriptBytes : reversedStack -> do-      (v, internalKey, control) <- eitherToMaybe $ decodeControlBlock ctx controlBytes+      (v, internalKey, control) <- eitherToMaybe $ decodeControlBlock controlBytes       -- The script is kept as opcodes when the bytes are exactly the       -- serialization of a list of opcodes, and as bytes otherwise, so       -- that the leaf hash is always the hash of the witness bytes.@@ -524,8 +537,8 @@ --   carry. -- -- @since 0.21.0-encodeTaprootWitness :: Ctx -> TaprootWitness -> Either String WitnessStack-encodeTaprootWitness ctx = \case+encodeTaprootWitness :: TaprootWitness -> Either String WitnessStack+encodeTaprootWitness = \case   KeyPathSpend signature annex -> do     mapM_ checkAnnex annex     return (signature : maybeToList annex)@@ -538,7 +551,7 @@     return $       d.stack         <> [ scriptPathScriptBytes d,-             encodeControlBlock ctx (d.leafVersion .|. bool 0 1 d.extIsOdd) d.internalKey d.control+             encodeControlBlock (d.leafVersion .|. bool 0 1 d.extIsOdd) d.internalKey d.control            ]         <> maybeToList d.annex   where@@ -563,24 +576,23 @@ -- -- @since 0.21.0 verifyScriptPathData ::-  Ctx ->   -- | Output key   PubKey ->   ScriptPathData ->   Bool-verifyScriptPathData ctx outkey spd = fromMaybe False $ do+verifyScriptPathData outkey spd = fromMaybe False $ do   if length spd.control > maxControlBlockNodes     then Nothing     else       tweak commitment         >>= fmap onComputedKey-          . tweakAddXOnlyPubKey ctx spd.internalKey+          . tweakAddXOnlyPubKey spd.internalKey   where     onComputedKey computedKey =       XOnlyPubKey outkey == XOnlyPubKey computedKey-        && expectedParity == keyParity ctx computedKey+        && expectedParity == keyParity computedKey     commitment =-      taprootCommitment ctx spd.internalKey (Just merkleRoot)+      taprootCommitment spd.internalKey (Just merkleRoot)     merkleRoot = foldl' hashBranch theLeafHash spd.control     theLeafHash = leafHashBytes (spd.leafVersion .&. 0xfe) (scriptPathScriptBytes spd)     expectedParity = bool 0 1 spd.extIsOdd@@ -705,7 +717,8 @@       serialize $ sha256 (runPutS (mapM_ (putVarIntBytes . (.script)) spent))       serialize $ sha256 (runPutS (mapM_ (putWord32le . (.sequence)) tx.inputs))     unless (isSigHashNone sh || isSigHashSingle sh) $-      serialize $ sha256 (runPutS (mapM_ serialize tx.outputs))+      serialize $+        sha256 (runPutS (mapM_ serialize tx.outputs))     putWord8 (bool 0 2 (isJust' leafM) .|. bool 0 1 (isJust' annexM))     if anyoneCanPay sh       then do@@ -717,7 +730,8 @@     forM_ annexM $ \annex ->       serialize $ sha256 (runPutS (putVarIntBytes annex))     when (isSigHashSingle sh) $-      serialize $ sha256 (runPutS (serialize (tx.outputs !! i)))+      serialize $+        sha256 (runPutS (serialize (tx.outputs !! i)))     forM_ leafM $ \(leaf, codeSeparatorPosition) -> do       putByteString (BA.convert leaf)       putWord8 0x00 -- the key version
src/Haskoin/Util/Arbitrary/Block.hs view
@@ -12,7 +12,6 @@  import qualified Data.HashMap.Strict as HashMap import Haskoin.Block-import Haskoin.Crypto (Ctx) import Haskoin.Network.Data import Haskoin.Transaction.Common (Tx, TxHash (..), txHash) import Haskoin.Util.Arbitrary.Crypto@@ -24,11 +23,11 @@ -- | Block of arbitrary transactions. The header has the Merkle root of the -- transactions when there are some. On a network without SegWit the -- transactions have no witness, as a block of that network has none.-arbitraryBlock :: Network -> Ctx -> Gen Block-arbitraryBlock net ctx = do+arbitraryBlock :: Network -> Gen Block+arbitraryBlock net = do   h <- arbitraryBlockHeader   c <- choose (0, 10)-  txs <- vectorOf c (arbitraryNetworkTx net ctx)+  txs <- vectorOf c (arbitraryNetworkTx net)   let header = case buildMerkleRoot (map txHash txs) of         Right root -> (h :: BlockHeader) {merkle = root}         Left _ -> h@@ -36,10 +35,10 @@  -- | Arbitrary transaction of the kind a peer of the network sends: with or -- without a witness where the network has SegWit, without one elsewhere.-arbitraryNetworkTx :: Network -> Ctx -> Gen Tx-arbitraryNetworkTx net ctx-  | net.segWit = arbitraryTx net ctx-  | otherwise = arbitraryLegacyTx net ctx+arbitraryNetworkTx :: Network -> Gen Tx+arbitraryNetworkTx net+  | net.segWit = arbitraryTx net+  | otherwise = arbitraryLegacyTx net  -- | Block header with random hash. arbitraryBlockHeader :: Gen BlockHeader
src/Haskoin/Util/Arbitrary/Keys.hs view
@@ -25,21 +25,21 @@ arbitraryPrivateKey = wrapSecKey <$> arbitrary <*> arbitrary  -- | Arbitrary public key, either compressed or not.-arbitraryPublicKey :: Ctx -> Gen PublicKey-arbitraryPublicKey ctx = snd <$> arbitraryKeyPair ctx+arbitraryPublicKey :: Gen PublicKey+arbitraryPublicKey = snd <$> arbitraryKeyPair  -- | Arbitrary keypair, both either compressed or not.-arbitraryKeyPair :: Ctx -> Gen (PrivateKey, PublicKey)-arbitraryKeyPair ctx = do+arbitraryKeyPair :: Gen (PrivateKey, PublicKey)+arbitraryKeyPair = do   k <- arbitraryPrivateKey-  return (k, derivePublicKey ctx k)+  return (k, derivePublicKey k)  -- | Arbitrary private key with its public key, both in compressed form: the -- only form of key that a SegWit version 0 input is signed with-arbitraryKeyPairC :: Ctx -> Gen (PrivateKey, PublicKey)-arbitraryKeyPairC ctx = do+arbitraryKeyPairC :: Gen (PrivateKey, PublicKey)+arbitraryKeyPairC = do   k <- wrapSecKey True <$> arbitrary-  return (k, derivePublicKey ctx k)+  return (k, derivePublicKey k)  arbitraryFingerprint :: Gen Fingerprint arbitraryFingerprint = Fingerprint <$> arbitrary@@ -54,12 +54,12 @@   XPrvKey depth parent index <$> arbitraryHash256 <*> arbitrary  -- | Arbitrary extended public key.-arbitraryXPubKey :: Ctx -> Gen XPubKey-arbitraryXPubKey ctx = snd <$> arbitraryXKeyPair ctx+arbitraryXPubKey :: Gen XPubKey+arbitraryXPubKey = snd <$> arbitraryXKeyPair  -- | Arbitrary extended public key with its corresponding private key.-arbitraryXKeyPair :: Ctx -> Gen (XPrvKey, XPubKey)-arbitraryXKeyPair ctx = (\k -> (k, deriveXPubKey ctx k)) <$> arbitraryXPrvKey+arbitraryXKeyPair :: Gen (XPrvKey, XPubKey)+arbitraryXKeyPair = (\k -> (k, deriveXPubKey k)) <$> arbitraryXPrvKey  {- Custom derivations -} @@ -100,9 +100,9 @@ -- | Arbitrary message hash, private key, nonce and corresponding signature. The -- signature is generated with a random message, random private key and a random -- nonce.-arbitrarySignature :: Ctx -> Gen (Hash256, SecKey, Sig)-arbitrarySignature ctx = do+arbitrarySignature :: Gen (Hash256, SecKey, Sig)+arbitrarySignature = do   m <- arbitraryHash256   key <- arbitrary-  let sig = signHash ctx key m+  let sig = signHash key m   return (m, key, sig)
src/Haskoin/Util/Arbitrary/Message.hs view
@@ -12,7 +12,6 @@  import Data.List (nub, sort) import Data.Word (Word32)-import Haskoin.Crypto (Ctx) import Haskoin.Network.BlockFilter import Haskoin.Network.CompactBlock import Haskoin.Network.Data@@ -51,14 +50,14 @@ -- | Arbitrary 'CompactBlock' that a peer of the network can send: positions -- within the 'maxCompactBlockIndex' of the network, and transactions as -- 'arbitraryNetworkTx' makes them.-arbitraryCompactBlock :: Network -> Ctx -> Gen CompactBlock-arbitraryCompactBlock net ctx = do+arbitraryCompactBlock :: Network -> Gen CompactBlock+arbitraryCompactBlock net = do   positions <- arbitraryPositionsUpTo net.maxCompactBlockIndex   CompactBlock     <$> arbitraryBlockHeader     <*> arbitrary     <*> listOf (choose (0, maxShortId))-    <*> mapM (\i -> PrefilledTx i <$> arbitraryNetworkTx net ctx) positions+    <*> mapM (\i -> PrefilledTx i <$> arbitraryNetworkTx net) positions  -- | Arbitrary 'GetBlockTxn' with positions of up to 32 bits. arbitraryGetBlockTxn :: Gen GetBlockTxn@@ -70,8 +69,8 @@   GetBlockTxn <$> arbitraryBlockHash <*> arbitraryPositionsUpTo net.maxCompactBlockIndex  -- | Arbitrary 'BlockTxn' that a peer of the network can send.-arbitraryBlockTxn :: Network -> Ctx -> Gen BlockTxn-arbitraryBlockTxn net ctx = BlockTxn <$> arbitraryBlockHash <*> listOf (arbitraryNetworkTx net ctx)+arbitraryBlockTxn :: Network -> Gen BlockTxn+arbitraryBlockTxn net = BlockTxn <$> arbitraryBlockHash <*> listOf (arbitraryNetworkTx net)  -- | Arbitrary 'GetCFilters'. arbitraryGetCFilters :: Gen GetCFilters@@ -103,8 +102,8 @@ arbitraryCFCheckpt = CFCheckpt <$> arbitrary <*> arbitraryBlockHash <*> listOf arbitraryHash256  -- | Arbitrary 'Message' of every kind, including one of an unknown command.-arbitraryMessage :: Network -> Ctx -> Gen Message-arbitraryMessage net ctx =+arbitraryMessage :: Network -> Gen Message+arbitraryMessage net =   oneof     [ MVersion <$> arbitraryVersion,       return MVerAck,@@ -116,8 +115,8 @@       MNotFound <$> arbitraryNotFound,       MGetBlocks <$> arbitraryGetBlocks,       MGetHeaders <$> arbitraryGetHeaders,-      MTx <$> arbitraryNetworkTx net ctx,-      MBlock <$> arbitraryBlock net ctx,+      MTx <$> arbitraryNetworkTx net,+      MBlock <$> arbitraryBlock net,       MMerkleBlock <$> arbitraryMerkleBlock,       MHeaders <$> arbitraryHeaders,       return MGetAddr,@@ -132,9 +131,9 @@       return MSendHeaders,       MFeeFilter <$> arbitraryFeeFilter,       MSendCompact <$> arbitrarySendCompact,-      MCompactBlock <$> arbitraryCompactBlock net ctx,+      MCompactBlock <$> arbitraryCompactBlock net,       MGetBlockTxn <$> arbitraryNetworkGetBlockTxn net,-      MBlockTxn <$> arbitraryBlockTxn net ctx,+      MBlockTxn <$> arbitraryBlockTxn net,       MGetCFilters <$> arbitraryGetCFilters,       MCFilter <$> arbitraryCFilter,       MGetCFHeaders <$> arbitraryGetCFHeaders,
src/Haskoin/Util/Arbitrary/Script.hs view
@@ -237,9 +237,9 @@ -- | Arbitrary message hash, private key and corresponding 'TxSignature'. The -- signature is generated deterministically using a random message and a random -- private key.-arbitraryTxSignature :: Network -> Ctx -> Gen (TxHash, SecKey, TxSignature)-arbitraryTxSignature net ctx = do-  (m, key, sig) <- arbitrarySignature ctx+arbitraryTxSignature :: Network -> Gen (TxHash, SecKey, TxSignature)+arbitraryTxSignature net = do+  (m, key, sig) <- arbitrarySignature   sh <- (fromIntegral <$> (arbitrary :: Gen Word8)) `suchThat` filterBad   let txsig = TxSignature sig sh   return (TxHash m, key, txsig)@@ -251,11 +251,11 @@           || isJust net.sigHashForkId && not (hasForkIdFlag sh)  -- | Arbitrary transaction signature that could also be empty.-arbitraryTxSignatureEmpty :: Network -> Ctx -> Gen TxSignature-arbitraryTxSignatureEmpty net ctx =+arbitraryTxSignatureEmpty :: Network -> Gen TxSignature+arbitraryTxSignatureEmpty net =   frequency     [ (1, return TxSignatureEmpty),-      (10, lst3 <$> arbitraryTxSignature net ctx)+      (10, lst3 <$> arbitraryTxSignature net)     ]  -- | Arbitrary m of n parameters, with n up to 'maxMultisigKeys'. Such a@@ -298,12 +298,12 @@   return (m, n)  -- | Arbitrary 'ScriptOutput' (Can by any valid type).-arbitraryScriptOutput :: Network -> Ctx -> Gen ScriptOutput-arbitraryScriptOutput net ctx =+arbitraryScriptOutput :: Network -> Gen ScriptOutput+arbitraryScriptOutput net =   oneof $-    [ arbitraryPKOutput ctx,+    [ arbitraryPKOutput,       arbitraryPKHashOutput,-      arbitraryMSOutput ctx,+      arbitraryMSOutput,       arbitrarySHOutput,       arbitraryDCOutput     ]@@ -321,17 +321,17 @@  -- | Arbitrary 'ScriptOutput' of type 'PayPK', 'PayPKHash' or 'PayMS' -- (Not 'PayScriptHash', 'DataCarrier', or SegWit)-arbitrarySimpleOutput :: Ctx -> Gen ScriptOutput-arbitrarySimpleOutput ctx =+arbitrarySimpleOutput :: Gen ScriptOutput+arbitrarySimpleOutput =   oneof-    [ arbitraryPKOutput ctx,+    [ arbitraryPKOutput,       arbitraryPKHashOutput,-      arbitraryMSOutput ctx+      arbitraryMSOutput     ]  -- | Arbitrary 'ScriptOutput' of type 'PayPK'-arbitraryPKOutput :: Ctx -> Gen ScriptOutput-arbitraryPKOutput ctx = PayPK . snd <$> arbitraryKeyPair ctx+arbitraryPKOutput :: Gen ScriptOutput+arbitraryPKOutput = PayPK . snd <$> arbitraryKeyPair  -- | Arbitrary 'ScriptOutput' of type 'PayPKHash' arbitraryPKHashOutput :: Gen ScriptOutput@@ -354,41 +354,41 @@   return $ PayWitness ver bs  -- | Arbitrary 'ScriptOutput' of type 'PayMS'.-arbitraryMSOutput :: Ctx -> Gen ScriptOutput-arbitraryMSOutput ctx = do+arbitraryMSOutput :: Gen ScriptOutput+arbitraryMSOutput = do   (m, n) <- arbitraryMSParam-  keys <- map snd <$> vectorOf n (arbitraryKeyPair ctx)+  keys <- map snd <$> vectorOf n arbitraryKeyPair   return $ PayMulSig keys m  -- | Arbitrary 'ScriptOutput' of type 'PayMS', only using compressed keys.-arbitraryMSOutputC :: Ctx -> Gen ScriptOutput-arbitraryMSOutputC ctx = do+arbitraryMSOutputC :: Gen ScriptOutput+arbitraryMSOutputC = do   (m, n) <- arbitraryMSParam   keys <-     map snd-      <$> vectorOf n (arbitraryKeyPair ctx `suchThat` ((.compress) . snd))+      <$> vectorOf n (arbitraryKeyPair `suchThat` ((.compress) . snd))   return $ PayMulSig keys m  -- | Arbitrary multisig that fits a pay-to-script-hash redeem script: up to -- 7 keys of any form, or up to 15 compressed keys.-arbitraryP2SHMSOutput :: Ctx -> Gen ScriptOutput-arbitraryP2SHMSOutput ctx =+arbitraryP2SHMSOutput :: Gen ScriptOutput+arbitraryP2SHMSOutput =   oneof     [ do         (m, n) <- arbitraryP2SHMSParam-        keys <- map snd <$> vectorOf n (arbitraryKeyPair ctx)+        keys <- map snd <$> vectorOf n arbitraryKeyPair         return $ PayMulSig keys m,-      arbitraryP2SHMSOutputC ctx+      arbitraryP2SHMSOutputC     ]  -- | Arbitrary multisig of compressed keys that fits a pay-to-script-hash -- redeem script: up to 15 keys.-arbitraryP2SHMSOutputC :: Ctx -> Gen ScriptOutput-arbitraryP2SHMSOutputC ctx = do+arbitraryP2SHMSOutputC :: Gen ScriptOutput+arbitraryP2SHMSOutputC = do   (m, n) <- arbitraryP2SHMSParamC   keys <-     map snd-      <$> vectorOf n (arbitraryKeyPair ctx `suchThat` ((.compress) . snd))+      <$> vectorOf n (arbitraryKeyPair `suchThat` ((.compress) . snd))   return $ PayMulSig keys m  -- | Arbitrary 'ScriptOutput' of type 'PayScript32Hash'.@@ -410,13 +410,13 @@  -- | Arbitrary 'ScriptInput'. A nested witness input is only drawn on a -- network that has SegWit.-arbitraryScriptInput :: Network -> Ctx -> Gen ScriptInput-arbitraryScriptInput net ctx =+arbitraryScriptInput :: Network -> Gen ScriptInput+arbitraryScriptInput net =   oneof $-    [ arbitraryPKInput net ctx,-      arbitraryPKHashInput net ctx,-      arbitraryMSInput net ctx,-      arbitrarySHInput net ctx+    [ arbitraryPKInput net,+      arbitraryPKHashInput net,+      arbitraryMSInput net,+      arbitrarySHInput net     ]       ++ [arbitraryNestedWitnessInput | net.segWit] @@ -428,98 +428,98 @@  -- | Arbitrary 'ScriptInput' of type 'SpendPK', 'SpendPKHash' or 'SpendMulSig' -- (not 'ScriptHashInput')-arbitrarySimpleInput :: Network -> Ctx -> Gen ScriptInput-arbitrarySimpleInput net ctx =+arbitrarySimpleInput :: Network -> Gen ScriptInput+arbitrarySimpleInput net =   oneof-    [ arbitraryPKInput net ctx,-      arbitraryPKHashInput net ctx,-      arbitraryMSInput net ctx+    [ arbitraryPKInput net,+      arbitraryPKHashInput net,+      arbitraryMSInput net     ]  -- | Arbitrary 'ScriptInput' of type 'SpendPK'.-arbitraryPKInput :: Network -> Ctx -> Gen ScriptInput-arbitraryPKInput net ctx = RegularInput . SpendPK <$> arbitraryTxSignatureEmpty net ctx+arbitraryPKInput :: Network -> Gen ScriptInput+arbitraryPKInput net = RegularInput . SpendPK <$> arbitraryTxSignatureEmpty net  -- | Arbitrary 'ScriptInput' of type 'SpendPK'.-arbitraryPKHashInput :: Network -> Ctx -> Gen ScriptInput-arbitraryPKHashInput net ctx = do-  sig <- arbitraryTxSignatureEmpty net ctx-  key <- snd <$> arbitraryKeyPair ctx+arbitraryPKHashInput :: Network -> Gen ScriptInput+arbitraryPKHashInput net = do+  sig <- arbitraryTxSignatureEmpty net+  key <- snd <$> arbitraryKeyPair   return $ RegularInput $ SpendPKHash sig key  -- | Like 'arbitraryPKHashInput' without empty signatures.-arbitraryPKHashInputFull :: Network -> Ctx -> Gen ScriptInput-arbitraryPKHashInputFull net ctx = do-  sig <- lst3 <$> arbitraryTxSignature net ctx-  key <- snd <$> arbitraryKeyPair ctx+arbitraryPKHashInputFull :: Network -> Gen ScriptInput+arbitraryPKHashInputFull net = do+  sig <- lst3 <$> arbitraryTxSignature net+  key <- snd <$> arbitraryKeyPair   return $ RegularInput $ SpendPKHash sig key  -- | Like above but only compressed.-arbitraryPKHashInputFullC :: Network -> Ctx -> Gen ScriptInput-arbitraryPKHashInputFullC net ctx = do-  sig <- lst3 <$> arbitraryTxSignature net ctx-  key <- fmap snd $ arbitraryKeyPair ctx `suchThat` ((.compress) . snd)+arbitraryPKHashInputFullC :: Network -> Gen ScriptInput+arbitraryPKHashInputFullC net = do+  sig <- lst3 <$> arbitraryTxSignature net+  key <- fmap snd $ arbitraryKeyPair `suchThat` ((.compress) . snd)   return $ RegularInput $ SpendPKHash sig key  -- | Arbitrary 'ScriptInput' of type 'SpendMulSig'.-arbitraryMSInput :: Network -> Ctx -> Gen ScriptInput-arbitraryMSInput net ctx = do+arbitraryMSInput :: Network -> Gen ScriptInput+arbitraryMSInput net = do   m <- fst <$> arbitraryMSParam-  sigs <- vectorOf m (arbitraryTxSignatureEmpty net ctx)+  sigs <- vectorOf m (arbitraryTxSignatureEmpty net)   return $ RegularInput $ SpendMulSig sigs  -- | Arbitrary 'ScriptInput' of type 'ScriptHashInput', whose input fits its -- redeem script: a 'SpendPK' for a 'PayPK', a 'SpendPKHash' for a -- 'PayPKHash', a 'SpendMulSig' for a 'PayMulSig'.-arbitrarySHInput :: Network -> Ctx -> Gen ScriptInput-arbitrarySHInput net ctx =+arbitrarySHInput :: Network -> Gen ScriptInput+arbitrarySHInput net =   oneof     [ do-        sig <- arbitraryTxSignatureEmpty net ctx-        ScriptHashInput (SpendPK sig) <$> arbitraryPKOutput ctx,+        sig <- arbitraryTxSignatureEmpty net+        ScriptHashInput (SpendPK sig) <$> arbitraryPKOutput,       do-        sig <- arbitraryTxSignatureEmpty net ctx-        key <- snd <$> arbitraryKeyPair ctx+        sig <- arbitraryTxSignatureEmpty net+        key <- snd <$> arbitraryKeyPair         ScriptHashInput (SpendPKHash sig key) <$> arbitraryPKHashOutput,-      arbitraryMulSigSHInput net ctx+      arbitraryMulSigSHInput net     ]  -- | Arbitrary 'ScriptInput' of type 'ScriptHashInput' containing a -- 'RedeemScript' of type 'PayMulSig' and an input of type 'SpendMulSig'. The -- redeem script is at most 520 bytes long, as a pay-to-script-hash redeem -- script must be.-arbitraryMulSigSHInput :: Network -> Ctx -> Gen ScriptInput-arbitraryMulSigSHInput net ctx =-  arbitraryP2SHMSOutput ctx >>= \case+arbitraryMulSigSHInput :: Network -> Gen ScriptInput+arbitraryMulSigSHInput net =+  arbitraryP2SHMSOutput >>= \case     rdm@(PayMulSig _ m) -> do-      sigs <- vectorOf m (arbitraryTxSignatureEmpty net ctx)+      sigs <- vectorOf m (arbitraryTxSignatureEmpty net)       return $ ScriptHashInput (SpendMulSig sigs) rdm     _ -> undefined  -- | Arbitrary 'ScriptInput' of type 'ScriptHashInput' containing a -- 'RedeemScript' of type 'PayMulSig' and an input of type 'SpendMulSig'.-arbitraryMulSigSHInputC :: Network -> Ctx -> Gen ScriptInput-arbitraryMulSigSHInputC net ctx =-  arbitraryP2SHMSOutputC ctx >>= \case+arbitraryMulSigSHInputC :: Network -> Gen ScriptInput+arbitraryMulSigSHInputC net =+  arbitraryP2SHMSOutputC >>= \case     rdm@(PayMulSig _ m) -> do-      sigs <- vectorOf m (arbitraryTxSignatureEmpty net ctx)+      sigs <- vectorOf m (arbitraryTxSignatureEmpty net)       return $ ScriptHashInput (SpendMulSig sigs) rdm     _ -> undefined  -- | Like 'arbitraryMulSigSHCInput' with no empty signatures.-arbitraryMulSigSHInputFull :: Network -> Ctx -> Gen ScriptInput-arbitraryMulSigSHInputFull net ctx =-  arbitraryP2SHMSOutput ctx >>= \case+arbitraryMulSigSHInputFull :: Network -> Gen ScriptInput+arbitraryMulSigSHInputFull net =+  arbitraryP2SHMSOutput >>= \case     rdm@(PayMulSig _ m) -> do-      sigs <- map lst3 <$> vectorOf m (arbitraryTxSignature net ctx)+      sigs <- map lst3 <$> vectorOf m (arbitraryTxSignature net)       return $ ScriptHashInput (SpendMulSig sigs) rdm     _ -> undefined  -- | Like 'arbitraryMulSigSHCInput' with no empty signatures.-arbitraryMulSigSHInputFullC :: Network -> Ctx -> Gen ScriptInput-arbitraryMulSigSHInputFullC net ctx =-  arbitraryP2SHMSOutputC ctx >>= \case+arbitraryMulSigSHInputFullC :: Network -> Gen ScriptInput+arbitraryMulSigSHInputFullC net =+  arbitraryP2SHMSOutputC >>= \case     rdm@(PayMulSig _ m) -> do-      sigs <- map lst3 <$> vectorOf m (arbitraryTxSignature net ctx)+      sigs <- map lst3 <$> vectorOf m (arbitraryTxSignature net)       return $ ScriptHashInput (SpendMulSig sigs) rdm     _ -> undefined
src/Haskoin/Util/Arbitrary/Transaction.hs view
@@ -15,11 +15,10 @@ import Data.ByteString qualified as BS import Data.Either (fromRight) import Data.List (findIndex, nub, nubBy, permutations)-import Data.Maybe (fromMaybe, isNothing) import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe, isNothing) import Data.Word (Word32, Word64) import Haskoin.Address-import Haskoin.Crypto (Ctx) import Haskoin.Crypto.Keys.Common import Haskoin.Crypto.Keys.Extended (XPubKey (..), listToPath) import Haskoin.Network.Constants@@ -99,42 +98,42 @@ arbitraryOutPoint = OutPoint <$> arbitraryTxHash <*> arbitrary  -- | Arbitrary 'TxOut'.-arbitraryTxOut :: Network -> Ctx -> Gen TxOut-arbitraryTxOut net ctx =+arbitraryTxOut :: Network -> Gen TxOut+arbitraryTxOut net =   TxOut     <$> (getTestCoin <$> arbitrarySatoshi net)-    <*> (marshal ctx <$> arbitraryScriptOutput net ctx)+    <*> (encodeSerial <$> arbitraryScriptOutput net)  -- | Arbitrary 'TxIn'.-arbitraryTxIn :: Network -> Ctx -> Gen TxIn-arbitraryTxIn net ctx =+arbitraryTxIn :: Network -> Gen TxIn+arbitraryTxIn net =   TxIn     <$> arbitraryOutPoint-    <*> (marshal (net, ctx) <$> arbitraryScriptInput net ctx)+    <*> (marshal net <$> arbitraryScriptInput net)     <*> arbitrary  -- | Arbitrary transaction. Can be regular or with witnesses.-arbitraryTx :: Network -> Ctx -> Gen Tx-arbitraryTx net ctx =-  oneof [arbitraryLegacyTx net ctx, arbitraryWitnessTx net ctx]+arbitraryTx :: Network -> Gen Tx+arbitraryTx net =+  oneof [arbitraryLegacyTx net, arbitraryWitnessTx net]  -- | Arbitrary regular transaction.-arbitraryLegacyTx :: Network -> Ctx -> Gen Tx-arbitraryLegacyTx net ctx = arbitraryWLTx net ctx False+arbitraryLegacyTx :: Network -> Gen Tx+arbitraryLegacyTx net = arbitraryWLTx net False  -- | Arbitrary witness transaction (witness data is fake). At least one -- input has a witness item, since a transaction whose stacks are all -- empty has no witness.-arbitraryWitnessTx :: Network -> Ctx -> Gen Tx-arbitraryWitnessTx net ctx = arbitraryWLTx net ctx True+arbitraryWitnessTx :: Network -> Gen Tx+arbitraryWitnessTx net = arbitraryWLTx net True  -- | Arbitrary witness or legacy transaction.-arbitraryWLTx :: Network -> Ctx -> Bool -> Gen Tx-arbitraryWLTx net ctx wit = do+arbitraryWLTx :: Network -> Bool -> Gen Tx+arbitraryWLTx net wit = do   ni <- choose (1, 5)   no <- choose (1, 5)-  inps <- vectorOf ni (arbitraryTxIn net ctx)-  outs <- vectorOf no (arbitraryTxOut net ctx)+  inps <- vectorOf ni (arbitraryTxIn net)+  outs <- vectorOf no (arbitraryTxOut net)   let uniqueInps = nubBy (\a b -> a.outpoint == b.outpoint) inps   w <-     if wit@@ -145,60 +144,60 @@ -- | Arbitrary transaction containing only inputs of type 'SpendPKHash', -- 'SpendScriptHash' (multisig) and outputs of type 'PayPKHash' and 'PaySH'. -- Only compressed public keys are used.-arbitraryAddrOnlyTx :: Network -> Ctx -> Gen Tx-arbitraryAddrOnlyTx net ctx = do+arbitraryAddrOnlyTx :: Network -> Gen Tx+arbitraryAddrOnlyTx net = do   ni <- choose (1, 5)   no <- choose (1, 5)-  inps <- vectorOf ni (arbitraryAddrOnlyTxIn net ctx)-  outs <- vectorOf no (arbitraryAddrOnlyTxOut net ctx)+  inps <- vectorOf ni (arbitraryAddrOnlyTxIn net)+  outs <- vectorOf no (arbitraryAddrOnlyTxOut net)   Tx <$> arbitrary <*> pure inps <*> pure outs <*> pure [] <*> arbitrary  -- | Like 'arbitraryAddrOnlyTx' without empty signatures in the inputs.-arbitraryAddrOnlyTxFull :: Network -> Ctx -> Gen Tx-arbitraryAddrOnlyTxFull net ctx = do+arbitraryAddrOnlyTxFull :: Network -> Gen Tx+arbitraryAddrOnlyTxFull net = do   ni <- choose (1, 5)   no <- choose (1, 5)-  inps <- vectorOf ni (arbitraryAddrOnlyTxInFull net ctx)-  outs <- vectorOf no (arbitraryAddrOnlyTxOut net ctx)+  inps <- vectorOf ni (arbitraryAddrOnlyTxInFull net)+  outs <- vectorOf no (arbitraryAddrOnlyTxOut net)   Tx <$> arbitrary <*> pure inps <*> pure outs <*> pure [] <*> arbitrary  -- | Arbitrary TxIn that can only be of type 'SpendPKHash' or 'SpendScriptHash' -- (multisig). Only compressed public keys are used.-arbitraryAddrOnlyTxIn :: Network -> Ctx -> Gen TxIn-arbitraryAddrOnlyTxIn net ctx = do-  inp <- oneof [arbitraryPKHashInput net ctx, arbitraryMulSigSHInput net ctx]-  TxIn <$> arbitraryOutPoint <*> pure (marshal (net, ctx) inp) <*> arbitrary+arbitraryAddrOnlyTxIn :: Network -> Gen TxIn+arbitraryAddrOnlyTxIn net = do+  inp <- oneof [arbitraryPKHashInput net, arbitraryMulSigSHInput net]+  TxIn <$> arbitraryOutPoint <*> pure (marshal net inp) <*> arbitrary  -- | like 'arbitraryAddrOnlyTxIn' with no empty signatures.-arbitraryAddrOnlyTxInFull :: Network -> Ctx -> Gen TxIn-arbitraryAddrOnlyTxInFull net ctx = do+arbitraryAddrOnlyTxInFull :: Network -> Gen TxIn+arbitraryAddrOnlyTxInFull net = do   inp <--    oneof [arbitraryPKHashInputFullC net ctx, arbitraryMulSigSHInputFullC net ctx]-  TxIn <$> arbitraryOutPoint <*> pure (marshal (net, ctx) inp) <*> arbitrary+    oneof [arbitraryPKHashInputFullC net, arbitraryMulSigSHInputFullC net]+  TxIn <$> arbitraryOutPoint <*> pure (marshal net inp) <*> arbitrary  -- | Arbitrary 'TxOut' that can only be of type 'PayPKHash' or 'PaySH'.-arbitraryAddrOnlyTxOut :: Network -> Ctx -> Gen TxOut-arbitraryAddrOnlyTxOut net ctx = do+arbitraryAddrOnlyTxOut :: Network -> Gen TxOut+arbitraryAddrOnlyTxOut net = do   v <- getTestCoin <$> arbitrarySatoshi net   out <- oneof [arbitraryPKHashOutput, arbitrarySHOutput]-  return $ TxOut v $ marshal ctx out+  return $ TxOut v $ encodeSerial out  -- | Arbitrary 'SigInput' with the corresponding private keys used -- to generate the 'ScriptOutput' or 'RedeemScript'. On a network with -- SegWit, it may be a SegWit version 0 output, or a Taproot output spent -- by its key path. The signer refuses those on a network without SegWit.-arbitrarySigInput :: Network -> Ctx -> Gen (SigInput, [PrivateKey])-arbitrarySigInput net ctx =+arbitrarySigInput :: Network -> Gen (SigInput, [PrivateKey])+arbitrarySigInput net =   oneof $-    [ wrapKey <$> arbitraryPKSigInput net ctx,-      wrapKey <$> arbitraryPKHashSigInput net ctx,-      arbitraryMSSigInput net ctx,-      arbitrarySHSigInput net ctx+    [ wrapKey <$> arbitraryPKSigInput net,+      wrapKey <$> arbitraryPKHashSigInput net,+      arbitraryMSSigInput net,+      arbitrarySHSigInput net     ]       <> concat-        [ [ wrapKey <$> arbitraryWPKHSigInput net ctx,-            arbitraryWSHSigInput net ctx,-            wrapKey <$> arbitraryTaprootSigInput net ctx+        [ [ wrapKey <$> arbitraryWPKHSigInput net,+            arbitraryWSHSigInput net,+            wrapKey <$> arbitraryTaprootSigInput net           ]         | net.segWit         ]@@ -207,35 +206,35 @@ -- by its key path with the key of the internal key, as a wallet of BIP 86 -- spends. The sighash is one a Taproot signature may use, other than -- SIGHASH_SINGLE, which needs an output at the index of the input.-arbitraryTaprootSigInput :: Network -> Ctx -> Gen (SigInput, PrivateKey)-arbitraryTaprootSigInput net ctx = do-  (k, p) <- arbitraryKeyPair ctx+arbitraryTaprootSigInput :: Network -> Gen (SigInput, PrivateKey)+arbitraryTaprootSigInput net = do+  (k, p) <- arbitraryKeyPair   val <- getTestCoin <$> arbitrarySatoshi net   op <- arbitraryOutPoint   sh <- elements [sigHashDefault, sigHashAll, sigHashNone, setAnyoneCanPay sigHashAll, setAnyoneCanPay sigHashNone]-  let out = taprootScriptOutput ctx (TaprootOutput p.point Nothing)+  let out = taprootScriptOutput (TaprootOutput p.point Nothing)   return (SigInput out val op sh Nothing, k)  -- | Arbitrary 'SigInput' with a 'ScriptOutput' of type 'PayPK'.-arbitraryPKSigInput :: Network -> Ctx -> Gen (SigInput, PrivateKey)-arbitraryPKSigInput net ctx = arbitraryAnyInput net ctx False+arbitraryPKSigInput :: Network -> Gen (SigInput, PrivateKey)+arbitraryPKSigInput net = arbitraryAnyInput net False  -- | Arbitrary 'SigInput' with a 'ScriptOutput' of type 'PayPKHash'.-arbitraryPKHashSigInput :: Network -> Ctx -> Gen (SigInput, PrivateKey)-arbitraryPKHashSigInput net ctx = arbitraryAnyInput net ctx True+arbitraryPKHashSigInput :: Network -> Gen (SigInput, PrivateKey)+arbitraryPKHashSigInput net = arbitraryAnyInput net True  -- | Arbitrary 'SigInput' of a key in either form.-arbitraryAnyInput :: Network -> Ctx -> Bool -> Gen (SigInput, PrivateKey)-arbitraryAnyInput net ctx = arbitraryAnyInputOf (arbitraryKeyPair ctx) net ctx+arbitraryAnyInput :: Network -> Bool -> Gen (SigInput, PrivateKey)+arbitraryAnyInput net = arbitraryAnyInputOf arbitraryKeyPair net  -- | Arbitrary 'SigInput' with a 'ScriptOutput' of type 'PayPKHash', when -- the flag is set, or 'PayPK', of a key from the generator given. arbitraryAnyInputOf ::-  Gen (PrivateKey, PublicKey) -> Network -> Ctx -> Bool -> Gen (SigInput, PrivateKey)-arbitraryAnyInputOf keyPair net ctx pkh = do+  Gen (PrivateKey, PublicKey) -> Network -> Bool -> Gen (SigInput, PrivateKey)+arbitraryAnyInputOf keyPair net pkh = do   (k, p) <- keyPair   let out-        | pkh = case addressHash160 (pubKeyAddr ctx p) of+        | pkh = case addressHash160 (pubKeyAddr p) of             Just h -> PayPKHash h             Nothing -> error "Could not get Hash160 from address"         | otherwise = PayPK p@@ -251,14 +250,14 @@   return (val, op, sh)  -- | Arbitrary 'SigInput' with a 'ScriptOutput' of type 'PayMulSig'.-arbitraryMSSigInput :: Network -> Ctx -> Gen (SigInput, [PrivateKey])+arbitraryMSSigInput :: Network -> Gen (SigInput, [PrivateKey]) arbitraryMSSigInput = arbitraryMSSigInputOf arbitraryMSParam  -- | Arbitrary 'SigInput' with a 'ScriptOutput' of type 'PayMulSig', whose m -- of n parameters come from the given generator. arbitraryMSSigInputOf ::-  Gen (Int, Int) -> Network -> Ctx -> Gen (SigInput, [PrivateKey])-arbitraryMSSigInputOf params net ctx = arbitraryMSSigInputWith (arbitraryKeyPair ctx) params net+  Gen (Int, Int) -> Network -> Gen (SigInput, [PrivateKey])+arbitraryMSSigInputOf params net = arbitraryMSSigInputWith arbitraryKeyPair params net  -- | Arbitrary 'SigInput' with a 'ScriptOutput' of type 'PayMulSig', whose -- keys and m of n parameters come from the given generators.@@ -277,26 +276,26 @@ -- 'RedeemScript'. A multisig redeem script has at most 7 keys, so that it -- fits the 520 bytes of a pay-to-script-hash redeem script with keys of any -- form.-arbitrarySHSigInput :: Network -> Ctx -> Gen (SigInput, [PrivateKey])-arbitrarySHSigInput net ctx = do+arbitrarySHSigInput :: Network -> Gen (SigInput, [PrivateKey])+arbitrarySHSigInput net = do   (SigInput rdm val op sh _, ks) <-     oneof-      [ wrapKey <$> arbitraryPKSigInput net ctx,-        wrapKey <$> arbitraryPKHashSigInput net ctx,-        arbitraryMSSigInputOf arbitraryP2SHMSParam net ctx+      [ wrapKey <$> arbitraryPKSigInput net,+        wrapKey <$> arbitraryPKHashSigInput net,+        arbitraryMSSigInputOf arbitraryP2SHMSParam net       ]-  let out = case either (const Nothing) addressHash160 (payToScriptAddress ctx rdm) of+  let out = case either (const Nothing) addressHash160 (payToScriptAddress rdm) of         Just h -> PayScriptHash h         Nothing -> error "Could not get Hash160 from address"   return (SigInput out val op sh $ Just rdm, ks)  -- | Arbitrary 'SigInput' with a 'ScriptOutput' of type 'PayWitnessPKHash'. -- The key is compressed, as nodes require of a SegWit version 0 input.-arbitraryWPKHSigInput :: Network -> Ctx -> Gen (SigInput, PrivateKey)-arbitraryWPKHSigInput net ctx = do-  (k, p) <- arbitraryKeyPairC ctx+arbitraryWPKHSigInput :: Network -> Gen (SigInput, PrivateKey)+arbitraryWPKHSigInput net = do+  (k, p) <- arbitraryKeyPairC   (val, op, sh) <- arbitraryInputStuff net-  let out = case addressHash160 (pubKeyAddr ctx p) of+  let out = case addressHash160 (pubKeyAddr p) of         Just h -> PayWitnessPKHash h         Nothing -> error "Could not get Hash160 from address"   return (SigInput out val op sh Nothing, k)@@ -304,15 +303,15 @@ -- | Arbitrary 'SigInput' with a 'ScriptOutput' of type -- 'PayWitnessScriptHash' and its witness script. The keys of the witness -- script are compressed, as nodes require of a SegWit version 0 input.-arbitraryWSHSigInput :: Network -> Ctx -> Gen (SigInput, [PrivateKey])-arbitraryWSHSigInput net ctx = do+arbitraryWSHSigInput :: Network -> Gen (SigInput, [PrivateKey])+arbitraryWSHSigInput net = do   (SigInput rdm val op sh _, ks) <-     oneof-      [ wrapKey <$> arbitraryAnyInputOf (arbitraryKeyPairC ctx) net ctx False,-        wrapKey <$> arbitraryAnyInputOf (arbitraryKeyPairC ctx) net ctx True,-        arbitraryMSSigInputWith (arbitraryKeyPairC ctx) arbitraryMSParam net+      [ wrapKey <$> arbitraryAnyInputOf arbitraryKeyPairC net False,+        wrapKey <$> arbitraryAnyInputOf arbitraryKeyPairC net True,+        arbitraryMSSigInputWith arbitraryKeyPairC arbitraryMSParam net       ]-  let out = case either (const Nothing) addressHash256 (payToWitnessScriptAddress ctx rdm) of+  let out = case either (const Nothing) addressHash256 (payToWitnessScriptAddress rdm) of         Just h -> PayWitnessScriptHash h         Nothing -> error "Could not get Hash256 from address"   return (SigInput out val op sh $ Just rdm, ks)@@ -320,17 +319,17 @@ -- | Arbitrary 'Tx' (empty 'TxIn'), 'SigInputs' and private keys that can be -- passed to 'signTx' or 'detSignTx' to fully sign the 'Tx'. The outputs -- spend no more than the inputs hold.-arbitrarySigningData :: Network -> Ctx -> Gen (Tx, [SigInput], [PrivateKey])-arbitrarySigningData net ctx = do+arbitrarySigningData :: Network -> Gen (Tx, [SigInput], [PrivateKey])+arbitrarySigningData net = do   v <- arbitrary   ni <- choose (1, 5)-  sigis <- vectorOf ni (arbitrarySigInput net ctx)+  sigis <- vectorOf ni (arbitrarySigInput net)   let uSigis = nubBy (\(a, _) (b, _) -> a.outpoint == b.outpoint) sigis   -- The signer refuses SIGHASH_SINGLE on a legacy input without an output   -- at its index, so every input gets an output when one asks for it   no <- choose (if any (legacySingle net . fst) uSigis then length uSigis else 1, 5)   inps <- forM uSigis $ \(s, _) -> TxIn s.outpoint BS.empty <$> arbitrary-  outs <- arbitraryOutputsWithin net ctx (sum (map ((.value) . fst) uSigis)) no+  outs <- arbitraryOutputsWithin net (sum (map ((.value) . fst) uSigis)) no   l <- arbitrary   perm <- choose (0, length inps - 1)   let tx = Tx v (permutations inps !! perm) outs [] l@@ -345,20 +344,20 @@   isSigHashSingle si.sighash && not (isSegwit si.script) && isNothing net.sigHashForkId  -- | Arbitrary outputs whose values add up to at most the amount given-arbitraryOutputsWithin :: Network -> Ctx -> Word64 -> Int -> Gen [TxOut]-arbitraryOutputsWithin net ctx total count =+arbitraryOutputsWithin :: Network -> Word64 -> Int -> Gen [TxOut]+arbitraryOutputsWithin net total count =   vectorOf count $     TxOut       <$> choose (0, total `div` fromIntegral count)-      <*> (marshal ctx <$> arbitraryScriptOutput net ctx)+      <*> (encodeSerial <$> arbitraryScriptOutput net)  -- | Arbitrary transaction with empty inputs.-arbitraryEmptyTx :: Network -> Ctx -> Gen Tx-arbitraryEmptyTx net ctx = do+arbitraryEmptyTx :: Network -> Gen Tx+arbitraryEmptyTx net = do   v <- arbitrary   no <- choose (1, 5)   ni <- choose (1, 5)-  outs <- vectorOf no (arbitraryTxOut net ctx)+  outs <- vectorOf no (arbitraryTxOut net)   ops <- vectorOf ni arbitraryOutPoint   t <- arbitrary   s <- arbitrary@@ -367,11 +366,11 @@ -- | Arbitrary partially-signed transactions. The outputs spend no more -- than the coins hold. arbitraryPartialTxs ::-  Network -> Ctx -> Gen ([Tx], [(ScriptOutput, Word64, OutPoint, Int, Int)])-arbitraryPartialTxs net ctx = do-  empty <- arbitraryEmptyTx net ctx+  Network -> Gen ([Tx], [(ScriptOutput, Word64, OutPoint, Int, Int)])+arbitraryPartialTxs net = do+  empty <- arbitraryEmptyTx net   coins <- forM (map (.outpoint) empty.inputs) $ \op -> (,) op <$> arbitraryData-  outs <- arbitraryOutputsWithin net ctx (sum [val | (_, (_, val, _, _, _, _)) <- coins]) (length empty.outputs)+  outs <- arbitraryOutputsWithin net (sum [val | (_, (_, val, _, _, _, _)) <- coins]) (length empty.outputs)   let tx = Tx empty.version empty.inputs outs [] empty.locktime   res <-     forM coins $ \(op, (so, val, rdmM, prvs, m, n)) -> do@@ -387,14 +386,14 @@       sh <- arbitraryValidSigHash net `suchThat` (not . refused)       let sigi = SigInput so val op sh rdmM       return . fromRight (error "Could not decode transaction") $-        signTx net ctx tx [sigi] [prv]+        signTx net tx [sigi] [prv]     arbitraryData = do       -- At most 7 keys, so that the script also fits a pay-to-script-hash       -- redeem script       (m, n) <- arbitraryP2SHMSParam       val <- getTestCoin <$> arbitrarySatoshi net       nPrv <- choose (m, n)-      keys <- vectorOf n (arbitraryKeyPair ctx)+      keys <- vectorOf n arbitraryKeyPair       perm <- choose (0, length keys - 1)       let pubKeys = map snd keys           prvKeys = take nPrv $ permutations (map fst keys) !! perm@@ -402,7 +401,7 @@       let h =             fromMaybe               (error "Could not get Hash160 from address")-              (either (const Nothing) addressHash160 (payToScriptAddress ctx so))+              (either (const Nothing) addressHash160 (payToScriptAddress so))       elements         [ (so, val, Nothing, prvKeys, m, n),           ( PayScriptHash h,@@ -425,9 +424,9 @@ -- transaction spends an output of it, as 'decodePsbt' requires. One PSBT -- in ten has no input. One of version 2 may have its flags, and lock -- times its inputs require.-arbitraryPsbt :: Network -> Ctx -> Gen Psbt-arbitraryPsbt net ctx = do-  drawn <- arbitraryTx net ctx+arbitraryPsbt :: Network -> Gen Psbt+arbitraryPsbt net = do+  drawn <- arbitraryTx net   inputs0 <- frequency [(9, return drawn.inputs), (1, return [])]   parents <- mapM (const (oneof [return Nothing, Just <$> spendable])) inputs0   let spend input = maybe input (\(parent, index) -> TxIn (OutPoint (txHash parent) index) input.script input.sequence)@@ -440,8 +439,8 @@   where     -- A transaction with at least one output, and the index of one of them     spendable = do-      parent <- arbitraryTx net ctx-      extra <- arbitraryTxOut net ctx+      parent <- arbitraryTx net+      extra <- arbitraryTxOut net       let outputs = if null parent.outputs then [extra] else parent.outputs       index <- choose (0, length outputs - 1)       return (Tx parent.version parent.inputs outputs parent.witness parent.locktime, fromIntegral index)@@ -483,28 +482,28 @@       return (foldr ($) m xpubs)     -- The path of an extended key has one index per level of its depth     xpubRecord = do-      xpub <- arbitraryXPubKey ctx+      xpub <- arbitraryXPubKey       path <- listToPath <$> vectorOf (fromIntegral xpub.depth) arbitrary-      (\fingerprint -> insertXpubRecord net ctx xpub (Derivation fingerprint path)) <$> arbitraryFingerprint+      (\fingerprint -> insertXpubRecord net xpub (Derivation fingerprint path)) <$> arbitraryFingerprint     inputFields parentM = do       m <- unknownFields       fields <-         sequence           [ return (maybe id (insertNonWitnessUtxo . fst) parentM),-            maybeField (insertWitnessUtxo <$> arbitraryTxOut net ctx),+            maybeField (insertWitnessUtxo <$> arbitraryTxOut net),             maybeField (insertSigHashType . fromIntegral <$> (arbitrary :: Gen Word32)),             maybeField (insertInputRedeemScript <$> arbitraryScript),             maybeField (insertInputWitnessScript <$> arbitraryScript),             maybeField (insertFinalScriptSig <$> arbitraryBS),             maybeField (insertFinalScriptWitness <$> resize 3 (listOf arbitraryBS)),-            derivations (insertInputDerivation ctx),+            derivations insertInputDerivation,             partialSignatures,-            maybeField (insertInputTapInternalKey ctx <$> point),+            maybeField (insertInputTapInternalKey <$> point),             maybeField (insertInputTapMerkleRoot <$> digest),             maybeField (insertTapKeySig <$> arbitraryTapSig),-            maybeField (insertTapScriptSig ctx <$> point <*> digest <*> arbitraryTapSig),+            maybeField (insertTapScriptSig <$> point <*> digest <*> arbitraryTapSig),             maybeField (insertTapLeafScript <$> leafScript),-            maybeField (insertInputTapDerivation ctx <$> point <*> tapDerivation)+            maybeField (insertInputTapDerivation <$> point <*> tapDerivation)           ]       return (foldr ($) m fields)     outputFields = do@@ -513,22 +512,22 @@         sequence           [ maybeField (insertOutputRedeemScript <$> arbitraryScript),             maybeField (insertOutputWitnessScript <$> arbitraryScript),-            derivations (insertOutputDerivation ctx),-            maybeField (insertOutputTapInternalKey ctx <$> point),+            derivations insertOutputDerivation,+            maybeField (insertOutputTapInternalKey <$> point),             maybeField (insertOutputTapTree <$> scriptTree),-            maybeField (insertOutputTapDerivation ctx <$> point <*> tapDerivation)+            maybeField (insertOutputTapDerivation <$> point <*> tapDerivation)           ]       return (foldr ($) m fields)     maybeField gen = oneof [return id, gen]     derivations insert = do-      records <- resize 2 (listOf ((,) <$> (snd <$> arbitraryKeyPair ctx) <*> (Derivation <$> arbitraryFingerprint <*> arbitraryDerivPath)))+      records <- resize 2 (listOf ((,) <$> (snd <$> arbitraryKeyPair) <*> (Derivation <$> arbitraryFingerprint <*> arbitraryDerivPath)))       return $ foldr (\(key, derivation) inserted -> insert key derivation . inserted) id records     -- Signatures of a sighash type the network defines, under keys that     -- need not be theirs: a PSBT is read without verifying them     partialSignatures = do-      signatures <- resize 2 (listOf ((,) <$> (snd <$> arbitraryKeyPair ctx) <*> ((\(_, _, signature) -> encodeTxSig net ctx signature) <$> arbitraryTxSignature net ctx)))-      return $ foldr (\(key, signature) inserted -> insertPartialSignature ctx key signature . inserted) id signatures-    point = (.point) . snd <$> arbitraryKeyPair ctx+      signatures <- resize 2 (listOf ((,) <$> (snd <$> arbitraryKeyPair) <*> ((\(_, _, signature) -> encodeTxSig net signature) <$> arbitraryTxSignature net)))+      return $ foldr (\(key, signature) inserted -> insertPartialSignature key signature . inserted) id signatures+    point = (.point) . snd <$> arbitraryKeyPair     digest = leafHash 0xc0 <$> arbitraryScript     -- 64 bytes, alone or with one of the six sighash bytes of BIP 341     arbitraryTapSig = do@@ -538,7 +537,7 @@     leafScript = do       internal <- point       nodes <- resize 3 (listOf digest)-      (\script -> TapLeafScript (encodeControlBlock ctx 0xc0 internal nodes) script 0xc0) <$> arbitraryScript+      (\script -> TapLeafScript (encodeControlBlock 0xc0 internal nodes) script 0xc0) <$> arbitraryScript     tapDerivation = TapDerivation <$> resize 2 (listOf digest) <*> (Derivation <$> arbitraryFingerprint <*> arbitraryDerivPath)     -- The leaves of a whole tree: one leaf alone, or two under the root     scriptTree =
src/Haskoin/Util/Arbitrary/Util.hs view
@@ -49,7 +49,6 @@ import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import qualified Data.Typeable as T import Data.Word (Word32)-import Haskoin.Crypto (Ctx) import Haskoin.Network.Constants import Haskoin.Network.Data import Haskoin.Util@@ -100,9 +99,6 @@ arbitraryNetwork = elements allNets  -- Helpers for creating Serial and JSON Identity tests--instance Show Ctx where-  show _ = "Ctx"  data ReadBox   = forall a.
+ src/Haskoin/Util/Direct.hs view
@@ -0,0 +1,601 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE ImportQualifiedPost #-}+{-# LANGUAGE MagicHash #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE UnboxedSums #-}+{-# LANGUAGE UnboxedTuples #-}++-- |+-- Module      : Haskoin.Util.Direct+-- Description : Run a serializer straight on a buffer+-- Copyright   : No rights reserved+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- The serializers of this library are written once, for any monad of the+-- 'MonadPut' and 'MonadGet' classes, so that the same code gives the bytes+-- through cereal, through binary and through anything else. The monads of+-- cereal and binary are general: they write through a+-- 'Data.ByteString.Builder.Builder', which does not know how long its output+-- will be, and read through continuations, which can stop anywhere and ask+-- for more input. That generality is paid for in every field. Writing a+-- transaction of 387 bytes through cereal allocated 11 kB and took 1.6+-- microseconds, and reading it back allocated 7 kB and took a microsecond,+-- most of it spent on closures that describe the work instead of on the+-- work. Here the same transaction is written in 0.18 microseconds and 0.5+-- kB, and read in 0.4 microseconds at @-O2@, or 0.5 at @-O1@, and 2 kB,+-- which is the transaction itself.+--+-- A program that already holds the whole value, or the whole input, needs+-- none of that. This module has three small monads for that case, and four+-- functions that run a serializer in them:+--+-- * 'encodeDirect' runs a serializer twice: once in t'Size', which only adds+--   up the lengths, and once in t'Poke', which writes the bytes one after the+--   other into a buffer of exactly that length. Nothing else is allocated.+-- * 'decodeDirect' runs a parser in t'Peek', which reads from the bytes at a+--   position that it moves forward, and gives up at the first difficulty.+-- * 'putDirect' and 'getDirect' do the same from inside a cereal serializer,+--   for the @put@ and @get@ of a 'Data.Serialize.Serialize' instance.+--+-- Each of the four gives the result that the same serializer gives through+-- cereal, in every case: the serializer is the same code, and when t'Peek'+-- gives up, for bytes that do not parse or for an operation that it does+-- not have, the parser runs again through cereal from where it started. So+-- the error of a bad input is the one cereal reports, and input that+-- arrives in pieces is read as before. Only the speed differs.+--+-- The serializer is taken as a value that works in any monad, with a+-- @forall@. To be fast, GHC must compile a copy of it for each monad here,+-- which it does when the function called and the serializer given are both+-- known where they meet: the four functions are inlined for that, and the+-- 'Data.Bytes.Serial.Serial' instances of this library carry @INLINABLE@+-- pragmas. A serializer reached through a dictionary that GHC cannot see+-- through still works, at the speed of a function call per field.+--+-- Use these functions for values that are written or read whole and often:+-- keys and records of a database, hashes of transactions. Do not use them+-- to write a value so large that a second pass over it, or a buffer of its+-- whole length, costs more than a builder, nor to read from a stream.+-- The @Haskoin@ module does not re-export this one.+module Haskoin.Util.Direct+  ( -- * Writing+    encodeDirect,+    sizeDirect,+    putDirect,+    putShortBytes,++    -- * Reading+    decodeDirect,+    getDirect,+    getShortBytes,++    -- * Monads+    Size,+    Poke,+    Peek,+  )+where++import Control.Monad.Fail qualified as Fail+import Data.Binary.Put qualified as Binary+import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.ByteString.Internal (ByteString (BS), accursedUnutterablePerformIO, unsafeCreate)+import Data.ByteString.Lazy qualified as L+import Data.ByteString.Short (ShortByteString, fromShort, toShort)+import Data.ByteString.Short qualified as Short+import Data.ByteString.Short.Internal qualified as Short (copyToPtr)+import Data.Bytes.Get (MonadGet (..), runGetS)+import Data.Bytes.Put (MonadPut (..))+import Data.Serialize.Get qualified as Cereal+import Data.Serialize.Put qualified as Cereal+import Foreign.ForeignPtr (plusForeignPtr)+import Foreign.Marshal.Utils (copyBytes)+import Foreign.Ptr (plusPtr)+import Foreign.Storable (sizeOf)+import GHC.ByteOrder (ByteOrder (..), targetByteOrder)+import GHC.Exts+import GHC.ForeignPtr (unsafeWithForeignPtr)+import GHC.IO (IO (IO))+import GHC.Word (Word16 (W16#), Word32 (W32#), Word64 (W64#), Word8 (W8#), byteSwap16, byteSwap32, byteSwap64)++-- Byte order++-- | A word as its bytes are in memory for a little-endian value.+le16 :: Word16 -> Word16+le16 = case targetByteOrder of+  LittleEndian -> id+  BigEndian -> byteSwap16+{-# INLINE le16 #-}++le32 :: Word32 -> Word32+le32 = case targetByteOrder of+  LittleEndian -> id+  BigEndian -> byteSwap32+{-# INLINE le32 #-}++le64 :: Word64 -> Word64+le64 = case targetByteOrder of+  LittleEndian -> id+  BigEndian -> byteSwap64+{-# INLINE le64 #-}++-- | A word as its bytes are in memory for a big-endian value.+be16 :: Word16 -> Word16+be16 = case targetByteOrder of+  LittleEndian -> byteSwap16+  BigEndian -> id+{-# INLINE be16 #-}++be32 :: Word32 -> Word32+be32 = case targetByteOrder of+  LittleEndian -> byteSwap32+  BigEndian -> id+{-# INLINE be32 #-}++be64 :: Word64 -> Word64+be64 = case targetByteOrder of+  LittleEndian -> byteSwap64+  BigEndian -> id+{-# INLINE be64 #-}++-- | The size of a machine word in bytes.+wordSize :: Int+wordSize = sizeOf (0 :: Word)+{-# INLINE wordSize #-}++-- Size++-- | The monad that measures: every write adds the number of its bytes to a+-- count and does nothing else. 'encodeDirect' runs a serializer in it first,+-- to learn how long a buffer to allocate.+newtype Size a = Size (Int# -> (# Int#, a #))++instance Functor Size where+  fmap f (Size g) = Size (oneShot (\n -> case g n of (# n', a #) -> (# n', f a #)))+  {-# INLINE fmap #-}++instance Applicative Size where+  pure a = Size (oneShot (\n -> (# n, a #)))+  {-# INLINE pure #-}+  Size f <*> Size g =+    Size (oneShot (\n -> case f n of (# n1, h #) -> case g n1 of (# n2, a #) -> (# n2, h a #)))+  {-# INLINE (<*>) #-}+  Size f *> Size g = Size (oneShot (\n -> case f n of (# n1, _ #) -> g n1))+  {-# INLINE (*>) #-}++instance Monad Size where+  Size g >>= f = Size (oneShot (\n -> case g n of (# n1, a #) -> case f a of Size h -> h n1))+  {-# INLINE (>>=) #-}+  (>>) = (*>)+  {-# INLINE (>>) #-}++-- | Count that many bytes.+count :: Int -> Size ()+count (I# k) = Size (oneShot (\n -> (# n +# k, () #)))+{-# INLINE count #-}++instance MonadPut Size where+  putWord8 _ = count 1+  {-# INLINE putWord8 #-}+  putByteString b = count (B.length b)+  {-# INLINE putByteString #-}+  putLazyByteString b = count (fromIntegral (L.length b))+  {-# INLINE putLazyByteString #-}+  flush = pure ()+  {-# INLINE flush #-}+  putWord16le _ = count 2+  {-# INLINE putWord16le #-}+  putWord16be _ = count 2+  {-# INLINE putWord16be #-}+  putWord16host _ = count 2+  {-# INLINE putWord16host #-}+  putWord32le _ = count 4+  {-# INLINE putWord32le #-}+  putWord32be _ = count 4+  {-# INLINE putWord32be #-}+  putWord32host _ = count 4+  {-# INLINE putWord32host #-}+  putWord64le _ = count 8+  {-# INLINE putWord64le #-}+  putWord64be _ = count 8+  {-# INLINE putWord64be #-}+  putWord64host _ = count 8+  {-# INLINE putWord64host #-}+  putWordhost _ = count wordSize+  {-# INLINE putWordhost #-}++-- Poke++-- | The monad that writes: every write stores its bytes at an address and+-- moves the address past them. It checks nothing, because 'encodeDirect'+-- runs it on a buffer that t'Size' measured for the same serializer.+newtype Poke a = Poke (Addr# -> State# RealWorld -> (# State# RealWorld, Addr#, a #))++instance Functor Poke where+  fmap f (Poke g) =+    Poke (oneShot (\p -> oneShot (\s -> case g p s of (# s1, p1, a #) -> (# s1, p1, f a #))))+  {-# INLINE fmap #-}++instance Applicative Poke where+  pure a = Poke (oneShot (\p -> oneShot (\s -> (# s, p, a #))))+  {-# INLINE pure #-}+  Poke f <*> Poke g =+    Poke . oneShot $ \p -> oneShot $ \s ->+      case f p s of+        (# s1, p1, h #) -> case g p1 s1 of+          (# s2, p2, a #) -> (# s2, p2, h a #)+  {-# INLINE (<*>) #-}+  Poke f *> Poke g = Poke (oneShot (\p -> oneShot (\s -> case f p s of (# s1, p1, _ #) -> g p1 s1)))+  {-# INLINE (*>) #-}++instance Monad Poke where+  Poke g >>= f =+    Poke (oneShot (\p -> oneShot (\s -> case g p s of (# s1, p1, a #) -> case f a of Poke h -> h p1 s1)))+  {-# INLINE (>>=) #-}+  (>>) = (*>)+  {-# INLINE (>>) #-}++-- | Write that many bytes with the given action, which gets the address to+-- write them at.+store :: Int -> (Ptr Word8 -> IO ()) -> Poke ()+store (I# k) f =+  Poke . oneShot $ \p -> oneShot $ \s ->+    case f (Ptr p) of+      IO io -> case io s of+        (# s1, _ #) -> (# s1, plusAddr# p k, () #)+{-# INLINE store #-}++-- The stores below write a whole word at an address that need not be+-- aligned, which the primitives that they call allow on every machine.++store8 :: Word8 -> Ptr Word8 -> IO ()+store8 (W8# w) (Ptr p) = IO (\s -> (# writeWord8OffAddr# p 0# w s, () #))+{-# INLINE store8 #-}++store16 :: Word16 -> Ptr Word8 -> IO ()+store16 (W16# w) (Ptr p) = IO (\s -> (# writeWord8OffAddrAsWord16# p 0# w s, () #))+{-# INLINE store16 #-}++store32 :: Word32 -> Ptr Word8 -> IO ()+store32 (W32# w) (Ptr p) = IO (\s -> (# writeWord8OffAddrAsWord32# p 0# w s, () #))+{-# INLINE store32 #-}++store64 :: Word64 -> Ptr Word8 -> IO ()+store64 (W64# w) (Ptr p) = IO (\s -> (# writeWord8OffAddrAsWord64# p 0# w s, () #))+{-# INLINE store64 #-}++storeWord :: Word -> Ptr Word8 -> IO ()+storeWord (W# w) (Ptr p) = IO (\s -> (# writeWord8OffAddrAsWord# p 0# w s, () #))+{-# INLINE storeWord #-}++storeBytes :: ByteString -> Poke ()+storeBytes (BS fp n) = store n (\p -> unsafeWithForeignPtr fp (\q -> copyBytes p q n))+{-# INLINE storeBytes #-}++instance MonadPut Poke where+  putWord8 w = store 1 (store8 w)+  {-# INLINE putWord8 #-}+  putByteString = storeBytes+  {-# INLINE putByteString #-}+  putLazyByteString = L.foldrChunks (\chunk rest -> storeBytes chunk *> rest) (pure ())+  {-# INLINE putLazyByteString #-}+  flush = pure ()+  {-# INLINE flush #-}+  putWord16le w = store 2 (store16 (le16 w))+  {-# INLINE putWord16le #-}+  putWord16be w = store 2 (store16 (be16 w))+  {-# INLINE putWord16be #-}+  putWord16host w = store 2 (store16 w)+  {-# INLINE putWord16host #-}+  putWord32le w = store 4 (store32 (le32 w))+  {-# INLINE putWord32le #-}+  putWord32be w = store 4 (store32 (be32 w))+  {-# INLINE putWord32be #-}+  putWord32host w = store 4 (store32 w)+  {-# INLINE putWord32host #-}+  putWord64le w = store 8 (store64 (le64 w))+  {-# INLINE putWord64le #-}+  putWord64be w = store 8 (store64 (be64 w))+  {-# INLINE putWord64be #-}+  putWord64host w = store 8 (store64 w)+  {-# INLINE putWord64host #-}+  putWordhost w = store wordSize (storeWord w)+  {-# INLINE putWordhost #-}++-- | The bytes that a serializer writes: the same as+-- @'Data.Bytes.Put.runPutS' p@, without the builder. The serializer runs+-- twice, to measure and then to write into one buffer of the exact length,+-- so the cost of a small value is that of its bytes, where a builder first+-- allocates a buffer of 4 kB for any value and then copies what it wrote.+--+-- Give it a serializer that GHC can see, such as+-- @'Data.Bytes.Serial.serialize' x@ for a type that is known where this is+-- called. See the notes of this module.+encodeDirect :: (forall m. (MonadPut m) => m ()) -> ByteString+encodeDirect p =+  case p of+    Size measure -> case measure 0# of+      (# n, _ #) -> unsafeCreate (I# n) $ \(Ptr start) ->+        IO $ \s -> case p of+          Poke write -> case write start s of+            (# s1, end, _ #)+              | isTrue# (minusAddr# end start ==# n) -> (# s1, () #)+              | otherwise -> errorWithoutStackTrace "encodeDirect: the serializer wrote a different length"+{-# INLINE encodeDirect #-}++-- | The number of bytes that a serializer writes, without writing them:+-- the same as the length of @'Data.Bytes.Put.runPutS' p@. Use it for the+-- size of a transaction or of a block, which is asked for more often than+-- its bytes.+sizeDirect :: (forall m. (MonadPut m) => m ()) -> Int+sizeDirect p =+  case p of+    Size measure -> case measure 0# of+      (# n, _ #) -> I# n+{-# INLINE sizeDirect #-}++-- | Write in cereal what a serializer writes, built with 'encodeDirect' and+-- added to the output in one piece. It is the same as the serializer run+-- in cereal, and is meant for the @put@ of a 'Data.Serialize.Serialize'+-- instance:+--+-- > instance Serialize TxOut where+-- >   put x = putDirect (serialize x)+putDirect :: (forall m. (MonadPut m) => m ()) -> Cereal.Put+putDirect p = Cereal.putByteString (encodeDirect p)+{-# INLINE putDirect #-}++-- | Write the bytes of a short byte string. 'MonadPut' has no method for+-- one, so a serializer would have to copy it into a 'ByteString' first, only+-- to copy that again. This function does so in a monad that it does not+-- know, and writes the bytes straight from where they are in the monads of+-- this module, of cereal and of binary, through the rewrite rules below.+-- The hashes of this library are short byte strings.+putShortBytes :: (MonadPut m) => ShortByteString -> m ()+putShortBytes s = putByteString (fromShort s)+{-# INLINE [1] putShortBytes #-}++{-# RULES+"putShortBytes/Size" putShortBytes = countShort+"putShortBytes/Poke" putShortBytes = storeShort+"putShortBytes/cereal" putShortBytes = Cereal.putShortByteString+"putShortBytes/binary" putShortBytes = Binary.putShortByteString+  #-}++countShort :: ShortByteString -> Size ()+countShort s = count (Short.length s)+{-# INLINE countShort #-}++storeShort :: ShortByteString -> Poke ()+storeShort s = store n (\p -> Short.copyToPtr s 0 p n)+  where+    n = Short.length s+{-# INLINE storeShort #-}++-- Peek++-- | What t'Peek' reads from: the bytes, and whether they are the whole input+-- or only what has arrived of it so far.+data Input = Input {-# UNPACK #-} !ByteString !Bool++-- | The monad that reads: every read checks that its bytes are there, takes+-- them at a position and moves the position past them. Its result is the+-- new position and the value, or nothing.+--+-- It has no error messages and cannot wait for more input. Where a parser+-- fails, or asks for something that depends on input that is not there+-- yet, t'Peek' gives up, and the function that ran it runs the parser again+-- through cereal, which reports the error or waits. It gives up on 'fail',+-- on a read past the end, on a negative length, on 'ensure' and on+-- 'getLazyByteString', and on 'isEmpty' and 'remaining' at the end of bytes+-- that are not the whole input.+newtype Peek a = Peek (Input -> Int# -> (# (# #) | (# Int#, a #) #))++instance Functor Peek where+  fmap f (Peek g) =+    Peek . oneShot $ \i -> oneShot $ \o ->+      case g i o of+        (# | (# o1, a #) #) -> (# | (# o1, f a #) #)+        (# (# #) | #) -> (# (# #) | #)+  {-# INLINE fmap #-}++instance Applicative Peek where+  pure a = Peek (oneShot (\_ -> oneShot (\o -> (# | (# o, a #) #))))+  {-# INLINE pure #-}+  Peek f <*> Peek g =+    Peek . oneShot $ \i -> oneShot $ \o ->+      case f i o of+        (# | (# o1, h #) #) -> case g i o1 of+          (# | (# o2, a #) #) -> (# | (# o2, h a #) #)+          (# (# #) | #) -> (# (# #) | #)+        (# (# #) | #) -> (# (# #) | #)+  {-# INLINE (<*>) #-}+  Peek f *> Peek g =+    Peek . oneShot $ \i -> oneShot $ \o ->+      case f i o of+        (# | (# o1, _ #) #) -> g i o1+        (# (# #) | #) -> (# (# #) | #)+  {-# INLINE (*>) #-}++instance Monad Peek where+  Peek g >>= f =+    Peek . oneShot $ \i -> oneShot $ \o ->+      case g i o of+        (# | (# o1, a #) #) -> case f a of Peek h -> h i o1+        (# (# #) | #) -> (# (# #) | #)+  {-# INLINE (>>=) #-}+  (>>) = (*>)+  {-# INLINE (>>) #-}++instance Fail.MonadFail Peek where+  fail _ = giveUp+  {-# INLINE fail #-}++giveUp :: Peek a+giveUp = Peek (\_ _ -> (# (# #) | #))+{-# INLINE giveUp #-}++-- | Read that many bytes with the given action, which gets their address.+-- The number must not be negative.+load :: Int -> (Ptr Word8 -> IO a) -> Peek a+load (I# k) f =+  Peek . oneShot $ \(Input (BS fp (I# len)) _) -> oneShot $ \o ->+    if isTrue# (k <=# (len -# o))+      then case accursedUnutterablePerformIO (unsafeWithForeignPtr fp (\p -> f (p `plusPtr` I# o))) of+        !a -> (# | (# o +# k, a #) #)+      else (# (# #) | #)+{-# INLINE load #-}++-- The loads below read a whole word at an address that need not be aligned.++load8 :: Ptr Word8 -> IO Word8+load8 (Ptr p) = IO (\s -> case readWord8OffAddr# p 0# s of (# s1, w #) -> (# s1, W8# w #))+{-# INLINE load8 #-}++load16 :: Ptr Word8 -> IO Word16+load16 (Ptr p) = IO (\s -> case readWord8OffAddrAsWord16# p 0# s of (# s1, w #) -> (# s1, W16# w #))+{-# INLINE load16 #-}++load32 :: Ptr Word8 -> IO Word32+load32 (Ptr p) = IO (\s -> case readWord8OffAddrAsWord32# p 0# s of (# s1, w #) -> (# s1, W32# w #))+{-# INLINE load32 #-}++load64 :: Ptr Word8 -> IO Word64+load64 (Ptr p) = IO (\s -> case readWord8OffAddrAsWord64# p 0# s of (# s1, w #) -> (# s1, W64# w #))+{-# INLINE load64 #-}++loadWord :: Ptr Word8 -> IO Word+loadWord (Ptr p) = IO (\s -> case readWord8OffAddrAsWord# p 0# s of (# s1, w #) -> (# s1, W# w #))+{-# INLINE loadWord #-}++-- | That many bytes of the input, not copied, or nothing for a negative+-- number.+slice :: Int -> Peek ByteString+slice n@(I# k) =+  Peek . oneShot $ \(Input (BS fp (I# len)) _) -> oneShot $ \o ->+    if isTrue# (k >=# 0#) && isTrue# (k <=# (len -# o))+      then (# | (# o +# k, BS (fp `plusForeignPtr` I# o) n #) #)+      else (# (# #) | #)+{-# INLINE slice #-}++instance MonadGet Peek where+  type Remaining Peek = Int+  type Bytes Peek = ByteString+  skip n = () <$ slice n+  {-# INLINE skip #-}++  -- how much of the input this returns differs from one monad to the next+  ensure _ = giveUp+  {-# INLINE ensure #-}+  lookAhead (Peek g) =+    Peek . oneShot $ \i -> oneShot $ \o ->+      case g i o of+        (# | (# _, a #) #) -> (# | (# o, a #) #)+        (# (# #) | #) -> (# (# #) | #)+  {-# INLINE lookAhead #-}+  lookAheadM (Peek g) =+    Peek . oneShot $ \i -> oneShot $ \o ->+      case g i o of+        (# | (# o1, a #) #) -> case a of+          Nothing -> (# | (# o, a #) #)+          Just _ -> (# | (# o1, a #) #)+        (# (# #) | #) -> (# (# #) | #)+  {-# INLINE lookAheadM #-}+  lookAheadE (Peek g) =+    Peek . oneShot $ \i -> oneShot $ \o ->+      case g i o of+        (# | (# o1, a #) #) -> case a of+          Left _ -> (# | (# o, a #) #)+          Right _ -> (# | (# o1, a #) #)+        (# (# #) | #) -> (# (# #) | #)+  {-# INLINE lookAheadE #-}+  getBytes = slice+  {-# INLINE getBytes #-}++  -- At the end of bytes that are only a part of the input, whether more+  -- follows is not known here.+  remaining =+    Peek $ \(Input (BS _ (I# len)) whole) o ->+      if whole then (# | (# o, I# (len -# o) #) #) else (# (# #) | #)+  {-# INLINE remaining #-}+  isEmpty =+    Peek $ \(Input (BS _ (I# len)) whole) o ->+      if isTrue# (o <# len)+        then (# | (# o, False #) #)+        else if whole then (# | (# o, True #) #) else (# (# #) | #)+  {-# INLINE isEmpty #-}+  getWord8 = load 1 load8+  {-# INLINE getWord8 #-}++  -- a copy, as in cereal, so that the value does not keep the input alive+  getByteString n = slice n >>= \b -> let !c = B.copy b in pure c+  {-# INLINE getByteString #-}+  getLazyByteString _ = giveUp+  {-# INLINE getLazyByteString #-}+  getWord16be = be16 <$> load 2 load16+  {-# INLINE getWord16be #-}+  getWord16le = le16 <$> load 2 load16+  {-# INLINE getWord16le #-}+  getWord16host = load 2 load16+  {-# INLINE getWord16host #-}+  getWord32be = be32 <$> load 4 load32+  {-# INLINE getWord32be #-}+  getWord32le = le32 <$> load 4 load32+  {-# INLINE getWord32le #-}+  getWord32host = load 4 load32+  {-# INLINE getWord32host #-}+  getWord64be = be64 <$> load 8 load64+  {-# INLINE getWord64be #-}+  getWord64le = le64 <$> load 8 load64+  {-# INLINE getWord64le #-}+  getWord64host = load 8 load64+  {-# INLINE getWord64host #-}+  getWordhost = load wordSize loadWord+  {-# INLINE getWordhost #-}++-- | Run a parser on bytes that are the whole input: the same as+-- @'runGetS' p@, without the continuations of cereal when the bytes parse.+-- Like 'runGetS', it does not mind bytes left over after the value; a+-- parser that must end with the input says so with 'isEmpty', as+-- 'Haskoin.Util.Marshal.decodeSerial' does.+--+-- When the bytes do not parse, the parser runs again through cereal to+-- report why, so a failure costs a little more than it did. Do not use this+-- where most inputs are expected to fail.+decodeDirect :: (forall m. (MonadGet m) => m a) -> ByteString -> Either String a+decodeDirect p bytes =+  case p of+    Peek peek -> case peek (Input bytes True) 0# of+      (# | (# _, a #) #) -> Right a+      (# (# #) | #) -> runGetS p bytes+{-# INLINE decodeDirect #-}++-- | Read in cereal what a parser reads, from the input that cereal has at+-- hand when that holds the whole value, and through cereal otherwise. It is+-- the same as the parser run in cereal, and is meant for the @get@ of a+-- 'Data.Serialize.Serialize' instance:+--+-- > instance Serialize TxOut where+-- >   get = getDirect deserialize+getDirect :: (forall m. (MonadGet m) => m a) -> Cereal.Get a+getDirect p = do+  bytes <- Cereal.ensure 0+  left <- Cereal.remaining+  -- cereal takes the input for whole when it knows of nothing after it+  case p of+    Peek peek -> case peek (Input bytes (left == B.length bytes)) 0# of+      (# | (# n, a #) #) -> a <$ Cereal.uncheckedSkip (I# n)+      (# (# #) | #) -> p+{-# INLINE getDirect #-}++-- | Read that many bytes as a short byte string, copied once from the+-- input. The value is built before the parser goes on, so that it does not+-- keep the input alive as an unevaluated copy would.+getShortBytes :: (MonadGet m) => Int -> m ShortByteString+getShortBytes n = getBytes n >>= \b -> let !s = toShort b in pure s+{-# INLINE getShortBytes #-}
src/Haskoin/Util/Helpers.hs view
@@ -67,7 +67,6 @@     putTwo,      -- * Test Helpers-    prepareContext,     customCerealID,     readTestFile,     readTestFileParser,@@ -108,7 +107,7 @@ import Data.Text.Lazy qualified as LT import Data.Text.Lazy.Encoding qualified as LT import Data.Word-import Foreign.Ptr (Ptr)+import Foreign.Ptr (Ptr, plusPtr) import Foreign.Storable (peekByteOff, pokeByteOff) import Test.Hspec @@ -132,33 +131,66 @@  -- Hexadecimal ----- Hex is written by looking up the two digits of each byte in a table of--- the 256 pairs. Measured on a 250-byte transaction, that is four times as--- fast as base16, and twice as fast as the hex of the builder of--- bytestring, which works a digit at a time; on a block of a megabyte, it--- is 1.5 times as fast as the builder. Inside a builder, short input is--- left to the builder's own hex, which costs as much there and writes in--- place: copying in a table-made string would allocate for each one.+-- Two ways of writing hex are used here, each where it measured fastest.+--+-- Inside a builder, the hex is the builder's own, 'lazyByteStringHex' of+-- bytestring. It looks up the two digits of each byte in a table and writes+-- them straight into the output buffer, so it allocates nothing of its own.+-- Version 1.6.4 replaced it with a loop that made a strict string first and+-- copied it in, and that was slower at every size, at @-O1@ and at @-O2@.+--+-- Outside a builder, the result is a strict string or text of a known+-- length, so the bytes are allocated once and filled by a loop over the+-- input that writes each pair of digits with 'BP.word8HexFixed', the same+-- table lookup that the builder uses. On a transaction of 250 bytes that+-- takes less than half the time of base16, which 'encodeHex' used until+-- 1.6.3, and it costs less than running a builder for a short string.+--+-- The loop of 1.6.4 kept a table of its own in a 'ByteString'. GHC found+-- where that table was once, before the loop, only at @-O2@, where its+-- liberate-case pass runs. At @-O1@, the level this package is built at+-- unless the user asks otherwise, it looked again for every byte, and+-- 'encodeHex' was slower than the base16 it had replaced. The table of+-- bytestring is a literal with a fixed address, so the loop below is as+-- fast at @-O1@ as at @-O2@, and no option of the compiler is needed to+-- get its speed.+--+-- The benchmark of this package measures every function below at both+-- levels, next to what version 1.6.0 did. The README says how to run it. --- | JSON string of the hex of bytes.+-- | JSON string of the hex of bytes, in lowercase.+--+-- This is 'hexBuilder' between two quotes. Hex has no character that JSON+-- escapes, so nothing else is needed. Use it to write a script, a+-- transaction or a block as one field of a JSON object without building the+-- text first. hexEncoding :: LB.ByteString -> Encoding hexEncoding b =   unsafeToEncoding $     char7 '"' <> hexBuilder b <> char7 '"'  -- | Hex of bytes, in lowercase, to append to other output.+--+-- This is 'lazyByteStringHex' of bytestring, which writes the digits into+-- the buffer of the builder. Version 1.6.4 used a loop of its own for chunks+-- of 256 bytes and more. On a megabyte that took 1.5 times as long at @-O2@+-- and five times as long at @-O1@, so version 2.0.0 went back. Use this+-- function when the hex goes into a response or a file. For hex that you+-- keep as a value, 'encodeHex' and 'encodeHexBytes' cost less than running+-- a builder. hexBuilder :: LB.ByteString -> Builder-hexBuilder = foldMap chunk . LB.toChunks-  where-    chunk c-      | B.length c < 256 = byteStringHex c-      | otherwise = byteString (encodeHexBytes c)+hexBuilder = lazyByteStringHex  -- | Hex of bytes, in lowercase.+--+-- The text is the digits of 'encodeHexBytes', which are ASCII. encodeHex :: ByteString -> Text encodeHex = T.decodeLatin1 . encodeHexBytes  -- | Hex of bytes, in lowercase, as the bytes of its ASCII digits.+--+-- The result is allocated once, at twice the length of the input, and+-- filled in one pass. encodeHexBytes :: ByteString -> ByteString encodeHexBytes bs =   BI.unsafeCreate (2 * n) $ \out ->@@ -167,59 +199,61 @@             | i >= n = return ()             | otherwise = do                 w <- peekByteOff inp i-                pokeDigits out (2 * i) w+                pokeHex (out `plusPtr` (2 * i)) w                 go (i + 1)        in go 0   where     n = B.length bs --- | Encode as string of human-readable hex characters.+-- | Hex of lazy bytes, in lowercase, as lazy text with a chunk for each+-- chunk of the input. encodeHexLazy :: LB.ByteString -> LT.Text encodeHexLazy = LT.fromChunks . map encodeHex . LB.toChunks  -- | Hex of bytes in reverse order, as hashes are shown, in lowercase.+--+-- The hash of a block or of a transaction is kept in the order of its bytes+-- on the wire and shown in the opposite order. Reading the bytes backwards+-- while writing the digits saves serializing the hash and reversing it,+-- which is what showing a hash cost until 1.6.3. encodeHexReversed :: ShortByteString -> Text encodeHexReversed h =   T.decodeLatin1 . BI.unsafeCreate (2 * n) $ \out ->     let go !i           | i >= n = return ()-          | otherwise = pokeDigits out (2 * i) (SBS.index h (n - 1 - i)) >> go (i + 1)+          | otherwise = pokeHex (out `plusPtr` (2 * i)) (SBS.index h (n - 1 - i)) >> go (i + 1)      in go 0   where     n = SBS.length h  -- | JSON string of the hex of bytes in reverse order, as hashes are shown.--- A hash of 32 bytes, the size of the hashes of blocks and transactions,--- is written in one step, straight from its bytes: a fifth of the time of--- serializing it, reversing it and writing its hex.+--+-- A hash of 32 bytes, the size of the hashes of blocks and transactions, is+-- written in one step of 66 bytes, straight from its bytes into the buffer+-- of the encoder. Any other length is reversed and given to 'hexEncoding'. hexEncodingReversed :: ShortByteString -> Encoding hexEncodingReversed h   | SBS.length h == 32 = unsafeToEncoding (BP.primFixed quotedHash h)   | otherwise = hexEncoding (LB.fromStrict (B.reverse (SBS.fromShort h)))   where     quotedHash = BPI.fixedPrim 66 $ \x p -> do-      pokeByteOff p 0 (0x22 :: Word8)+      pokeByteOff p 0 quote       let go !i             | i >= 32 = return ()-            | otherwise = pokeDigits p (1 + 2 * i) (SBS.index x (31 - i)) >> go (i + 1)+            | otherwise = pokeHex (p `plusPtr` (1 + 2 * i)) (SBS.index x (31 - i)) >> go (i + 1)       go 0-      pokeByteOff p 65 (0x22 :: Word8)---- | Write the two hex digits of a byte at an offset, from the table.-pokeDigits :: Ptr a -> Int -> Word8 -> IO ()-pokeDigits out at w = do-  let k = 2 * fromIntegral w-  pokeByteOff out at (BU.unsafeIndex hexDigits k)-  pokeByteOff out (at + 1) (BU.unsafeIndex hexDigits (k + 1))-{-# INLINE pokeDigits #-}+      pokeByteOff p 65 quote+    quote = 0x22 :: Word8 --- | The two lowercase hex digits of each byte, in order: 512 bytes.-hexDigits :: ByteString-hexDigits = B.pack (concat [[digit (w `shiftR` 4), digit (w .&. 15)] | w <- [0 .. 255]])-  where-    digit x = if x < 10 then 0x30 + x else 0x57 + x-{-# NOINLINE hexDigits #-}+-- | Write the two lowercase hex digits of a byte at an address. The digits+-- come from the table of bytestring, through the primitive that its builder+-- writes hex with.+pokeHex :: Ptr Word8 -> Word8 -> IO ()+pokeHex out w = BPI.runF BP.word8HexFixed w out+{-# INLINE pokeHex #-} +-- | Bytes from their hex, in lowercase or uppercase. 'Nothing' for text that+-- is not hex, or that has an odd number of digits. decodeHex :: Text -> Maybe ByteString decodeHex t =   case parseBase16 u8 of@@ -383,6 +417,7 @@ putInt32be n   | n < 0 = putWord32be (complement (fromIntegral (abs n)) + 1)   | otherwise = putWord32be (fromIntegral (abs n))+{-# INLINEABLE putInt32be #-}  getInt32be :: (MonadGet m) => m Int32 getInt32be = do@@ -390,11 +425,13 @@   if testBit n 31     then return (negate (complement (fromIntegral n) + 1))     else return (fromIntegral n)+{-# INLINEABLE getInt32be #-}  putInt64be :: (MonadPut m) => Int64 -> m () putInt64be n   | n < 0 = putWord64be (complement (fromIntegral (abs n)) + 1)   | otherwise = putWord64be (fromIntegral (abs n))+{-# INLINEABLE putInt64be #-}  getInt64be :: (MonadGet m) => m Int64 getInt64be = do@@ -402,6 +439,7 @@   if testBit n 63     then return (negate (complement (fromIntegral n) + 1))     else return (fromIntegral n)+{-# INLINEABLE getInt64be #-}  putInteger :: (MonadPut m) => Integer -> m () putInteger n@@ -417,6 +455,7 @@   where     lo = fromIntegral (minBound :: Int32)     hi = fromIntegral (maxBound :: Int32)+{-# INLINEABLE putInteger #-}  -- | Read an 'Integer' that 'putInteger' wrote. A number has one encoding, and -- any other way to write it is refused:@@ -448,6 +487,7 @@   where     fitsInt32 n =       n >= fromIntegral (minBound :: Int32) && n <= fromIntegral (maxBound :: Int32)+{-# INLINEABLE getInteger #-}  -- | The number that a string of bytes spells, least significant byte first. -- The string is split in halves and the two numbers are joined. Adding one@@ -465,6 +505,7 @@ putMaybe :: (MonadPut m) => (a -> m ()) -> Maybe a -> m () putMaybe f Nothing = putWord8 0x00 putMaybe f (Just x) = putWord8 0x01 >> f x+{-# INLINEABLE putMaybe #-}  getMaybe :: (MonadGet m) => m a -> m (Maybe a) getMaybe f =@@ -472,14 +513,17 @@     0x00 -> return Nothing     0x01 -> Just <$> f     _ -> fail "Not a Maybe"+{-# INLINEABLE getMaybe #-}  putLengthBytes :: (MonadPut m) => ByteString -> m () putLengthBytes bs = do   putWord64be (fromIntegral (B.length bs))   putByteString bs+{-# INLINEABLE putLengthBytes #-}  getLengthBytes :: (MonadGet m) => m ByteString getLengthBytes = getByteString =<< getCount+{-# INLINEABLE getLengthBytes #-}  -- | A 64-bit count that must fit an 'Int'. A larger one fails the parse -- instead of wrapping around to a negative number.@@ -489,6 +533,7 @@   when (n > fromIntegral (maxBound :: Int)) $     fail ("Count too large: " <> show n)   return (fromIntegral n)+{-# INLINEABLE getCount #-}  -- -- Fold and unfold an Integer to and from a list of its bytes@@ -522,33 +567,35 @@   unless (and (zipWith (<) keys (drop 1 keys))) $     fail "getIntMap: the keys are not in ascending order"   return (IntMap.fromDistinctAscList pairs)+{-# INLINEABLE getIntMap #-}  putIntMap :: (MonadPut m) => (Int -> m ()) -> (a -> m ()) -> IntMap a -> m () putIntMap f g = putList (putTwo f g) . IntMap.toAscList+{-# INLINEABLE putIntMap #-}  putTwo :: (MonadPut m) => (a -> m ()) -> (b -> m ()) -> (a, b) -> m () putTwo f g (x, y) = f x >> g y+{-# INLINEABLE putTwo #-}  getTwo :: (MonadGet m) => m a -> m b -> m (a, b) getTwo f g = (,) <$> f <*> g+{-# INLINEABLE getTwo #-}  putList :: (MonadPut m) => (a -> m ()) -> [a] -> m () putList f ls = do   putWord64be (fromIntegral (length ls))   mapM_ f ls+{-# INLINEABLE putList #-}  getList :: (MonadGet m) => m a -> m [a] getList f = do   l <- getCount   replicateM l f+{-# INLINEABLE getList #-}  -- -- Test Helpers ----prepareContext :: (Ctx -> SpecWith a) -> SpecWith a-prepareContext go = go =<< runIO createContext-    customCerealID :: (Eq a) => S.Get a -> S.Putter a -> a -> Bool customCerealID g p a = (S.runGet g . S.runPut . p) a == Right a
src/Haskoin/Util/Marshal.hs view
@@ -1,10 +1,27 @@ {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE ImportQualifiedPost #-} +-- |+-- Module      : Haskoin.Util.Marshal+-- Description : Encodings that depend on the network+--+-- Most types of this library are written the same way everywhere, and have+-- 'Serial', 'Data.Aeson.ToJSON' and 'Data.Aeson.FromJSON' instances. A few are+-- not: an extended key starts with version bytes that differ from one network+-- to the next, an address has a prefix, and a transaction signature may carry+-- a fork id. Those types cannot have the ordinary instances, since an instance+-- has nowhere to take the network from. They have 'Marshal' and 'MarshalJSON'+-- instances instead, whose functions take a parameter first, a @Network@+-- in every instance of this library.+--+-- Up to version 1.6 the parameter was also used to pass a secp256k1 context+-- to the types that hold a public key or a signature. The context is global+-- since 2.0.0, so those types went back to the ordinary classes, and+-- 'encodeSerial' and 'decodeSerial' stand in for 'marshal' and 'unmarshal'+-- on them. module Haskoin.Util.Marshal where  import Control.Monad-import Crypto.Secp256k1 import Data.Aeson import Data.Aeson.Encoding import Data.Aeson.Types@@ -14,6 +31,7 @@ import Data.Bytes.Get import Data.Bytes.Put import Data.Bytes.Serial+import Haskoin.Util.Direct (decodeDirect, encodeDirect)  class Marshal s a | a -> s where   marshalPut :: (MonadPut m) => s -> a -> m ()@@ -43,6 +61,46 @@   done <- isEmpty   unless done $ fail "unmarshal: bytes left over after the value"   return value++-- | Write a value of an ordinary 'Serial' type to bytes. It is the+-- counterpart of 'marshal' for the types that need nothing to be read or+-- written, such as public keys, signatures and output scripts. The bytes+-- are those of @'runPutS' . 'serialize'@.+--+-- They are written with 'encodeDirect', into one buffer of their exact+-- length, and the function is inlined where it is called so that GHC+-- compiles the serializer of the type for that. This is the cheapest way+-- to the bytes of a small value: 'runPutS', and @encode@ of cereal, first+-- allocate a buffer of 4 kB whatever the value, which costs about 200 ns+-- before the first byte is written.+encodeSerial :: (Serial a) => a -> ByteString+encodeSerial x = encodeDirect (serialize x)+{-# INLINE encodeSerial #-}++-- | Read a value of an ordinary 'Serial' type from bytes that hold the value+-- and nothing else. It is the counterpart of 'unmarshal' for the types that+-- need nothing to be read, and it keeps the same rule: bytes left over after+-- the value are an error. @'runGetS' 'deserialize'@ does not have that rule+-- and accepts a value followed by junk, so use it only to read from the start+-- of a longer stream.+--+-- The function is inlined where it is called, on purpose. A parser of this+-- library is written for any monad of the 'MonadGet' class. Called from+-- here, behind the 'Serial' dictionary of a type not yet known, it would run+-- every step through the dictionary of the monad. Inlined at a call that+-- names the type, it becomes the parser that GHC compiled for that type and+-- for the one monad used here, which is that of 'decodeDirect': it reads+-- the bytes where they are, and leaves cereal to report the error of bytes+-- that do not parse. For an output script of 34 bytes that is the+-- difference between about 900 ns and under 100 ns, which+-- 'Haskoin.Address.scriptToAddressBS' pays for every script it parses.+decodeSerial :: (Serial a) => ByteString -> Either String a+decodeSerial = decodeDirect $ do+  value <- deserialize+  done <- isEmpty+  unless done $ fail "decodeSerial: bytes left over after the value"+  return value+{-# INLINE decodeSerial #-}  class MarshalJSON s a | a -> s where   marshalValue :: s -> a -> Value
test/Haskoin/AddressSpec.hs view
@@ -41,7 +41,7 @@     }  spec :: Spec-spec = prepareContext $ \ctx -> do+spec = do   forM_ allNets $ \net -> testIdentity $ identityTests net   describe "Address properties" $ do     prop "encodes and decodes base58 bytestring" $@@ -58,12 +58,12 @@       -- its plain form, and the others have no script. Both have a test below.       forAll arbitraryNetAddress $ \(net, a) ->         not (isCashAddress a) ==>-          (scriptToAddressBS net ctx =<< maybeToEither "no script" (addressToScriptBS ctx a))+          (scriptToAddressBS net =<< maybeToEither "no script" (addressToScriptBS a))             `shouldBe` Right a     prop "an address that outputAddress gives always has a text form on that network" $       -- The output is of a kind of any network, not only of the one asked-      forAll ((,) <$> arbitraryNetwork <*> (arbitraryNetwork >>= \other -> arbitraryScriptOutput other ctx)) $ \(net, out) ->-        case outputAddress net ctx out of+      forAll ((,) <$> arbitraryNetwork <*> (arbitraryNetwork >>= \other -> arbitraryScriptOutput other)) $ \(net, out) ->+        case outputAddress net out of           Nothing -> property True           Just a -> property (isJust (addrToText net a))   describe "Address vectors" $ do@@ -76,7 +76,7 @@     it "Passes Base58Check invalid decoding vectors" $       mapM_ testBase58ChkInvalidVector base58ChkInvalidVectors     it "Passes addresses witness p2sh(pwpkh) vectors" $-      mapM_ (testCompatWitnessVector ctx) compatWitnessVectors+      mapM_ testCompatWitnessVector compatWitnessVectors   describe "Base58" $ do     it "decodes digits by their position in the alphabet" $       -- 2 is digit 1 and 1 is digit 0, so 1 × 58 + 0 = 58@@ -89,14 +89,25 @@     it "rejects a checked string shorter than a checksum" $       decodeBase58Check "1" `shouldBe` Nothing     prop "writes what the plain conversion through one big number writes" $-      -- leading zero bytes, which are written as 1, and lengths of every-      -- remainder by four, for the limbs of 32 bits+      -- leading zero bytes, which are written as 1, and lengths either+      -- side of the eight bytes of a machine word       forAll ((<>) <$> (B.pack <$> listOf (pure 0)) <*> arbitraryBS) $ \bs ->         encodeBase58 bs `shouldBe` slowBase58 bs-    it "writes the numbers around the edges of a limb and of 58^5" $-      forM_ [0, 1, 57, 58, 656356767, 656356768, 4294967295, 4294967296, 2 ^ (200 :: Int) - 1] $ \n -> do+    prop "writes long input as the plain conversion does" $+      -- longer than anything in Bitcoin, where the digits come from many+      -- divisions by 58^10+      forAll (choose (100, 1500) >>= arbitraryBSn) $ \bs ->+        encodeBase58 bs `shouldBe` slowBase58 bs+    it "writes the numbers around the edges of a machine word and of the powers of 58^10" $ do+      let edges = [58, 58 ^ (5 :: Int), 2 ^ (32 :: Int), 58 ^ (10 :: Int), 2 ^ (64 :: Int), 58 ^ (20 :: Int), 2 ^ (200 :: Int)]+      forM_ ([0, 1, 57] <> concat [[n - 1, n, n + 1] | n <- edges]) $ \n -> do         let bs = integerToBS n         assertEqual (show n) (slowBase58 bs) (encodeBase58 bs)+    it "writes digits that are all zero after the first as the plain conversion does" $+      -- multiples of 58^10 and of 58^20: every group of ten digits but the first is zero+      forM_ [k * 58 ^ e | k <- [1, 57, 58, 12345], e <- [10, 20, 30 :: Int]] $ \n -> do+        let bs = integerToBS n+        assertEqual (show n) (slowBase58 bs) (encodeBase58 bs)   describe "Smart constructors" $ do     it "witnessAddress builds a P2WPKH address from version 0 and 20 bytes" $       witnessAddress 0 hash20Bytes `shouldBe` Just (WitnessPubKeyAddress hash20)@@ -280,21 +291,21 @@         `shouldReturn` Just Nothing   describe "Addresses from public keys" $ do     it "pubKeyAddr hashes a compressed key" $-      addrToText btc (pubKeyAddr ctx (compressedKey ctx))+      addrToText btc (pubKeyAddr compressedKey)         `shouldBe` Just "1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH"     it "pubKeyAddr hashes an uncompressed key in its uncompressed form" $-      addrToText btc (pubKeyAddr ctx (uncompressedKey ctx))+      addrToText btc (pubKeyAddr uncompressedKey)         `shouldBe` Just "1EHNa6Q4Jz2uvNExL497mE43ikXhwF6kZm"     it "pubKeyWitnessAddr gives the P2WPKH address of a compressed key" $-      (addrToText btc =<< pubKeyWitnessAddr ctx (compressedKey ctx))+      (addrToText btc =<< pubKeyWitnessAddr compressedKey)         `shouldBe` Just "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"     it "pubKeyWitnessAddr refuses an uncompressed key" $-      pubKeyWitnessAddr ctx (uncompressedKey ctx) `shouldBe` Nothing+      pubKeyWitnessAddr uncompressedKey `shouldBe` Nothing     it "pubKeyCompatWitnessAddr gives the P2SH-P2WPKH address of a compressed key" $-      (addrToText btc =<< pubKeyCompatWitnessAddr ctx (compressedKey ctx))+      (addrToText btc =<< pubKeyCompatWitnessAddr compressedKey)         `shouldBe` Just "3JvL6Ymt8MVWiCNHC7oWU6nLeHNJKLZGLN"     it "pubKeyCompatWitnessAddr refuses an uncompressed key" $-      pubKeyCompatWitnessAddr ctx (uncompressedKey ctx) `shouldBe` Nothing+      pubKeyCompatWitnessAddr uncompressedKey `shouldBe` Nothing     it "p2pkhAddr, p2shAddr, p2wpkhAddr and p2wshAddr wrap a hash" $ do       addrToText btc (p2pkhAddr hash20) `shouldBe` Just "1BpEi6DfDAUFd7GtittLSdBeYJvcoaVggu"       addrToText btc (p2shAddr hash20) `shouldBe` Just "3CWFddi6m4ndiGyKqzYvsFYagqDLPVMTzC"@@ -302,13 +313,13 @@       addrToText btc (p2wshAddr hash32) `shouldBe` Just "bc1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qccfmv3"   describe "Addresses from scripts" $ do     it "payToScriptAddress hashes the output script with HASH160" $-      (addrToText btc <$> payToScriptAddress ctx (multisig ctx))+      (addrToText btc <$> payToScriptAddress multisig)         `shouldBe` Right (Just "38fEX6RbBBMmpu3nbbuULku1xyrrzqqqnE")     it "payToWitnessScriptAddress hashes the output script with SHA256" $-      (addrToText btc <$> payToWitnessScriptAddress ctx (multisig ctx))+      (addrToText btc <$> payToWitnessScriptAddress multisig)         `shouldBe` Right (Just "bc1qd6e6c86xp56gw8pty8suuqhscpttea2c5m2fggzjkxzk5nl9faks5pehxu")     it "payToNestedScriptAddress wraps the P2WSH script in P2SH" $-      (addrToText btc <$> payToNestedScriptAddress ctx (multisig ctx))+      (addrToText btc <$> payToNestedScriptAddress multisig)         `shouldBe` Right (Just "3JSuZ22mPR2aD5bf77KsGi36V5ar3p87LX")     it "p2shP2wpkhAddr is the P2SH address of the witness program of a key hash" $       -- The P2SH-P2WPKH example of BIP 143: redeem script 0014 79091972…,@@ -320,72 +331,72 @@     -- base58) from the script bytes, not with this library.     it "gives the P2SH address of a 1-of-15 multisig of compressed keys" $       -- 3 + 15 × 34 = 513 bytes, which fits the 520 bytes of a push-      (addrToText btc <$> payToScriptAddress ctx (multisigOf ctx 15))+      (addrToText btc <$> payToScriptAddress (multisigOf 15))         `shouldBe` Right (Just "32vPTRtH3XPKgBxBtEoiQdGzVEZydYKduQ")     it "has no P2SH address for a 1-of-16 multisig of compressed keys" $       -- 3 + 16 × 34 = 547 bytes: no input can push that redeem script-      payToScriptAddress ctx (multisigOf ctx 16)+      payToScriptAddress (multisigOf 16)         `shouldBe` Left "The redeem script is 547 bytes long, and a pay-to-script-hash redeem script can have at most 520"     it "has no P2SH address for a 1-of-20 multisig of compressed keys" $       -- 3 + 20 × 34 + 1 = 684 bytes: the count 20 takes a one-byte push-      payToScriptAddress ctx (multisigOf ctx 20)+      payToScriptAddress (multisigOf 20)         `shouldBe` Left "The redeem script is 684 bytes long, and a pay-to-script-hash redeem script can have at most 520"     it "gives the P2SH address of a redeem script of exactly 520 bytes" $       -- OP_RETURN, the three bytes of OP_PUSHDATA2 and its length, 516 bytes-      (addrToText btc <$> payToScriptAddress ctx (DataCarrier [B.replicate 516 0xab]))+      (addrToText btc <$> payToScriptAddress (DataCarrier [B.replicate 516 0xab]))         `shouldBe` Right (Just "35xAkh7KgcziTpgBWPAoXGzGDgLujKCnLL")     it "has no P2SH address for a redeem script of 521 bytes" $-      payToScriptAddress ctx (DataCarrier [B.replicate 517 0xab])+      payToScriptAddress (DataCarrier [B.replicate 517 0xab])         `shouldBe` Left "The redeem script is 521 bytes long, and a pay-to-script-hash redeem script can have at most 520"     it "gives the P2WSH and the P2SH-P2WSH address of a 1-of-20 multisig" $ do-      (addrToText btc <$> payToWitnessScriptAddress ctx (multisigOf ctx 20))+      (addrToText btc <$> payToWitnessScriptAddress (multisigOf 20))         `shouldBe` Right (Just "bc1q5yfkferfc5w4t3chd0ghw6ume447rey75v8df4z6sjrhnegv50ysg5v7a5")-      (addrToText btc <$> payToNestedScriptAddress ctx (multisigOf ctx 20))+      (addrToText btc <$> payToNestedScriptAddress (multisigOf 20))         `shouldBe` Right (Just "3KHeFzKKQySyJSVTdqkkxxaMGRUCNdPfay")     it "gives the P2WSH and the P2SH-P2WSH address of a witness script of exactly 10,000 bytes" $ do       -- OP_RETURN, the three bytes of OP_PUSHDATA2 and its length, 9996 bytes-      (addrToText btc <$> payToWitnessScriptAddress ctx (DataCarrier [B.replicate 9996 0xab]))+      (addrToText btc <$> payToWitnessScriptAddress (DataCarrier [B.replicate 9996 0xab]))         `shouldBe` Right (Just "bc1q5w9futq5wnymeh5wfrak2388u0cmup9nhkwxsq56rraaxvfy22pqrzp44n")-      (addrToText btc <$> payToNestedScriptAddress ctx (DataCarrier [B.replicate 9996 0xab]))+      (addrToText btc <$> payToNestedScriptAddress (DataCarrier [B.replicate 9996 0xab]))         `shouldBe` Right (Just "34v1ZTik6F9PmGBTcXnmbHF1NfTjufPgvv")     it "has no P2WSH and no P2SH-P2WSH address for a witness script of 10,001 bytes" $ do-      payToWitnessScriptAddress ctx (DataCarrier [B.replicate 9997 0xab])+      payToWitnessScriptAddress (DataCarrier [B.replicate 9997 0xab])         `shouldBe` Left "The witness script is 10001 bytes long, and a pay-to-witness-script-hash witness script can have at most 10000"-      payToNestedScriptAddress ctx (DataCarrier [B.replicate 9997 0xab])+      payToNestedScriptAddress (DataCarrier [B.replicate 9997 0xab])         `shouldBe` Left "The witness script is 10001 bytes long, and a pay-to-witness-script-hash witness script can have at most 10000"     it "gives an error value, not an exception, for a multisig that no script can express" $ do-      payToScriptAddress ctx (PayMulSig [compressedKey ctx, secondKey ctx] 3)+      payToScriptAddress (PayMulSig [compressedKey, secondKey] 3)         `shouldBe` Left "encodeOutput: multisig requires more signatures than it has keys"-      payToScriptAddress ctx (PayMulSig [compressedKey ctx] 0)+      payToScriptAddress (PayMulSig [compressedKey] 0)         `shouldBe` Left "encodeOutput: multisig must require at least one signature"-      payToWitnessScriptAddress ctx (PayMulSig [] 1)+      payToWitnessScriptAddress (PayMulSig [] 1)         `shouldBe` Left "encodeOutput: multisig requires more signatures than it has keys"-      payToNestedScriptAddress ctx (PayMulSig (replicate 21 (compressedKey ctx)) 1)+      payToNestedScriptAddress (PayMulSig (replicate 21 compressedKey) 1)         `shouldBe` Left "encodeOutput: multisig has more than 20 keys"   describe "addressToOutput, addressToScript and addressToScriptBS" $ do     it "builds the locking script of every address kind" $       forM_ scriptTable $ \(_, a, hex) ->-        assertEqual (T.unpack hex) (Just hex) (encodeHex <$> addressToScriptBS ctx a)+        assertEqual (T.unpack hex) (Just hex) (encodeHex <$> addressToScriptBS a)     it "pays a token-aware address and its plain form with the same script" $ do       let script = Just "76a91476a04053bda0a88bda5177b86a15c3b29f55987388ac"-      (encodeHex <$> (addressToScriptBS ctx =<< textToAddr bch "bitcoincash:zpm2qsznhks23z7629mms6s4cwef74vcwvrqekrq9w"))+      (encodeHex <$> (addressToScriptBS =<< textToAddr bch "bitcoincash:zpm2qsznhks23z7629mms6s4cwef74vcwvrqekrq9w"))         `shouldBe` script-      (encodeHex <$> (addressToScriptBS ctx =<< textToAddr bch "bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a"))+      (encodeHex <$> (addressToScriptBS =<< textToAddr bch "bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a"))         `shouldBe` script     it "the script of a token-aware address has the plain address, which is another value" $ do       -- An index keyed by address must look a token-aware address up by its       -- script, or by its plain form-      (scriptToAddressBS bch ctx =<< maybeToEither "no script" (addressToScriptBS ctx tokenP2pkh))+      (scriptToAddressBS bch =<< maybeToEither "no script" (addressToScriptBS tokenP2pkh))         `shouldBe` Right p2pkh       tokenP2pkh `shouldNotBe` p2pkh     it "pays a token-aware P2PKH address with the plain P2PKH script" $-      (encodeHex <$> addressToScriptBS ctx tokenP2pkh)+      (encodeHex <$> addressToScriptBS tokenP2pkh)         `shouldBe` Just "76a91476a04053bda0a88bda5177b86a15c3b29f55987388ac"     it "pays a token-aware P2SH address with the plain P2SH script" $-      (encodeHex <$> addressToScriptBS ctx tokenP2sh)+      (encodeHex <$> addressToScriptBS tokenP2sh)         `shouldBe` Just "a91476a04053bda0a88bda5177b86a15c3b29f55987387"     it "pays a token-aware P2SH32 address with the plain P2SH32 script" $-      (encodeHex <$> addressToScriptBS ctx tokenP2sh32)+      (encodeHex <$> addressToScriptBS tokenP2sh32)         `shouldBe` Just "aa201863143c14c5166804bd19203356da136c985678cd4d27a1b8c632960490326287"     it "has no script for a CashAddr type with no known script" $ do       addressToOutput cash15 `shouldBe` Nothing@@ -397,14 +408,14 @@       addressToOutput p2tr `shouldBe` Just (PayWitness 1 hash32Bytes)       addressToOutput tokenP2sh32 `shouldBe` Just (PayScript32Hash hash32)     it "addressToScript gives the script AST" $-      ((.ops) <$> addressToScript ctx p2sh)+      ((.ops) <$> addressToScript p2sh)         `shouldBe` Just [OP_HASH160, OP_PUSHDATA hash20Bytes OPCODE, OP_EQUAL]   describe "outputAddress, scriptToAddress and scriptToAddressBS" $ do     prop "reads the standard kinds by their bytes as the parser reads them" $       -- outputs of every kind, of any network, read on any network-      forAll ((,) <$> arbitraryNetwork <*> (arbitraryNetwork >>= \other -> arbitraryScriptOutput other ctx)) $ \(net, out) ->-        let bytes = marshal ctx out-         in scriptToAddressBS net ctx bytes `shouldBe` parsed ctx net bytes+      forAll ((,) <$> arbitraryNetwork <*> (arbitraryNetwork >>= \other -> arbitraryScriptOutput other)) $ \(net, out) ->+        let bytes = encodeSerial out+         in scriptToAddressBS net bytes `shouldBe` parsed net bytes     prop "reads bytes that are nearly of a standard kind as the parser reads them" $       -- a standard script with one byte changed, or one too many or too few       forAll ((,,) <$> arbitraryNetwork <*> elements standardShapes <*> arbitrary) $ \(net, hex, (i, w, cut)) -> do@@ -415,69 +426,69 @@               0 -> changed               1 -> changed <> "\x00"               _ -> B.take (B.length changed - 1) changed-        scriptToAddressBS net ctx bytes `shouldBe` parsed ctx net bytes+        scriptToAddressBS net bytes `shouldBe` parsed net bytes     it "recovers the address of every standard locking script on a network that has its kind" $       forM_ scriptTable $ \(net, a, hex) ->-        assertEqual (T.unpack hex) (Right a) (scriptToAddressBS net ctx (fromJust (decodeHex hex)))+        assertEqual (T.unpack hex) (Right a) (scriptToAddressBS net (fromJust (decodeHex hex)))     it "scriptToAddress works on the script AST" $-      (scriptToAddress btc ctx =<< runGetS deserialize (fromJust (decodeHex "76a91476a04053bda0a88bda5177b86a15c3b29f55987388ac")))+      (scriptToAddress btc =<< runGetS deserialize (fromJust (decodeHex "76a91476a04053bda0a88bda5177b86a15c3b29f55987388ac")))         `shouldBe` Right p2pkh     it "has no address for a pay-to-public-key script" $-      scriptToAddressBS btc ctx (fromJust (decodeHex p2pkScript))+      scriptToAddressBS btc (fromJust (decodeHex p2pkScript))         `shouldBe` Left "Could not decode address"     it "has no address for a bare multisig script" $-      scriptToAddressBS btc ctx (fromJust (decodeHex multisigScript))+      scriptToAddressBS btc (fromJust (decodeHex multisigScript))         `shouldBe` Left "Could not decode address"     it "has no address for a data carrier script" $-      scriptToAddressBS btc ctx (fromJust (decodeHex "6a04deadbeef"))+      scriptToAddressBS btc (fromJust (decodeHex "6a04deadbeef"))         `shouldBe` Left "Could not decode address"     it "fails on a script that is not standard" $-      scriptToAddressBS btc ctx (fromJust (decodeHex "51")) `shouldSatisfy` isLeft+      scriptToAddressBS btc (fromJust (decodeHex "51")) `shouldSatisfy` isLeft     it "outputAddress has no address for a pay-to-public-key output" $-      outputAddress btc ctx (PayPK (compressedKey ctx)) `shouldBe` Nothing+      outputAddress btc (PayPK compressedKey) `shouldBe` Nothing     it "a script of the 256-bit script hash shape has no address on Bitcoin" $ do       -- Output 0 of mainnet transaction a4bfa8ab…bc31b, in block 211997.       -- Bitcoin Core reports it as non-standard, with no address.       let puzzle = fromJust (decodeHex "aa206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d619000000000087")       forM_ [btc, btcTest, btcTest4, btcRegTest] $ \net ->-        assertEqual net.name (Left "Could not decode address") (scriptToAddressBS net ctx puzzle)+        assertEqual net.name (Left "Could not decode address") (scriptToAddressBS net puzzle)       -- On Bitcoin Cash the same bytes are pay-to-script-hash with a 32-byte hash-      (addrToText bch =<< eitherToMaybe (scriptToAddressBS bch ctx puzzle))+      (addrToText bch =<< eitherToMaybe (scriptToAddressBS bch puzzle))         `shouldBe` Just "bitcoincash:pdh79rq2kmcmxukp563ydtnr7a8ex85rvhs45zyudrtpjqqqqqqqqgss5hn0j"     it "a witness program has no address on Bitcoin Cash" $       forM_ [bch, bchTest, bchTest4, bchRegTest] $ \net -> do         -- version 0 with 20 bytes, version 0 with 32 bytes, and Taproot         assertEqual net.name (Left "Could not decode address") $-          scriptToAddressBS net ctx (fromJust (decodeHex "001476a04053bda0a88bda5177b86a15c3b29f559873"))+          scriptToAddressBS net (fromJust (decodeHex "001476a04053bda0a88bda5177b86a15c3b29f559873"))         assertEqual net.name (Left "Could not decode address") $-          scriptToAddressBS net ctx (fromJust (decodeHex "00201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262"))+          scriptToAddressBS net (fromJust (decodeHex "00201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262"))         assertEqual net.name (Left "Could not decode address") $-          scriptToAddressBS net ctx (fromJust (decodeHex "51201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262"))+          scriptToAddressBS net (fromJust (decodeHex "51201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262"))     it "outputAddress gives an output kind an address only where the network has that kind" $ do-      outputAddress btc ctx (PayScript32Hash hash32) `shouldBe` Nothing-      outputAddress bch ctx (PayScript32Hash hash32) `shouldBe` Just p2sh32-      outputAddress bch ctx (PayWitnessPKHash hash20) `shouldBe` Nothing-      outputAddress bch ctx (PayWitnessScriptHash hash32) `shouldBe` Nothing-      outputAddress bch ctx (PayWitness 1 hash32Bytes) `shouldBe` Nothing-      outputAddress btc ctx (PayWitnessPKHash hash20) `shouldBe` Just p2wpkh-      outputAddress btc ctx (PayWitness 1 hash32Bytes) `shouldBe` Just p2tr+      outputAddress btc (PayScript32Hash hash32) `shouldBe` Nothing+      outputAddress bch (PayScript32Hash hash32) `shouldBe` Just p2sh32+      outputAddress bch (PayWitnessPKHash hash20) `shouldBe` Nothing+      outputAddress bch (PayWitnessScriptHash hash32) `shouldBe` Nothing+      outputAddress bch (PayWitness 1 hash32Bytes) `shouldBe` Nothing+      outputAddress btc (PayWitnessPKHash hash20) `shouldBe` Just p2wpkh+      outputAddress btc (PayWitness 1 hash32Bytes) `shouldBe` Just p2tr     it "the address of the mainnet 256-bit hash lock script is not written as JSON, because it has none" $       -- This is the value an indexer encodes for that output-      marshalValue btc <$> eitherToMaybe (scriptToAddressBS btc ctx (fromJust (decodeHex "aa206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d619000000000087")))+      marshalValue btc <$> eitherToMaybe (scriptToAddressBS btc (fromJust (decodeHex "aa206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d619000000000087")))         `shouldBe` Nothing   describe "inputAddress" $ do     it "gives the P2PKH address of the key in a public key hash input" $-      (addrToText btc =<< inputAddress ctx (RegularInput (SpendPKHash TxSignatureEmpty (compressedKey ctx))))+      (addrToText btc =<< inputAddress (RegularInput (SpendPKHash TxSignatureEmpty compressedKey)))         `shouldBe` Just "1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH"     it "gives the P2SH address of the redeem script in a script hash input" $-      (addrToText btc =<< inputAddress ctx (ScriptHashInput (SpendMulSig [TxSignatureEmpty]) (multisig ctx)))+      (addrToText btc =<< inputAddress (ScriptHashInput (SpendMulSig [TxSignatureEmpty]) multisig))         `shouldBe` Just "38fEX6RbBBMmpu3nbbuULku1xyrrzqqqnE"     it "gives the hash of the redeem script bytes of a decoded P2SH input" $ do       -- OP_0, an empty signature, and the push of the 37-byte redeem script       -- 51 21 <key of private key 1> 51 ae. Its HASH160 is       -- 83eebb7d79aa1d388e3b0ac65b98ac580c4da01a (Python, hashlib).       let script = fromJust (decodeHex "00002551210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179851ae")-      (addrToText btc =<< inputAddress ctx =<< eitherToMaybe (decodeInput btc ctx =<< runGetS deserialize script))+      (addrToText btc =<< inputAddress =<< eitherToMaybe (decodeInput btc =<< runGetS deserialize script))         `shouldBe` Just "3DicS6C8JZm59RsrgXr56iVHzYdQngiehV"     it "gives no address for a P2SH input whose redeem script pushes its key with OP_PUSHDATA1" $ do       -- The redeem script 51 4c 21 <key> 51 ae hashes to@@ -485,20 +496,20 @@       -- 3BUbubs2pJzko1Xg5KBVDpoRa7V3kRAsVP. Written back in the form of this       -- library it would hash to 3DicS6C8…, an address that held no coin.       let script = fromJust (decodeHex "000026514c210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179851ae")-      (inputAddress ctx =<< eitherToMaybe (decodeInput btc ctx =<< runGetS deserialize script))+      (inputAddress =<< eitherToMaybe (decodeInput btc =<< runGetS deserialize script))         `shouldBe` Nothing     it "has no address for a redeem script that is too long to be pushed" $-      inputAddress ctx (ScriptHashInput (SpendMulSig [TxSignatureEmpty]) (multisigOf ctx 16))+      inputAddress (ScriptHashInput (SpendMulSig [TxSignatureEmpty]) (multisigOf 16))         `shouldBe` Nothing     it "gives the P2SH address of the wrapped program in a nested witness input" $       -- The P2SH-P2WPKH example of BIP 143: redeem script 0014 79091972…,       -- script hash 4733f37cf4db86fbc2efed2500b4f4e49f312023.-      (addrToText btc =<< inputAddress ctx (NestedWitnessInput (PayWitnessPKHash "79091972186c449eb1ded22b78e40d009bdf0089")))+      (addrToText btc =<< inputAddress (NestedWitnessInput (PayWitnessPKHash "79091972186c449eb1ded22b78e40d009bdf0089")))         `shouldBe` Just "38BW8nqpHSWpkf5sXrQd2xYwvnPJwP59ic"     it "has no address for a pay-to-public-key input" $-      inputAddress ctx (RegularInput (SpendPK TxSignatureEmpty)) `shouldBe` Nothing+      inputAddress (RegularInput (SpendPK TxSignatureEmpty)) `shouldBe` Nothing     it "has no address for a bare multisig input" $-      inputAddress ctx (RegularInput (SpendMulSig [TxSignatureEmpty])) `shouldBe` Nothing+      inputAddress (RegularInput (SpendMulSig [TxSignatureEmpty])) `shouldBe` Nothing   describe "Binary serialization" $ do     it "writes a P2PKH address as a type byte and the hash" $       encodeHex (runPutS (serialize p2pkh))@@ -685,27 +696,27 @@ longestCashAddr = "bitcoincash:quqqzqsrqszsvpcgpy9qkrqdpc83qygjzv2p29shrqv35xcur50p7gppyg3jgffxyu5zj23t9skjutesxyerxdp4xcmnswf68v7r603lr3frdfp5"  -- | A 1-of-n multisig of the compressed public key of private key 1.-multisigOf :: Ctx -> Int -> ScriptOutput-multisigOf ctx n = PayMulSig (replicate n (compressedKey ctx)) 1+multisigOf :: Int -> ScriptOutput+multisigOf n = PayMulSig (replicate n compressedKey) 1  -- | Public key of private key 1, in both forms.-compressedKey, uncompressedKey :: Ctx -> PublicKey-compressedKey ctx =-  derivePublicKey ctx . fromJust $+compressedKey, uncompressedKey :: PublicKey+compressedKey =+  derivePublicKey . fromJust $     fromWif btc "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn"-uncompressedKey ctx =-  derivePublicKey ctx . fromJust $+uncompressedKey =+  derivePublicKey . fromJust $     fromWif btc "5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAnchuDf"  -- | Public key of private key 2.-secondKey :: Ctx -> PublicKey-secondKey ctx =-  either error id . unmarshal ctx . fromJust $+secondKey :: PublicKey+secondKey =+  either error id . decodeSerial . fromJust $     decodeHex "02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"  -- | 1-of-2 multisig of the keys of private keys 1 and 2.-multisig :: Ctx -> ScriptOutput-multisig ctx = PayMulSig [compressedKey ctx, secondKey ctx] 1+multisig :: ScriptOutput+multisig = PayMulSig [compressedKey, secondKey] 1  multisigScript :: Text multisigScript =@@ -847,12 +858,12 @@     ("3vQB7B6MrGQZaxCuFg4oh\00IOl", Nothing)   ] -testCompatWitnessVector :: Ctx -> (Network, Text, Text) -> Assertion-testCompatWitnessVector ctx (net, seckey, addr) = do+testCompatWitnessVector :: (Network, Text, Text) -> Assertion+testCompatWitnessVector (net, seckey, addr) = do   let seckeyM = fromWif net seckey   assertBool "decode seckey" (isJust seckeyM)-  let pubkey = derivePublicKey ctx (fromJust seckeyM)-  let addrM = addrToText btcTest =<< pubKeyCompatWitnessAddr ctx pubkey+  let pubkey = derivePublicKey (fromJust seckeyM)+  let addrM = addrToText btcTest =<< pubKeyCompatWitnessAddr pubkey   assertBool "address can be encoded" (isJust addrM)   assertEqual "witness address matches" addr (fromJust addrM) @@ -878,8 +889,8 @@  -- | The address of a script as the parser reads it, which is what -- 'scriptToAddressBS' did for every script until haskoin-core 1.6.2.-parsed :: Ctx -> Network -> ByteString -> Either String Address-parsed ctx net bytes = maybeToEither "Could not decode address" . outputAddress net ctx =<< unmarshal ctx bytes+parsed :: Network -> ByteString -> Either String Address+parsed net bytes = maybeToEither "Could not decode address" . outputAddress net =<< decodeSerial bytes  -- | The four kinds of script that 'scriptToAddressBS' reads by their bytes. standardShapes :: [Text]
test/Haskoin/BlockSpec.hs view
@@ -39,11 +39,11 @@ import Test.QuickCheck import Text.Printf (printf) -identityTests :: Ctx -> IdentityTests-identityTests ctx =+identityTests :: IdentityTests+identityTests =   def     { readTests =-        [ ReadBox (flip arbitraryBlock ctx =<< arbitraryNetwork),+        [ ReadBox (arbitraryBlock =<< arbitraryNetwork),           ReadBox arbitraryBlockHash,           ReadBox arbitraryBlockHeader,           ReadBox arbitraryGetBlocks,@@ -54,12 +54,12 @@           ReadBox arbitraryHeaderMemory         ],       jsonTests =-        [ JsonBox (flip arbitraryBlock ctx =<< arbitraryNetwork),+        [ JsonBox (arbitraryBlock =<< arbitraryNetwork),           JsonBox arbitraryBlockHash,           JsonBox arbitraryBlockHeader         ],       serialTests =-        [ SerialBox (flip arbitraryBlock ctx =<< arbitraryNetwork),+        [ SerialBox (arbitraryBlock =<< arbitraryNetwork),           SerialBox arbitraryBlockHash,           SerialBox arbitraryBlockHeader,           SerialBox arbitraryGetBlocks,@@ -224,8 +224,8 @@ displayTxHash = fromJust . hexToTxHash  spec :: Spec-spec = prepareContext $ \ctx -> do-  testIdentity $ identityTests ctx+spec = do+  testIdentity $ identityTests   blockHashSpec   blockHeaderSpec   compactSpec
test/Haskoin/Crypto/Keys/ExtendedSpec.hs view
@@ -38,11 +38,11 @@ import Test.QuickCheck hiding ((.&.)) import Text.Read (readMaybe) -identityTests :: Ctx -> IdentityTests-identityTests ctx =+identityTests :: IdentityTests+identityTests =   def     { readTests =-        [ ReadBox (arbitraryXPubKey ctx),+        [ ReadBox arbitraryXPubKey,           ReadBox arbitraryDerivPath,           ReadBox arbitraryHardPath,           ReadBox arbitrarySoftPath,@@ -58,7 +58,7 @@       marshalJsonTests =         [ MarshalJsonBox $ (,) <$> arbitraryNetwork <*> arbitraryXPrvKey,           MarshalJsonBox $-            (,) <$> ((,ctx) <$> arbitraryNetwork) <*> arbitraryXPubKey ctx+            (,) <$> arbitraryNetwork <*> arbitraryXPubKey         ],       serialTests =         [ SerialBox arbitraryDerivPath,@@ -68,13 +68,13 @@       marshalTests =         [ MarshalBox $ (,) <$> arbitraryNetwork <*> arbitraryXPrvKey,           MarshalBox $-            (,) <$> ((,ctx) <$> arbitraryNetwork) <*> arbitraryXPubKey ctx+            (,) <$> arbitraryNetwork <*> arbitraryXPubKey         ]     }  spec :: Spec-spec = prepareContext $ \ctx -> do-  testIdentity $ identityTests ctx+spec = do+  testIdentity $ identityTests   describe "Custom identity tests" $ do     prop "encodes and decodes extended private key" $       forAll arbitraryNetwork $ \net ->@@ -82,66 +82,66 @@           customCerealID (marshalGet net) (marshalPut net)     prop "encodes and decodes extended public key" $       forAll arbitraryNetwork $ \net ->-        forAll (arbitraryXPubKey ctx) $-          customCerealID (marshalGet (net, ctx)) (marshalPut (net, ctx))-  describe "bip32 subkey derivation vector 1" $ vectorSpec ctx m1 vector1-  describe "bip32 subkey derivation vector 2" $ vectorSpec ctx m2 vector2-  describe "bip32 subkey derivation vector 3" $ vectorSpec ctx m3 vector3+        forAll arbitraryXPubKey $+          customCerealID (marshalGet net) (marshalPut net)+  describe "bip32 subkey derivation vector 1" $ vectorSpec m1 vector1+  describe "bip32 subkey derivation vector 2" $ vectorSpec m2 vector2+  describe "bip32 subkey derivation vector 3" $ vectorSpec m3 vector3   describe "bip32 test vector 4: private keys with leading zeros" $     forM_ vector4 $ \(path, xpubText, xprvText) ->       it ("chain " <> path) $ do         let m = makeXPrvKey (fromJust (decodeHex m4))-            k = derivePath ctx ((.get) (fromJust (parsePath path))) m+            k = derivePath ((.get) (fromJust (parsePath path))) m         xPrvExport btc k `shouldBe` xprvText-        xPubExport btc ctx (deriveXPubKey ctx k) `shouldBe` xpubText+        xPubExport btc (deriveXPubKey k) `shouldBe` xpubText   describe "bip32 test vector 5: invalid extended keys" $     forM_ vector5 $ \(key, reason) ->       it ("refuses " <> reason) $ do         xPrvImport btc key `shouldBe` Nothing-        xPubImport btc ctx key `shouldBe` Nothing+        xPubImport btc key `shouldBe` Nothing   describe "Extended key import" $ do     it "refuses an xpub with trailing bytes" $       -- the 78 bytes of the vector 1 master xpub followed by de ad be ef-      xPubImport btc ctx "7JJikZQ2NUXjSAnAF2v9rxutS1j84JbPJspH9roCjFfNvxFfhmgTczN53frJ4RaYoKmwYCj5r1qRsGbLz2fiUE4Aw7LqCR9NYxR72w6AThhWJsB43ZrGA"+      xPubImport btc "7JJikZQ2NUXjSAnAF2v9rxutS1j84JbPJspH9roCjFfNvxFfhmgTczN53frJ4RaYoKmwYCj5r1qRsGbLz2fiUE4Aw7LqCR9NYxR72w6AThhWJsB43ZrGA"         `shouldBe` Nothing     it "refuses an xprv with trailing bytes" $       xPrvImport btc "7JJRGiiVuW9DCAkyM2PaXqVx51tHCM3s2Wbq9SnmstZD4r8Ryf4i7Dbe2YQyz9mUF9oZEcdkyzU96dsBwJz3Uvu6PzVTC5k53mBrVHWxZMPdSBtmunEjn"         `shouldBe` Nothing     it "refuses an xpub carrying an uncompressed public key" $       -- 110 bytes: the vector 1 master xpub with its key in the 65-byte form-      xPubImport btc ctx "HarqLWPftSVzTwufEPMMMdZS33daVnF1pMQCFXEQoWwsd7tK1oCwB34reM1xTwhKvY11Pfgite2BcpvEDscYTtuZYL3pZAwQzAoZRLA1xCjK2F28jNBa3muZtLmsqfWHzwSGk2RRAd1e52SvdFecN97hmfA"+      xPubImport btc "HarqLWPftSVzTwufEPMMMdZS33daVnF1pMQCFXEQoWwsd7tK1oCwB34reM1xTwhKvY11Pfgite2BcpvEDscYTtuZYL3pZAwQzAoZRLA1xCjK2F28jNBa3muZtLmsqfWHzwSGk2RRAd1e52SvdFecN97hmfA"         `shouldBe` Nothing     it "refuses a string longer than any extended key" $ do       xPrvImport btc (T.replicate 113 "z") `shouldBe` Nothing-      xPubImport btc ctx (T.replicate 113 "z") `shouldBe` Nothing+      xPubImport btc (T.replicate 113 "z") `shouldBe` Nothing     it "refuses a string of a million characters at once, without decoding it" $ do       -- Decoding that much Base58 takes minutes. The length check comes first.       timeout 1000000 (evaluate (xPrvImport btc (T.replicate 1000000 "z")))         `shouldReturn` Just Nothing-      timeout 1000000 (evaluate (xPubImport btc ctx (T.replicate 1000000 "z")))+      timeout 1000000 (evaluate (xPubImport btc (T.replicate 1000000 "z")))         `shouldReturn` Just Nothing     it "refuses an extended key of another network" $ do       xPrvImport btcTest xprv1Text `shouldBe` Nothing       xPrvImport btc tprv1Text `shouldBe` Nothing-      xPubImport btcTest ctx xpub1Text `shouldBe` Nothing-      xPubImport btc ctx tpub1Text `shouldBe` Nothing+      xPubImport btcTest xpub1Text `shouldBe` Nothing+      xPubImport btc tpub1Text `shouldBe` Nothing     it "imports the testnet form of a key on testnet" $ do-      fmap (.key) (xPrvImport btcTest tprv1Text) `shouldBe` Just (xprv1 ctx).key-      fmap (.key) (xPubImport btcTest ctx tpub1Text) `shouldBe` Just (xpub1 ctx).key+      fmap (.key) (xPrvImport btcTest tprv1Text) `shouldBe` Just xprv1.key+      fmap (.key) (xPubImport btcTest tpub1Text) `shouldBe` Just xpub1.key     it "writes a key with the version bytes of each of the eight networks" $ do       -- xprv and xpub (0488ade4, 0488b21e) on the two main networks, tprv and       -- tpub (04358394, 043587cf) on the six others: chainparams.cpp of       -- Bitcoin Core and of Bitcoin Cash Node. The key is the master key of       -- BIP32 test vector 1.       forM_ [btc, bch] $ \net -> do-        xPrvExport net (xprv1 ctx) `shouldBe` xprv1Text-        xPubExport net ctx (xpub1 ctx) `shouldBe` xpub1Text+        xPrvExport net xprv1 `shouldBe` xprv1Text+        xPubExport net xpub1 `shouldBe` xpub1Text       forM_ [btcTest, btcTest4, btcRegTest, bchTest, bchTest4, bchRegTest] $ \net -> do-        xPrvExport net (xprv1 ctx) `shouldBe` tprv1Text-        xPubExport net ctx (xpub1 ctx) `shouldBe` tpub1Text+        xPrvExport net xprv1 `shouldBe` tprv1Text+        xPubExport net xpub1 `shouldBe` tpub1Text     it "refuses an xpub given to the private key importer, and the reverse" $ do       xPrvImport btc xpub1Text `shouldBe` Nothing-      xPubImport btc ctx xprv1Text `shouldBe` Nothing+      xPubImport btc xprv1Text `shouldBe` Nothing     it "fails the JSON parse of an invalid extended key" $       -- BIP32 test vector 5: private key 0       (unmarshalJSON btc "\"xprv9s21ZrQH143K24Mfq5zL5MhWK9hUhhGbd45hLXo2Pq2oqzMMo63oStZzF93Y5wvzdUayhgkkFoicQZcP3y52uPPxFnfoLZB21Teqt1VvEHx\"" :: Maybe XPrvKey)@@ -153,13 +153,13 @@         xpubBytes = hex ("0488b21e" <> header <> "0339a36013301597daef41fbe593a02cc513d0b55527ec2df1050e2e8ff49c85c2")         xprvBytes = hex ("0488ade4" <> header <> "00e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35")     it "reads the 78 bytes of an extended public key" $-      fmap (xPubExport btc ctx) (unmarshal (btc, ctx) xpubBytes) `shouldBe` Right xpub1Text+      fmap (xPubExport btc) (unmarshal btc xpubBytes) `shouldBe` Right xpub1Text     it "reads the 78 bytes of an extended private key" $       fmap (xPrvExport btc) (unmarshal btc xprvBytes) `shouldBe` Right xprv1Text     it "refuses an extended public key whose key is in the 65-byte form" $       -- the same key with its y coordinate, 110 bytes in all       ( unmarshal-          (btc, ctx)+          btc           ( hex               ( "0488b21e"                   <> header@@ -171,7 +171,7 @@       )         `shouldSatisfy` either ("compressed public key" `isInfixOf`) (const False)     it "refuses bytes after the 78 bytes of an extended key" $ do-      (unmarshal (btc, ctx) (xpubBytes <> "\x00") :: Either String XPubKey)+      (unmarshal btc (xpubBytes <> "\x00") :: Either String XPubKey)         `shouldSatisfy` either ("bytes left over" `isInfixOf`) (const False)       (unmarshal btc (xprvBytes <> "\x00") :: Either String XPrvKey)         `shouldSatisfy` either ("bytes left over" `isInfixOf`) (const False)@@ -207,7 +207,7 @@     it "shows the depth, parent and index but not the chain code or the key" $ do       let m = makeXPrvKey (fromJust (decodeHex m1))       show m `shouldBe` "XPrvKey {depth = 0, parent = \"00000000\", index = 0, chain = <redacted>, key = <redacted>}"-      show (hardSubKey ctx m 7) `shouldBe` "XPrvKey {depth = 1, parent = \"3442193e\", index = 2147483655, chain = <redacted>, key = <redacted>}"+      show (hardSubKey m 7) `shouldBe` "XPrvKey {depth = 1, parent = \"3442193e\", index = 2147483655, chain = <redacted>, key = <redacted>}"       show (Just m) `shouldBe` "Just (XPrvKey {depth = 0, parent = \"00000000\", index = 0, chain = <redacted>, key = <redacted>})"   describe "Derivation depth" $ do     let m = makeXPrvKey (fromJust (decodeHex m1))@@ -215,52 +215,52 @@         tooDeep = DerivationException "Maximum derivation depth exceeded"         hardIndex = DerivationException "Invalid child derivation index"     it "a child is one level deeper than its parent" $ do-      (prvSubKey ctx m 0).depth `shouldBe` 1-      (hardSubKey ctx m 0).depth `shouldBe` 1-      (pubSubKey ctx (deriveXPubKey ctx m) 0).depth `shouldBe` 1-      (derivePath ctx (Deriv :| 0 :/ 1 :/ 2 :: DerivPath) m).depth `shouldBe` 3+      (prvSubKey m 0).depth `shouldBe` 1+      (hardSubKey m 0).depth `shouldBe` 1+      (pubSubKey (deriveXPubKey m) 0).depth `shouldBe` 1+      (derivePath (Deriv :| 0 :/ 1 :/ 2 :: DerivPath) m).depth `shouldBe` 3     it "refuses to derive a child of a key at depth 255" $ do-      evaluate (prvSubKey ctx atDepth255 0) `shouldThrow` (== tooDeep)-      evaluate (hardSubKey ctx atDepth255 0) `shouldThrow` (== tooDeep)-      evaluate (pubSubKey ctx (deriveXPubKey ctx atDepth255) 0) `shouldThrow` (== tooDeep)+      evaluate (prvSubKey atDepth255 0) `shouldThrow` (== tooDeep)+      evaluate (hardSubKey atDepth255 0) `shouldThrow` (== tooDeep)+      evaluate (pubSubKey (deriveXPubKey atDepth255) 0) `shouldThrow` (== tooDeep)     it "refuses a child index with the hard bit set with a DerivationException" $ do-      evaluate (prvSubKey ctx m 0x80000000) `shouldThrow` (== hardIndex)-      evaluate (hardSubKey ctx m 0x80000000) `shouldThrow` (== hardIndex)-      evaluate (pubSubKey ctx (deriveXPubKey ctx m) 0x80000000) `shouldThrow` (== hardIndex)+      evaluate (prvSubKey m 0x80000000) `shouldThrow` (== hardIndex)+      evaluate (hardSubKey m 0x80000000) `shouldThrow` (== hardIndex)+      evaluate (pubSubKey (deriveXPubKey m) 0x80000000) `shouldThrow` (== hardIndex)     -- The depth is one byte, so a master key has descendants down to depth     -- 255 and no further     let steps n = concat (replicate n "/0")         depthOf (XPrv k _) = k.depth         depthOf (XPub k _) = k.depth     it "applyPath derives a path of 255 steps from a master key" $ do-      fmap depthOf (applyPath ctx (fromString ("m" <> steps 255)) (XPrv m btc)) `shouldBe` Right 255-      fmap depthOf (applyPath ctx (fromString ("M" <> steps 255)) (XPub (deriveXPubKey ctx m) btc)) `shouldBe` Right 255+      fmap depthOf (applyPath (fromString ("m" <> steps 255)) (XPrv m btc)) `shouldBe` Right 255+      fmap depthOf (applyPath (fromString ("M" <> steps 255)) (XPub (deriveXPubKey m) btc)) `shouldBe` Right 255     it "applyPath gives an error value for a path of 256 steps from a master key" $ do-      applyPath ctx (fromString ("m" <> steps 256)) (XPrv m btc)+      applyPath (fromString ("m" <> steps 256)) (XPrv m btc)         `shouldBe` Left "applyPath: Maximum derivation depth exceeded"-      applyPath ctx (fromString ("M" <> steps 256)) (XPrv m btc)+      applyPath (fromString ("M" <> steps 256)) (XPrv m btc)         `shouldBe` Left "applyPath: Maximum derivation depth exceeded"-      applyPath ctx (fromString ("M" <> steps 256)) (XPub (deriveXPubKey ctx m) btc)+      applyPath (fromString ("M" <> steps 256)) (XPub (deriveXPubKey m) btc)         `shouldBe` Left "applyPath: Maximum derivation depth exceeded"     it "applyPath gives an error value for one step from a key at depth 255" $-      applyPath ctx "m/0" (XPrv atDepth255 btc)+      applyPath "m/0" (XPrv atDepth255 btc)         `shouldBe` Left "applyPath: Maximum derivation depth exceeded"     it "tryDerivePath derives what derivePath derives" $       -- BIP32 test vector 1, chain m/0'/1-      fmap (xPrvExport btc) (tryDerivePath ctx (Deriv :| 0 :/ 1 :: DerivPath) m)+      fmap (xPrvExport btc) (tryDerivePath (Deriv :| 0 :/ 1 :: DerivPath) m)         `shouldBe` Right "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs"     it "tryDerivePath gives an error value for a path of 256 steps from a master key" $-      tryDerivePath ctx (listToPath (replicate 256 0)) m+      tryDerivePath (listToPath (replicate 256 0)) m         `shouldBe` Left "Maximum derivation depth exceeded"     it "tryDerivePubPath derives what derivePubPath derives" $       -- BIP32 test vector 2, chain m/0, from the master public key-      fmap (xPubExport btc ctx) (tryDerivePubPath ctx (Deriv :/ 0) (xpub2 ctx))+      fmap (xPubExport btc) (tryDerivePubPath (Deriv :/ 0) xpub2)         `shouldBe` Right "xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH"     it "tryDerivePubPath gives an error value for a path of 256 steps from a master key" $-      tryDerivePubPath ctx (foldl (:/) Deriv (replicate 256 0)) (deriveXPubKey ctx m)+      tryDerivePubPath (foldl (:/) Deriv (replicate 256 0)) (deriveXPubKey m)         `shouldBe` Left "Maximum derivation depth exceeded"     it "derivePath throws a DerivationException for a path of 256 steps from a master key" $-      evaluate (derivePath ctx (listToPath (replicate 256 0)) m) `shouldThrow` (== tooDeep)+      evaluate (derivePath (listToPath (replicate 256 0)) m) `shouldThrow` (== tooDeep)     it "the path constructors refuse an index of 2^31 or more" $ do       evaluate (Deriv :/ 0x80000000 :: DerivPath) `shouldThrow` (== hardIndex)       evaluate (Deriv :| 0x80000000 :: DerivPath) `shouldThrow` (== hardIndex)@@ -273,57 +273,57 @@   describe "Child index" $ do     let m = makeXPrvKey (fromJust (decodeHex m1))     it "a hardened child stores its index with the hard bit set" $ do-      let k = hardSubKey ctx m 7+      let k = hardSubKey m 7       k.index `shouldBe` 0x80000007       xPrvChild k `shouldBe` 7       xPrvIsHard k `shouldBe` True-      xPubChild (deriveXPubKey ctx k) `shouldBe` 7-      xPubIsHard (deriveXPubKey ctx k) `shouldBe` True+      xPubChild (deriveXPubKey k) `shouldBe` 7+      xPubIsHard (deriveXPubKey k) `shouldBe` True     it "a soft child stores its index as given" $ do-      let k = prvSubKey ctx m 7+      let k = prvSubKey m 7       k.index `shouldBe` 7       xPrvChild k `shouldBe` 7       xPrvIsHard k `shouldBe` False-      xPubChild (deriveXPubKey ctx k) `shouldBe` 7-      xPubIsHard (deriveXPubKey ctx k) `shouldBe` False+      xPubChild (deriveXPubKey k) `shouldBe` 7+      xPubIsHard (deriveXPubKey k) `shouldBe` False   describe "Addresses of an extended public key" $ do     -- BIP32 vector 1 master public key 0339a360…85c2 has HASH160 3442193e…f811     it "pay to public key hash" $-      addrToText btc (xPubAddr ctx (xpub1 ctx)) `shouldBe` Just "15mKKb2eos1hWa6tisdPwwDC1a5J1y9nma"+      addrToText btc (xPubAddr xpub1) `shouldBe` Just "15mKKb2eos1hWa6tisdPwwDC1a5J1y9nma"     it "pay to witness public key hash" $-      addrToText btc (xPubWitnessAddr ctx (xpub1 ctx)) `shouldBe` Just "bc1qx3ppj0smkuy3d6g525sh9n2w9k7fm7q3x30rtg"+      addrToText btc (xPubWitnessAddr xpub1) `shouldBe` Just "bc1qx3ppj0smkuy3d6g525sh9n2w9k7fm7q3x30rtg"     it "pay to script hash wrapping a witness public key hash" $-      addrToText btc (xPubCompatWitnessAddr ctx (xpub1 ctx)) `shouldBe` Just "3PpgpssV7mcAGpZRWiCWhodUTnjpoSZg7a"+      addrToText btc (xPubCompatWitnessAddr xpub1) `shouldBe` Just "3PpgpssV7mcAGpZRWiCWhodUTnjpoSZg7a"   describe "Address derivation helpers" $ do     -- BIP32 vector 2: child 0 of the master key has public key 02fc9e5a…12ea     it "deriveAddr gives the address and the public key of the child" $ do-      let (addr, key) = deriveAddr ctx (xpub2 ctx) 0+      let (addr, key) = deriveAddr xpub2 0       addrToText btc addr `shouldBe` Just "19EuDJdgfRkwCmRzbzVBHZWQG9QNWhftbZ"-      encodeHex (exportPubKey ctx True key)+      encodeHex (exportPubKey True key)         `shouldBe` "02fc9e5af0ac8d9b3cecfe2a888e2117ba3d089d8585886c9c826b6b22a98d12ea"     it "deriveWitnessAddr gives the witness address of the child" $-      addrToText btc (fst (deriveWitnessAddr ctx (xpub2 ctx) 0))+      addrToText btc (fst (deriveWitnessAddr xpub2 0))         `shouldBe` Just "bc1qtfsllr4h4t9rqyxmjl4a5asjzcgt0qykp3q3we"     it "deriveCompatWitnessAddr gives the wrapped witness address of the child" $-      addrToText btc (fst (deriveCompatWitnessAddr ctx (xpub2 ctx) 0))+      addrToText btc (fst (deriveCompatWitnessAddr xpub2 0))         `shouldBe` Just "39cFMGtVaEw6AfksMcaLpu8frZxmqngh8c"     it "deriveAddrs lists children from the start index and wraps around" $ do-      map lst3 (take 3 (deriveAddrs ctx (xpub2 ctx) 0x7ffffffe))+      map lst3 (take 3 (deriveAddrs xpub2 0x7ffffffe))         `shouldBe` [0x7ffffffe, 0x7fffffff, 0]-      map addressAndIndex (take 1 (deriveAddrs ctx (xpub2 ctx) 5))+      map addressAndIndex (take 1 (deriveAddrs xpub2 5))         `shouldBe` [(Just "16KmCWXw8kPgr9nnvETXoqzmsYcvscXfGL", 5)]     it "deriveWitnessAddrs lists witness addresses with their index" $-      map addressAndIndex (take 1 (deriveWitnessAddrs ctx (xpub2 ctx) 5))+      map addressAndIndex (take 1 (deriveWitnessAddrs xpub2 5))         `shouldBe` [(Just "bc1q8fjs9hakl9489q0fem0gya4m8yqr4gl32dhjr9", 5)]     it "deriveCompatWitnessAddrs lists wrapped witness addresses with their index" $-      map addressAndIndex (take 1 (deriveCompatWitnessAddrs ctx (xpub2 ctx) 5))+      map addressAndIndex (take 1 (deriveCompatWitnessAddrs xpub2 5))         `shouldBe` [(Just "3FzrsDTC8KiEsBeBTrhDnJoJYvkDpWaWR6", 5)]     it "prvSubKeys, pubSubKeys and hardSubKeys list children with their index" $ do       let m = makeXPrvKey (fromJust (decodeHex m1))-      map snd (take 3 (prvSubKeys ctx m 0x7ffffffe)) `shouldBe` [0x7ffffffe, 0x7fffffff, 0]-      map snd (take 2 (hardSubKeys ctx m 0)) `shouldBe` [0, 1]-      map ((.index) . fst) (take 1 (hardSubKeys ctx m 1)) `shouldBe` [0x80000001]-      map (\(k, i) -> (addrToText btc (xPubAddr ctx k), i)) (take 1 (pubSubKeys ctx (xpub2 ctx) 0))+      map snd (take 3 (prvSubKeys m 0x7ffffffe)) `shouldBe` [0x7ffffffe, 0x7fffffff, 0]+      map snd (take 2 (hardSubKeys m 0)) `shouldBe` [0, 1]+      map ((.index) . fst) (take 1 (hardSubKeys m 1)) `shouldBe` [0x80000001]+      map (\(k, i) -> (addrToText btc (xPubAddr k), i)) (take 1 (pubSubKeys xpub2 0))         `shouldBe` [(Just "19EuDJdgfRkwCmRzbzVBHZWQG9QNWhftbZ", 0)]     it "cycleIndex runs through the soft indices from the start and wraps around" $ do       take 3 (cycleIndex 0x7ffffffe) `shouldBe` [0x7ffffffe, 0x7fffffff, 0]@@ -332,63 +332,63 @@   describe "Multisig derivation" $ do     -- 2-of-2 of child 0 of vectors 1 and 2; sorted keys 027c4b09… then 02fc9e5a…     it "deriveMSAddr gives the P2SH address of the sorted multisig script" $ do-      let Right (addr, rdm) = deriveMSAddr ctx [xpub2 ctx, xpub1 ctx] 2 0+      let Right (addr, rdm) = deriveMSAddr [xpub2, xpub1] 2 0       addrToText btc addr `shouldBe` Just "3ARSZ47cqQBb9y6QhTk6UoWHMwpruUryZp"-      encodeHex (marshal ctx rdm)+      encodeHex (encodeSerial rdm)         `shouldBe` "5221027c4b09ffb985c298afe7e5813266cbfcb7780b480ac294b0b43dc21f2be3d13c\                    \2102fc9e5af0ac8d9b3cecfe2a888e2117ba3d089d8585886c9c826b6b22a98d12ea52ae"     it "deriveMSAddrs lists multisig addresses with their index" $ do-      (map lst3 . take 2 <$> deriveMSAddrs ctx [xpub1 ctx, xpub2 ctx] 2 0) `shouldBe` Right [0, 1]+      (map lst3 . take 2 <$> deriveMSAddrs [xpub1, xpub2] 2 0) `shouldBe` Right [0, 1]       -- 2-of-2 of child 1 of vectors 1 and 2-      (map addressAndIndex . take 1 <$> deriveMSAddrs ctx [xpub1 ctx, xpub2 ctx] 2 1)+      (map addressAndIndex . take 1 <$> deriveMSAddrs [xpub1, xpub2] 2 1)         `shouldBe` Right [(Just "3Pp8RkaJc8eNreFuTTTJ92QfXECQMXDEoE", 1)]     it "deriveMSAddr gives the P2SH address of 15 keys, the most that fit" $       -- 1-of-15 of child 0 of m/0 to m/14 of vector 1. The redeem script is       -- 3 + 15 × 34 = 513 bytes. The address is the one that createmultisig       -- of Bitcoin Core 32.1 gives for these keys on regtest.-      (addrToText btcRegTest . fst <$> deriveMSAddr ctx (accountKeys ctx 15) 1 0)+      (addrToText btcRegTest . fst <$> deriveMSAddr (accountKeys 15) 1 0)         `shouldBe` Right (Just "2NFJxQqeqnzhLx9a1UBhpdgYVGxcd95Ka1b")     it "deriveMSAddr has no address for 16 keys, whose redeem script cannot be spent" $       -- 3 + 16 × 34 = 547 bytes, and a push holds at most 520. Bitcoin Core       -- answers "redeemScript exceeds size limit: 547 > 520".-      (fst <$> deriveMSAddr ctx (accountKeys ctx 16) 1 0)+      (fst <$> deriveMSAddr (accountKeys 16) 1 0)         `shouldBe` Left "The redeem script is 547 bytes long, and a pay-to-script-hash redeem script can have at most 520"     it "deriveMSAddr has no address for 20 keys" $       -- 3 + 20 × 34 + 1 = 684 bytes-      (fst <$> deriveMSAddr ctx (accountKeys ctx 20) 1 0)+      (fst <$> deriveMSAddr (accountKeys 20) 1 0)         `shouldBe` Left "The redeem script is 684 bytes long, and a pay-to-script-hash redeem script can have at most 520"     it "deriveMSAddrs and the path forms fail for 16 keys as deriveMSAddr does" $ do       let tooLong = Left "The redeem script is 547 bytes long, and a pay-to-script-hash redeem script can have at most 520"-      (length . take 1 <$> deriveMSAddrs ctx (accountKeys ctx 16) 1 0) `shouldBe` tooLong-      (fst <$> derivePathMSAddr ctx (accountKeys ctx 16) (Deriv :/ 1) 1 0) `shouldBe` tooLong-      (length . take 1 <$> derivePathMSAddrs ctx (accountKeys ctx 16) (Deriv :/ 1) 1 0) `shouldBe` tooLong+      (length . take 1 <$> deriveMSAddrs (accountKeys 16) 1 0) `shouldBe` tooLong+      (fst <$> derivePathMSAddr (accountKeys 16) (Deriv :/ 1) 1 0) `shouldBe` tooLong+      (length . take 1 <$> derivePathMSAddrs (accountKeys 16) (Deriv :/ 1) 1 0) `shouldBe` tooLong     it "deriveMSAddr gives an error value for a signature count the keys cannot meet" $ do-      (fst <$> deriveMSAddr ctx [xpub1 ctx, xpub2 ctx] 3 0)+      (fst <$> deriveMSAddr [xpub1, xpub2] 3 0)         `shouldBe` Left "encodeOutput: multisig requires more signatures than it has keys"-      (fst <$> deriveMSAddr ctx [xpub1 ctx, xpub2 ctx] 0 0)+      (fst <$> deriveMSAddr [xpub1, xpub2] 0 0)         `shouldBe` Left "encodeOutput: multisig must require at least one signature"-      (fst <$> deriveMSAddr ctx [xpub1 ctx, xpub2 ctx] (-1) 0)+      (fst <$> deriveMSAddr [xpub1, xpub2] (-1) 0)         `shouldBe` Left "encodeOutput: multisig must require at least one signature"-      (fst <$> deriveMSAddr ctx [] 1 0)+      (fst <$> deriveMSAddr [] 1 0)         `shouldBe` Left "encodeOutput: multisig requires more signatures than it has keys"-      (length . take 1 <$> deriveMSAddrs ctx [xpub1 ctx, xpub2 ctx] 3 0)+      (length . take 1 <$> deriveMSAddrs [xpub1, xpub2] 3 0)         `shouldBe` Left "encodeOutput: multisig requires more signatures than it has keys"   describe "Address derivation below a path" $ do     -- vector 2: m/0/0 has public key 0205c889…ef8c     it "derivePathAddr derives the address of a child below a soft path" $ do-      let (addr, key) = derivePathAddr ctx (xpub2 ctx) (Deriv :/ 0) 0+      let (addr, key) = derivePathAddr xpub2 (Deriv :/ 0) 0       addrToText btc addr `shouldBe` Just "1NyMg76BQxDvV6vRsQugNS4ED2hpZCJtwK"-      encodeHex (exportPubKey ctx True key)+      encodeHex (exportPubKey True key)         `shouldBe` "0205c8897fd0ff5644adba4545a84020cd6aa94d90e1e0a56bb4b8eb7522e3ef8c"     it "derivePathAddrs lists children below the path with their index" $-      map addressAndIndex (take 1 (derivePathAddrs ctx (xpub2 ctx) (Deriv :/ 0) 0))+      map addressAndIndex (take 1 (derivePathAddrs xpub2 (Deriv :/ 0) 0))         `shouldBe` [(Just "1NyMg76BQxDvV6vRsQugNS4ED2hpZCJtwK", 0)]     it "derivePathMSAddr derives a multisig address below a soft path" $ do       -- 2-of-2 of m/1/0 of vectors 1 and 2-      let Right (addr, _) = derivePathMSAddr ctx [xpub1 ctx, xpub2 ctx] (Deriv :/ 1) 2 0+      let Right (addr, _) = derivePathMSAddr [xpub1, xpub2] (Deriv :/ 1) 2 0       addrToText btc addr `shouldBe` Just "39HHTbxsnt5SrM4h2BtUgVRFzGYcavJ8M4"     it "derivePathMSAddrs lists multisig addresses below the path with their index" $-      (map addressAndIndex . take 1 <$> derivePathMSAddrs ctx [xpub1 ctx, xpub2 ctx] (Deriv :/ 1) 2 0)+      (map addressAndIndex . take 1 <$> derivePathMSAddrs [xpub1, xpub2] (Deriv :/ 1) 2 0)         `shouldBe` Right [(Just "39HHTbxsnt5SrM4h2BtUgVRFzGYcavJ8M4", 0)]   describe "Path operations" $ do     it "++/ appends two paths into a mixed path" $ do@@ -464,9 +464,9 @@   describe "Fingerprint text" $ do     -- the identifier of the vector 1 master key starts with 3442193e     it "writes eight hex digits" $-      fingerprintToText (xPubFP ctx (xpub1 ctx)) `shouldBe` "3442193e"+      fingerprintToText (xPubFP xpub1) `shouldBe` "3442193e"     it "reads eight hex digits" $-      textToFingerprint "3442193e" `shouldBe` Right (xPubFP ctx (xpub1 ctx))+      textToFingerprint "3442193e" `shouldBe` Right (xPubFP xpub1)     it "refuses more or fewer than four bytes" $ do       textToFingerprint "0011223344" `shouldSatisfy` isLeft       textToFingerprint "001122" `shouldSatisfy` isLeft@@ -474,24 +474,24 @@     it "refuses text that is not hex" $       textToFingerprint "zzzzzzzz" `shouldSatisfy` isLeft     it "parses from JSON and refuses the wrong length" $ do-      A.decode "\"3442193e\"" `shouldBe` Just (xPubFP ctx (xpub1 ctx))+      A.decode "\"3442193e\"" `shouldBe` Just (xPubFP xpub1)       (A.decode "\"0011223344\"" :: Maybe Fingerprint) `shouldBe` Nothing     it "refuses to read the wrong length" $       readMaybe "\"0011223344\"" `shouldBe` (Nothing :: Maybe Fingerprint)     it "refuses a literal of the wrong length" $       evaluate ("0011223344" :: Fingerprint) `shouldThrow` anyErrorCall   describe "bip32 subkey derivation using string path" $ do-    it "applyPath derives private and public keys along a path" $ testApplyPath ctx-    it "applyPath refuses private derivations on a public key and hard public derivations" $ testBadApplyPath ctx+    it "applyPath derives private and public keys along a path" $ testApplyPath+    it "applyPath refuses private derivations on a public key and hard public derivations" $ testBadApplyPath     it "applyPath gives the keys of BIP32 test vector 1, chain m/0'/1" $ do       let exported (XPrv k n) = xPrvExport n k-          exported (XPub k n) = xPubExport n ctx k-      fmap exported (applyPath ctx "m/0'/1" (XPrv (xprv1 ctx) btc))+          exported (XPub k n) = xPubExport n k+      fmap exported (applyPath "m/0'/1" (XPrv xprv1 btc))         `shouldBe` Right "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs"-      fmap exported (applyPath ctx "M/0'/1" (XPrv (xprv1 ctx) btc))+      fmap exported (applyPath "M/0'/1" (XPrv xprv1 btc))         `shouldBe` Right "xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ"-    it "public derivations" $ testDerivePubPath ctx-    it "private derivations" $ testDerivePrvPath ctx+    it "public derivations" $ testDerivePubPath+    it "private derivations" $ testDerivePrvPath     it "path parsing" testParsePath     it "from json" testFromJsonPath     it "to json" testToJsonPath@@ -519,13 +519,13 @@     prop "computes pubkey of a subkey is subkey of the pubkey" $       -- a key at depth 255 cannot have children       forAll (arbitraryXPrvKey `suchThat` ((< 255) . (.depth))) $-        pubKeyOfSubKeyIsSubKeyOfPubKey ctx+        pubKeyOfSubKeyIsSubKeyOfPubKey     prop "exports and imports extended private key" $       forAll arbitraryXPrvKey $ \k ->         xPrvImport net (xPrvExport net k) == Just k     prop "exports and imports extended public key" $-      forAll (arbitraryXPubKey ctx) $ \k ->-        xPubImport net ctx (xPubExport net ctx k) == Just k+      forAll arbitraryXPubKey $ \k ->+        xPubImport net (xPubExport net k) == Just k  hex :: Text -> B.ByteString hex = fromJust . decodeHex@@ -543,25 +543,25 @@ tprv1Text = "tprv8ZgxMBicQKsPeDgjzdC36fs6bMjGApWDNLR9erAXMs5skhMv36j9MV5ecvfavji5khqjWaWSFhN3YcCUUdiKH6isR4Pwy3U5y5egddBr16m" xpub2Text = "xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB" -xpub1, xpub2 :: Ctx -> XPubKey-xpub1 ctx = fromJust (xPubImport btc ctx xpub1Text)-xpub2 ctx = fromJust (xPubImport btc ctx xpub2Text)+xpub1, xpub2 :: XPubKey+xpub1 = fromJust (xPubImport btc xpub1Text)+xpub2 = fromJust (xPubImport btc xpub2Text)  -- | The extended public keys m/0 to m/(n-1) of BIP 32 test vector 1.-accountKeys :: Ctx -> Int -> [XPubKey]-accountKeys ctx n =-  [ deriveXPubKey ctx (prvSubKey ctx master (fromIntegral i))-    | i <- [0 .. n - 1]+accountKeys :: Int -> [XPubKey]+accountKeys n =+  [ deriveXPubKey (prvSubKey master (fromIntegral i))+  | i <- [0 .. n - 1]   ]   where     master = makeXPrvKey (hex "000102030405060708090a0b0c0d0e0f") -xprv1 :: Ctx -> XPrvKey-xprv1 _ = fromJust (xPrvImport btc xprv1Text)+xprv1 :: XPrvKey+xprv1 = fromJust (xPrvImport btc xprv1Text) -pubKeyOfSubKeyIsSubKeyOfPubKey :: Ctx -> XPrvKey -> Word32 -> Bool-pubKeyOfSubKeyIsSubKeyOfPubKey ctx k i =-  deriveXPubKey ctx (prvSubKey ctx k i') == pubSubKey ctx (deriveXPubKey ctx k) i'+pubKeyOfSubKeyIsSubKeyOfPubKey :: XPrvKey -> Word32 -> Bool+pubKeyOfSubKeyIsSubKeyOfPubKey k i =+  deriveXPubKey (prvSubKey k i') == pubSubKey (deriveXPubKey k) i'   where     i' = fromIntegral $ i .&. 0x7fffffff -- make it a public derivation @@ -627,44 +627,44 @@     ("NaN", isNothing)   ] -testApplyPath :: Ctx -> Assertion-testApplyPath ctx =+testApplyPath :: Assertion+testApplyPath =   sequence_ $ do-    (key, path, final) <- applyPathVectors ctx+    (key, path, final) <- applyPathVectors     return $       assertEqual path final $-        applyPath ctx (fromJust $ parsePath path) key+        applyPath (fromJust $ parsePath path) key -testBadApplyPath :: Ctx -> Assertion-testBadApplyPath ctx =+testBadApplyPath :: Assertion+testBadApplyPath =   sequence_ $ do-    (key, path) <- badApplyPathVectors ctx+    (key, path) <- badApplyPathVectors     return $       assertBool path $         isLeft $-          applyPath ctx (fromJust $ parsePath path) key+          applyPath (fromJust $ parsePath path) key -testDerivePubPath :: Ctx -> Assertion-testDerivePubPath ctx =+testDerivePubPath :: Assertion+testDerivePubPath =   sequence_ $ do-    (key, path, final) <- derivePubPathVectors ctx+    (key, path, final) <- derivePubPathVectors     return $       assertEqual path final $-        derivePubPath ctx (fromString path :: SoftPath) key+        derivePubPath (fromString path :: SoftPath) key -testDerivePrvPath :: Ctx -> Assertion-testDerivePrvPath ctx =+testDerivePrvPath :: Assertion+testDerivePrvPath =   sequence_ $ do-    (key, path, final) <- derivePrvPathVectors ctx+    (key, path, final) <- derivePrvPathVectors     return $       assertEqual path final $-        derivePath ctx (fromString path :: DerivPath) key+        derivePath (fromString path :: DerivPath) key -derivePubPathVectors :: Ctx -> [(XPubKey, String, XPubKey)]-derivePubPathVectors ctx =+derivePubPathVectors :: [(XPubKey, String, XPubKey)]+derivePubPathVectors =   [ (xpub, "M", xpub),-    (xpub, "M/8", pubSubKey ctx xpub 8),-    (xpub, "M/8/30/1", foldl (pubSubKey ctx) xpub [8, 30, 1])+    (xpub, "M/8", pubSubKey xpub 8),+    (xpub, "M/8/30/1", foldl pubSubKey xpub [8, 30, 1])   ]   where     xprv =@@ -673,29 +673,29 @@           btc           "xprv9s21ZrQH143K46iDVRSyFfGfMgQjzC4BV3ZUfNbG7PHQrJjE53ofAn5gYkp6KQ\           \WzGmb8oageSRxBY8s4rjr9VXPVp2HQDbwPt4H31Gg4LpB"-    xpub = deriveXPubKey ctx xprv+    xpub = deriveXPubKey xprv -derivePrvPathVectors :: Ctx -> [(XPrvKey, String, XPrvKey)]-derivePrvPathVectors ctx =+derivePrvPathVectors :: [(XPrvKey, String, XPrvKey)]+derivePrvPathVectors =   [ (xprv, "m", xprv),     (xprv, "M", xprv),-    (xprv, "m/8'", hardSubKey ctx xprv 8),-    (xprv, "M/8'", hardSubKey ctx xprv 8),+    (xprv, "m/8'", hardSubKey xprv 8),+    (xprv, "M/8'", hardSubKey xprv 8),     ( xprv,       "m/8'/30/1",-      foldl (prvSubKey ctx) (hardSubKey ctx xprv 8) [30, 1]+      foldl prvSubKey (hardSubKey xprv 8) [30, 1]     ),     ( xprv,       "M/8'/30/1",-      foldl (prvSubKey ctx) (hardSubKey ctx xprv 8) [30, 1]+      foldl prvSubKey (hardSubKey xprv 8) [30, 1]     ),     ( xprv,       "m/3/20",-      foldl (prvSubKey ctx) xprv [3, 20]+      foldl prvSubKey xprv [3, 20]     ),     ( xprv,       "M/3/20",-      foldl (prvSubKey ctx) xprv [3, 20]+      foldl prvSubKey xprv [3, 20]     )   ]   where@@ -706,35 +706,35 @@           "xprv9s21ZrQH143K46iDVRSyFfGfMgQjzC4BV3ZUfNbG7PHQrJjE53ofAn5gYkp6KQ\           \WzGmb8oageSRxBY8s4rjr9VXPVp2HQDbwPt4H31Gg4LpB" -applyPathVectors :: Ctx -> [(XKey, String, Either String XKey)]-applyPathVectors ctx =+applyPathVectors :: [(XKey, String, Either String XKey)]+applyPathVectors =   [ (XPrv xprv btc, "m", Right (XPrv xprv btc)),     (XPrv xprv btc, "M", Right (XPub xpub btc)),-    (XPrv xprv btc, "m/8'", Right (XPrv (hardSubKey ctx xprv 8) btc)),+    (XPrv xprv btc, "m/8'", Right (XPrv (hardSubKey xprv 8) btc)),     ( XPrv xprv btc,       "M/8'",-      Right (XPub (deriveXPubKey ctx (hardSubKey ctx xprv 8)) btc)+      Right (XPub (deriveXPubKey (hardSubKey xprv 8)) btc)     ),     ( XPrv xprv btc,       "m/8'/30/1",-      Right (XPrv (foldl (prvSubKey ctx) (hardSubKey ctx xprv 8) [30, 1]) btc)+      Right (XPrv (foldl prvSubKey (hardSubKey xprv 8) [30, 1]) btc)     ),     ( XPrv xprv btc,       "M/8'/30/1",       Right         ( XPub-            (deriveXPubKey ctx (foldl (prvSubKey ctx) (hardSubKey ctx xprv 8) [30, 1]))+            (deriveXPubKey (foldl prvSubKey (hardSubKey xprv 8) [30, 1]))             btc         )     ),-    (XPrv xprv btc, "m/3/20", Right (XPrv (foldl (prvSubKey ctx) xprv [3, 20]) btc)),+    (XPrv xprv btc, "m/3/20", Right (XPrv (foldl prvSubKey xprv [3, 20]) btc)),     ( XPrv xprv btc,       "M/3/20",-      Right (XPub (deriveXPubKey ctx (foldl (prvSubKey ctx) xprv [3, 20])) btc)+      Right (XPub (deriveXPubKey (foldl prvSubKey xprv [3, 20])) btc)     ),     ( XPub xpub btc,       "M/3/20",-      Right (XPub (deriveXPubKey ctx (foldl (prvSubKey ctx) xprv [3, 20])) btc)+      Right (XPub (deriveXPubKey (foldl prvSubKey xprv [3, 20])) btc)     )   ]   where@@ -744,10 +744,10 @@           btc           "xprv9s21ZrQH143K46iDVRSyFfGfMgQjzC4BV3ZUfNbG7PHQrJjE53ofAn5gYkp6KQ\           \WzGmb8oageSRxBY8s4rjr9VXPVp2HQDbwPt4H31Gg4LpB"-    xpub = deriveXPubKey ctx xprv+    xpub = deriveXPubKey xprv -badApplyPathVectors :: Ctx -> [(XKey, String)]-badApplyPathVectors ctx =+badApplyPathVectors :: [(XKey, String)]+badApplyPathVectors =   [ (XPub xpub btc, "m/8'"),     (XPub xpub btc, "M/8'"),     (XPub xpub btc, "M/1/2/3'/4/5")@@ -759,7 +759,7 @@           btc           "xprv9s21ZrQH143K46iDVRSyFfGfMgQjzC4BV3ZUfNbG7PHQrJjE53ofAn5gYkp6KQ\           \WzGmb8oageSRxBY8s4rjr9VXPVp2HQDbwPt4H31Gg4LpB"-    xpub = deriveXPubKey ctx xprv+    xpub = deriveXPubKey xprv  -- BIP 0032 Test Vectors -- https://en.bitcoin.it/wiki/BIP_0032_TestVectors@@ -767,57 +767,57 @@ bip44Addr :: DerivPath bip44Addr = Deriv :| 44 :| 0 :| 0 :/ 0 :/ 0 -vectorSpec :: Ctx -> TestKey -> [TestVector] -> Spec-vectorSpec ctx mTxt vecTxt =-  forM_ (parseVector ctx mTxt vecTxt) $ \(d, m, v) ->-    it ("chain " <> cs d) $ runVector ctx m v+vectorSpec :: TestKey -> [TestVector] -> Spec+vectorSpec mTxt vecTxt =+  forM_ (parseVector mTxt vecTxt) $ \(d, m, v) ->+    it ("chain " <> cs d) $ runVector m v -runVector :: Ctx -> XPrvKey -> TestVector -> Assertion-runVector ctx m v = do-  assertBool "xPrvID" $ encodeHex ((runPutS . serialize) (xPrvID ctx m)) == head v-  assertBool "xPrvFP" $ encodeHex ((runPutS . serialize) (xPrvFP ctx m)) == v !! 1+runVector :: XPrvKey -> TestVector -> Assertion+runVector m v = do+  assertBool "xPrvID" $ encodeHex ((runPutS . serialize) (xPrvID m)) == head v+  assertBool "xPrvFP" $ encodeHex ((runPutS . serialize) (xPrvFP m)) == v !! 1   assertBool "xPrvAddr" $-    addrToText btc (xPubAddr ctx $ deriveXPubKey ctx m) == Just (v !! 2)+    addrToText btc (xPubAddr $ deriveXPubKey m) == Just (v !! 2)   assertBool "bip44Addr" $-    addrToText btc (xPubAddr ctx $ deriveXPubKey ctx $ derivePath ctx bip44Addr m)+    addrToText btc (xPubAddr $ deriveXPubKey $ derivePath bip44Addr m)       == Just (v !! 3)   assertBool "prvKey" $ encodeHex m.key.get == v !! 4   assertBool "xPrvWIF" $ xPrvWif btc m == v !! 5   assertBool "pubKey" $-    encodeHex (exportPubKey ctx True (deriveXPubKey ctx m).key) == v !! 6+    encodeHex (exportPubKey True (deriveXPubKey m).key) == v !! 6   assertBool "chain code" $ encodeHex (runPutS (serialize m.chain)) == v !! 7   assertBool "Hex PubKey" $-    encodeHex (marshal (btc, ctx) (deriveXPubKey ctx m)) == v !! 8+    encodeHex (marshal btc (deriveXPubKey m)) == v !! 8   assertBool "Hex PrvKey" $ encodeHex (marshal btc m) == v !! 9-  assertBool "Base58 PubKey" $ xPubExport btc ctx (deriveXPubKey ctx m) == v !! 10+  assertBool "Base58 PubKey" $ xPubExport btc (deriveXPubKey m) == v !! 10   assertBool "Base58 PrvKey" $ xPrvExport btc m == v !! 11  -- This function was used to generate addition data for the test vectors-genVector :: Ctx -> XPrvKey -> [(Text, Text)]-genVector ctx m =-  [ ("xPrvID", encodeHex (runPutS . serialize $ xPrvID ctx m)),-    ("xPrvFP", encodeHex (runPutS . serialize $ xPrvFP ctx m)),-    ("xPrvAddr", fromJust $ addrToText btc (xPubAddr ctx $ deriveXPubKey ctx m)),+genVector :: XPrvKey -> [(Text, Text)]+genVector m =+  [ ("xPrvID", encodeHex (runPutS . serialize $ xPrvID m)),+    ("xPrvFP", encodeHex (runPutS . serialize $ xPrvFP m)),+    ("xPrvAddr", fromJust $ addrToText btc (xPubAddr $ deriveXPubKey m)),     ( "bip44Addr",       fromJust $-        addrToText btc (xPubAddr ctx $ deriveXPubKey ctx $ derivePath ctx bip44Addr m)+        addrToText btc (xPubAddr $ deriveXPubKey $ derivePath bip44Addr m)     ),     ("prvKey", encodeHex m.key.get),     ("xPrvWIF", xPrvWif btc m),-    ("pubKey", encodeHex (exportPubKey ctx True (deriveXPubKey ctx m).key)),+    ("pubKey", encodeHex (exportPubKey True (deriveXPubKey m).key)),     ("chain code", encodeHex ((runPutS . serialize) m.chain)),-    ("Hex PubKey", encodeHex (marshal (btc, ctx) (deriveXPubKey ctx m))),+    ("Hex PubKey", encodeHex (marshal btc (deriveXPubKey m))),     ("Hex PrvKey", encodeHex (marshal btc m))   ] -parseVector :: Ctx -> TestKey -> [TestVector] -> [(Text, XPrvKey, TestVector)]-parseVector ctx mTxt vs =+parseVector :: TestKey -> [TestVector] -> [(Text, XPrvKey, TestVector)]+parseVector mTxt vs =   go <$> vs   where     mast = makeXPrvKey $ fromJust $ decodeHex mTxt     go (d : vec) =       let deriv = ((.get) . fromJust . parsePath) (cs d)-       in (d, derivePath ctx deriv mast, vec)+       in (d, derivePath deriv mast, vec)     go _ = undefined  type TestVector = [Text]
test/Haskoin/Crypto/Keys/Slip39Spec.hs view
@@ -90,7 +90,8 @@     it "is sorted" $       V.toList slip39WordList `shouldBe` sort (V.toList slip39WordList)     it "has words of 4 to 8 letters" $-      forM_ slip39WordList $ \w -> T.length w `shouldSatisfy` (\n -> n >= 4 && n <= 8)+      forM_ slip39WordList $+        \w -> T.length w `shouldSatisfy` (\n -> n >= 4 && n <= 8)     it "has distinct first four letters" $       length (nub (map (T.take 4) (V.toList slip39WordList))) `shouldBe` 1024     it "gives each word its index" $ do@@ -132,7 +133,8 @@       gfInv 0 `shouldBe` Nothing       gfDiv 1 0 `shouldBe` Nothing     it "multiplies every non-zero byte by its inverse to one" $-      forM_ [1 .. 255] $ \a -> (gfMul a <$> gfInv a) `shouldBe` Just 1+      forM_ [1 .. 255] $+        \a -> (gfMul a <$> gfInv a) `shouldBe` Just 1     it "divides 0xc1 by 0x83 to 0x57" $       gfDiv 0xc1 0x83 `shouldBe` Just 0x57 @@ -371,10 +373,11 @@       splitRandomSizes 2 16 `shouldBe` (0, 16, 12)       splitRandomSizes 5 32 `shouldBe` (3, 32, 28)     it "recovers any random secret from any threshold of its shares" $-      property $ forAll ((,) <$> bytesOf 16 <*> bytesOf 12) $ \(s, r) ->-        case splitSecret 2 3 s (SplitRandom [] r) of-          Right shares -> all ((== Right s) . recoverSecret 2) [two | two <- subsequences shares, length two == 2]-          Left _ -> False+      property $+        forAll ((,) <$> bytesOf 16 <*> bytesOf 12) $ \(s, r) ->+          case splitSecret 2 3 s (SplitRandom [] r) of+            Right shares -> all ((== Right s) . recoverSecret 2) [two | two <- subsequences shares, length two == 2]+            Left _ -> False    describe "the passphrase" $ do     let secret = "ABCDEFGHIJKLMNOP"@@ -447,8 +450,9 @@     it "shows an encrypted master secret without its ciphertext" $       show ems `shouldBe` "EncryptedMasterSecret {identifier = 7945, extendable = False, iterationExponent = 0, ciphertext = <redacted>}"     it "decrypts what it encrypts, for any secret and passphrase" $-      property $ forAll ((,) <$> bytesOf 16 <*> listOf (elements [' ' .. '~'])) $ \(s, p) ->-        (encryptMasterSecret 5 True 0 (T.pack p) s >>= decryptMasterSecret (T.pack p)) === Right s+      property $+        forAll ((,) <$> bytesOf 16 <*> listOf (elements [' ' .. '~'])) $ \(s, p) ->+          (encryptMasterSecret 5 True 0 (T.pack p) s >>= decryptMasterSecret (T.pack p)) === Right s    describe "generating shares" $ do     forM_ splitCases $ \c -> do@@ -530,22 +534,24 @@       draw (1, 2, 3, 4, 5) `shouldBe` draw (1, 2, 3, 4, 5)       draw (1, 2, 3, 4, 5) `shouldNotBe` draw (6, 7, 8, 9, 10)     it "rebuilds a secret of 16 to 64 bytes from a threshold of the shares of any small scheme" $-      property $ forAll splitOfAnyScheme $ \(scheme, ext, passphrase, secret, drawn) ->-        case drawn of-          Left err -> counterexample err False-          Right groups ->-            -- the first groups and the first members that meet the-            -- thresholds, then the last ones-            let firstOnes = concat [take t members | ((t, _), members) <- take scheme.groupThreshold (zip scheme.groups groups)]-                lastOnes = concat [lastN t members | ((t, _), members) <- lastN scheme.groupThreshold (zip scheme.groups groups)]-                rebuilt shares = combineShares shares >>= decryptMasterSecret passphrase-             in (rebuilt firstOnes, rebuilt lastOnes) === (Right secret, Right secret)+      property $+        forAll splitOfAnyScheme $ \(scheme, ext, passphrase, secret, drawn) ->+          case drawn of+            Left err -> counterexample err False+            Right groups ->+              -- the first groups and the first members that meet the+              -- thresholds, then the last ones+              let firstOnes = concat [take t members | ((t, _), members) <- take scheme.groupThreshold (zip scheme.groups groups)]+                  lastOnes = concat [lastN t members | ((t, _), members) <- lastN scheme.groupThreshold (zip scheme.groups groups)]+                  rebuilt shares = combineShares shares >>= decryptMasterSecret passphrase+               in (rebuilt firstOnes, rebuilt lastOnes) === (Right secret, Right secret)     it "refuses a share with one word of its value or checksum changed" $       -- the checksum catches any change of up to three words-      property $ forAll changedWord $ \(position, word) ->-        let ws = T.words (mnemonicOf vectors 1)-            changed = T.unwords (take position ws ++ [word] ++ drop (position + 1) ws)-         in ws !! position /= word ==> decodeShare changed === Left "The checksum of the mnemonic is invalid"+      property $+        forAll changedWord $ \(position, word) ->+          let ws = T.words (mnemonicOf vectors 1)+              changed = T.unwords (take position ws ++ [word] ++ drop (position + 1) ws)+           in ws !! position /= word ==> decodeShare changed === Left "The checksum of the mnemonic is invalid"     it "draws shares with the system's randomness that rebuild a two-level scheme" $ do       let secret = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"       drawn <- generateMnemonics (Scheme 2 [(1, 1), (2, 3), (3, 5)]) True 0 "pass" secret@@ -603,8 +609,9 @@         then it (T.unpack d <> ": gives the master secret and its BIP-32 key") $ do           combineMnemonics "TREZOR" ms `shouldBe` Right (hex secret)           xPrvExport btc (makeXPrvKey (hex secret)) `shouldBe` xprv-        else it (T.unpack d <> ": is refused") $-          combineMnemonics "TREZOR" ms `shouldBe` Left (refusalOf n)+        else+          it (T.unpack d <> ": is refused") $+            combineMnemonics "TREZOR" ms `shouldBe` Left (refusalOf n)  -- | A share made by version 0.3.0 of the reference implementation with the -- passphrase "café", from its tests. Its master secret is ABCDEFGHIJKLMNOP.@@ -711,9 +718,9 @@ thresholdSubsets :: SplitCase -> [[Text]] thresholdSubsets c =   [ concat members-    | chosen <- subsequences (zip (map fst c.caseScheme.groups) c.caseMnemonics),-      length chosen == c.caseScheme.groupThreshold,-      members <- mapM (\(threshold, ms) -> [ms' | ms' <- subsequences ms, length ms' == threshold]) chosen+  | chosen <- subsequences (zip (map fst c.caseScheme.groups) c.caseMnemonics),+    length chosen == c.caseScheme.groupThreshold,+    members <- mapM (\(threshold, ms) -> [ms' | ms' <- subsequences ms, length ms' == threshold]) chosen   ]  -- | A share of the given fields, decoded from its mnemonic for its value.
test/Haskoin/Crypto/KeysSpec.hs view
@@ -12,10 +12,10 @@ import Data.Aeson.Lens import Data.ByteString qualified as B import Data.ByteString.Char8 qualified as C-import Data.Char (isAsciiLower, isAsciiUpper, toLower, toUpper) import Data.Bytes.Get import Data.Bytes.Put import Data.Bytes.Serial+import Data.Char (isAsciiLower, isAsciiUpper, toLower, toUpper) import Data.Default (def) import Data.Either (isLeft) import Data.List (isInfixOf)@@ -38,55 +38,58 @@ import Test.Hspec.QuickCheck import Test.QuickCheck -identityTests :: Ctx -> IdentityTests-identityTests ctx =+identityTests :: IdentityTests+identityTests =   def     { readTests =-        [ ReadBox (arbitrary :: Gen SecKey),-          ReadBox (arbitraryPublicKey ctx)+        [ ReadBox arbitraryPublicKey         ],+      jsonTests =+        [ JsonBox arbitraryPublicKey+        ],       marshalJsonTests =-        [ MarshalJsonBox $ (,) <$> arbitraryNetwork <*> arbitraryPrivateKey,-          MarshalJsonBox ((,) ctx <$> arbitraryPublicKey ctx)+        [ MarshalJsonBox $ (,) <$> arbitraryNetwork <*> arbitraryPrivateKey         ],       serialTests =-        [ SerialBox arbitraryPrivateKey-        ],-      marshalTests =-        [ MarshalBox ((,) ctx <$> arbitraryPublicKey ctx)+        [ SerialBox arbitraryPrivateKey,+          SerialBox arbitraryPublicKey         ]     }  spec :: Spec-spec = prepareContext $ \ctx -> do+spec = do   describe "Key pair property checks" $ do-    testIdentity $ identityTests ctx+    testIdentity $ identityTests     prop "a compressed key is written in 33 bytes starting with 02 or 03, an uncompressed key in 65 bytes starting with 04" $-      forAll (arbitraryKeyPair ctx) $ \(_, pub) ->-        let bytes = marshal ctx pub+      forAll arbitraryKeyPair $ \(_, pub) ->+        let bytes = encodeSerial pub          in if pub.compress               then B.length bytes == 33 && B.head bytes `elem` [0x02, 0x03]               else B.length bytes == 65 && B.head bytes == 0x04+    prop "a secret key is not shown, and is still read from its hex" $+      forAll (arbitrary :: Gen SecKey) $ \sec -> do+        show sec `shouldBe` "SecKey <redacted>"+        read (show (encodeHex sec.get)) `shouldBe` sec     prop "Public key show . read identity" $-      forAll (arbitraryKeyPair ctx) $ \(_, pub) ->+      forAll arbitraryKeyPair $ \(_, pub) ->         (read . show) pub == pub     prop "Public key binary serialization" $ do-      forAll (arbitraryKeyPair ctx) $ \(sec, pub) ->-        (unmarshal ctx . marshal ctx) pub == Right pub+      forAll arbitraryKeyPair $ \(sec, pub) ->+        (decodeSerial . encodeSerial) pub == Right pub     prop "fromWif . toWif identity" $       forAll arbitraryNetwork $ \net ->-        forAll (arbitraryKeyPair ctx) $ \(key, _) ->+        forAll arbitraryKeyPair $ \(key, _) ->           (fromWif net . toWif net) key == Just key     prop "WIF binary identity" $       forAll arbitraryNetwork $ \net ->-        forAll (arbitraryKeyPair ctx) $ \(key, _) ->+        forAll arbitraryKeyPair $ \(key, _) ->           (runGetS deserialize . runPutS . serialize) key == Right key   describe "Bitcoin core vectors /src/test/key_tests.cpp" $ do     it "Passes WIF decoding tests" testPrivkey     it "Passes SecKey compression tests" testPrvKeyCompressed-    it "Passes PubKey compression tests" $ testKeyCompressed ctx-    it "Passes address matching tests" $ testMatchingAddress ctx-    it "Passes signature verification" $ testSigs ctx+    it "Passes PubKey compression tests" $ testKeyCompressed+    it "Passes address matching tests" $ testMatchingAddress+    it "Passes signature verification" $ testSigs   describe "MiniKey vectors" $     it "Passes MiniKey decoding tests" testMiniKey   describe "Secret key range" $ do@@ -163,46 +166,44 @@       fromMiniKey "0OIl_______________607" `shouldBe` Nothing   describe "Key tweaks" $ do     it "adding a zero tweak leaves the secret key unchanged" $-      tweakSecKey ctx secKey1 zeroHash `shouldBe` Just secKey1+      tweakSecKey secKey1 zeroHash `shouldBe` Just secKey1     it "adding one to secret key 1 gives secret key 2" $-      tweakSecKey ctx secKey1 oneHash+      tweakSecKey secKey1 oneHash         `shouldBe` Just "0000000000000000000000000000000000000000000000000000000000000002"     it "refuses a tweak that brings the secret key to zero" $       -- 1 + (n - 1) = n, which is 0 modulo n-      tweakSecKey ctx secKey1 orderMinusOneHash `shouldBe` Nothing+      tweakSecKey secKey1 orderMinusOneHash `shouldBe` Nothing     it "refuses a tweak at or above the curve order" $-      tweakSecKey ctx secKey1 orderHash `shouldBe` Nothing+      tweakSecKey secKey1 orderHash `shouldBe` Nothing     it "adding one to the public key of 1 gives the public key of 2" $-      tweakPubKey ctx (pubKey1 ctx) oneHash `shouldBe` Just (pubKey2 ctx)+      tweakPubKey pubKey1 oneHash `shouldBe` Just pubKey2     it "refuses a tweak that brings the public key to infinity" $-      tweakPubKey ctx (pubKey1 ctx) orderMinusOneHash `shouldBe` Nothing+      tweakPubKey pubKey1 orderMinusOneHash `shouldBe` Nothing     prop "tweaking the public key matches tweaking the secret key" $       forAll arbitraryPrivateKey $ \k ->         forAll arbitraryHash256 $ \t ->-          (derivePubKey ctx <$> tweakSecKey ctx k.key t)-            == tweakPubKey ctx (derivePubKey ctx k.key) t+          (derivePubKey <$> tweakSecKey k.key t)+            == tweakPubKey (derivePubKey k.key) t   describe "Public key text forms" $ do     it "parses a compressed public key from JSON" $-      unmarshalJSON ctx "\"0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\""-        `shouldBe` Just (wrapPubKey True (pubKey1 ctx))+      A.decode "\"0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\""+        `shouldBe` Just (wrapPubKey True pubKey1)     it "parses an uncompressed public key from JSON" $-      unmarshalJSON-        ctx+      A.decode         "\"0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\         \483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8\""-        `shouldBe` Just (wrapPubKey False (pubKey1 ctx))+        `shouldBe` Just (wrapPubKey False pubKey1)     it "refuses a public key with trailing bytes" $-      (unmarshalJSON ctx "\"0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798deadbeef\"" :: Maybe PublicKey)+      (A.decode "\"0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798deadbeef\"" :: Maybe PublicKey)         `shouldBe` Nothing     it "refuses a public key with an unknown prefix byte" $-      (unmarshalJSON ctx "\"0579be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\"" :: Maybe PublicKey)+      (A.decode "\"0579be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\"" :: Maybe PublicKey)         `shouldBe` Nothing     it "refuses a hybrid public key" $       -- 06, then x and the even y of the public key of 1. Consensus takes       -- this form, the relay rules of Bitcoin Core do not, and this library       -- reads keys in the two standard forms only.-      ( unmarshalJSON-          ctx+      ( A.decode           "\"0679be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\           \483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8\"" ::           Maybe PublicKey@@ -210,7 +211,7 @@         `shouldBe` Nothing     it "refuses a point that is not on the curve" $       -- the invalid public key of BIP32 test vector 5-      (unmarshalJSON ctx "\"020000000000000000000000000000000000000000000000000000000000000007\"" :: Maybe PublicKey)+      (A.decode "\"020000000000000000000000000000000000000000000000000000000000000007\"" :: Maybe PublicKey)         `shouldBe` Nothing   describe "Binary private key" $ do     it "is the 32 bytes of the key, then 01 for a compressed public key or 00" $ do@@ -240,7 +241,7 @@       length valid `shouldBe` 70       length invalid `shouldBe` 70     it "reads and writes every valid private key and address" $-      mapM_ (testKeyIOValidVector ctx) valid+      mapM_ testKeyIOValidVector valid     it "refuses every invalid string as an address and as a private key, on every network" $       mapM_ testKeyIOInvalidVector invalid @@ -252,9 +253,9 @@ secKey1 = "0000000000000000000000000000000000000000000000000000000000000001"  -- | Public keys of the secret keys 1 and 2, that is G and 2G.-pubKey1, pubKey2 :: Ctx -> PubKey-pubKey1 ctx = fromJust $ importPubKey ctx $ hex "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"-pubKey2 ctx = fromJust $ importPubKey ctx $ hex "02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"+pubKey1, pubKey2 :: PubKey+pubKey1 = fromJust $ importPubKey $ hex "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"+pubKey2 = fromJust $ importPubKey $ hex "02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"  -- | Tweaks of 0, 1, n - 1 and n, where n is the curve order. zeroHash, oneHash, orderMinusOneHash, orderHash :: Hash256@@ -275,8 +276,8 @@  -- | One valid vector: a string, the bytes it stands for and its chain. For a -- private key the bytes are the secret, for an address the output script.-testKeyIOValidVector :: Ctx -> (Text, Text, A.Value) -> Assertion-testKeyIOValidVector ctx (string, payload, metadata)+testKeyIOValidVector :: (Text, Text, A.Value) -> Assertion+testKeyIOValidVector (string, payload, metadata)   | isPrivkey = do       let compressed = metadata ^?! key "isCompressed" . _Bool           secret = fromMaybe (error "bad secret in the vector file") (secKey (hex payload))@@ -296,17 +297,17 @@       assertEqual         ("the address " <> cs string <> " pays to the script")         (Just payload)-        (encodeHex <$> (addressToScriptBS ctx =<< textToAddr net string))+        (encodeHex <$> (addressToScriptBS =<< textToAddr net string))       assertEqual         ("the script is written as the address " <> cs string)         (Just string)-        (addrToText net =<< eitherToMaybe (scriptToAddressBS net ctx (hex payload)))+        (addrToText net =<< eitherToMaybe (scriptToAddressBS net (hex payload)))       -- With the case of every letter flipped, a Bech32 address reads the       -- same and a Base58 address does not read       assertEqual         ("the address " <> cs string <> " with its case flipped")         (if tryCaseFlip then Just payload else Nothing)-        (encodeHex <$> (addressToScriptBS ctx =<< textToAddr net (flipCase string)))+        (encodeHex <$> (addressToScriptBS =<< textToAddr net (flipCase string)))       assertEqual         ("the address " <> cs string <> " is not a private key")         Nothing@@ -366,22 +367,22 @@   assertBool "Key 1C" sec1C.compress   assertBool "Key 2C" sec2C.compress -testKeyCompressed :: Ctx -> Assertion-testKeyCompressed ctx = do-  assertBool "Key 1" $ not (pub1 ctx).compress-  assertBool "Key 2" $ not (pub2 ctx).compress-  assertBool "Key 1C" (pub1C ctx).compress-  assertBool "Key 2C" (pub2C ctx).compress+testKeyCompressed :: Assertion+testKeyCompressed = do+  assertBool "Key 1" $ not pub1.compress+  assertBool "Key 2" $ not pub2.compress+  assertBool "Key 1C" pub1C.compress+  assertBool "Key 2C" pub2C.compress -testMatchingAddress :: Ctx -> Assertion-testMatchingAddress ctx = do-  assertEqual "Key 1" (Just addr1) $ addrToText btc (pubKeyAddr ctx (pub1 ctx))-  assertEqual "Key 2" (Just addr2) $ addrToText btc (pubKeyAddr ctx (pub2 ctx))-  assertEqual "Key 1C" (Just addr1C) $ addrToText btc (pubKeyAddr ctx (pub1C ctx))-  assertEqual "Key 2C" (Just addr2C) $ addrToText btc (pubKeyAddr ctx (pub2C ctx))+testMatchingAddress :: Assertion+testMatchingAddress = do+  assertEqual "Key 1" (Just addr1) $ addrToText btc (pubKeyAddr pub1)+  assertEqual "Key 2" (Just addr2) $ addrToText btc (pubKeyAddr pub2)+  assertEqual "Key 1C" (Just addr1C) $ addrToText btc (pubKeyAddr pub1C)+  assertEqual "Key 2C" (Just addr2C) $ addrToText btc (pubKeyAddr pub2C) -testSigs :: Ctx -> Assertion-testSigs ctx = forM_ sigMsg $ testSignature ctx . doubleSHA256+testSigs :: Assertion+testSigs = forM_ sigMsg $ testSignature . doubleSHA256  sigMsg :: [B.ByteString] sigMsg =@@ -389,28 +390,28 @@   | i <- [0 .. 15]   ] -testSignature :: Ctx -> Hash256 -> Assertion-testSignature ctx h = do-  let sign1 = signHash ctx sec1.key h-      sign2 = signHash ctx sec2.key h-      sign1C = signHash ctx sec1C.key h-      sign2C = signHash ctx sec2C.key h-  assertBool "Key 1, Sign1" $ verifyHashSig ctx h sign1 (pub1 ctx).point-  assertBool "Key 1, Sign2" $ not $ verifyHashSig ctx h sign2 (pub1 ctx).point-  assertBool "Key 1, Sign1C" $ verifyHashSig ctx h sign1C (pub1 ctx).point-  assertBool "Key 1, Sign2C" $ not $ verifyHashSig ctx h sign2C (pub1 ctx).point-  assertBool "Key 2, Sign1" $ not $ verifyHashSig ctx h sign1 (pub2 ctx).point-  assertBool "Key 2, Sign2" $ verifyHashSig ctx h sign2 (pub2 ctx).point-  assertBool "Key 2, Sign1C" $ not $ verifyHashSig ctx h sign1C (pub2 ctx).point-  assertBool "Key 2, Sign2C" $ verifyHashSig ctx h sign2C (pub2 ctx).point-  assertBool "Key 1C, Sign1" $ verifyHashSig ctx h sign1 (pub1C ctx).point-  assertBool "Key 1C, Sign2" $ not $ verifyHashSig ctx h sign2 (pub1C ctx).point-  assertBool "Key 1C, Sign1C" $ verifyHashSig ctx h sign1C (pub1C ctx).point-  assertBool "Key 1C, Sign2C" $ not $ verifyHashSig ctx h sign2C (pub1C ctx).point-  assertBool "Key 2C, Sign1" $ not $ verifyHashSig ctx h sign1 (pub2C ctx).point-  assertBool "Key 2C, Sign2" $ verifyHashSig ctx h sign2 (pub2C ctx).point-  assertBool "Key 2C, Sign1C" $ not $ verifyHashSig ctx h sign1C (pub2C ctx).point-  assertBool "Key 2C, Sign2C" $ verifyHashSig ctx h sign2C (pub2C ctx).point+testSignature :: Hash256 -> Assertion+testSignature h = do+  let sign1 = signHash sec1.key h+      sign2 = signHash sec2.key h+      sign1C = signHash sec1C.key h+      sign2C = signHash sec2C.key h+  assertBool "Key 1, Sign1" $ verifyHashSig h sign1 pub1.point+  assertBool "Key 1, Sign2" $ not $ verifyHashSig h sign2 pub1.point+  assertBool "Key 1, Sign1C" $ verifyHashSig h sign1C pub1.point+  assertBool "Key 1, Sign2C" $ not $ verifyHashSig h sign2C pub1.point+  assertBool "Key 2, Sign1" $ not $ verifyHashSig h sign1 pub2.point+  assertBool "Key 2, Sign2" $ verifyHashSig h sign2 pub2.point+  assertBool "Key 2, Sign1C" $ not $ verifyHashSig h sign1C pub2.point+  assertBool "Key 2, Sign2C" $ verifyHashSig h sign2C pub2.point+  assertBool "Key 1C, Sign1" $ verifyHashSig h sign1 pub1C.point+  assertBool "Key 1C, Sign2" $ not $ verifyHashSig h sign2 pub1C.point+  assertBool "Key 1C, Sign1C" $ verifyHashSig h sign1C pub1C.point+  assertBool "Key 1C, Sign2C" $ not $ verifyHashSig h sign2C pub1C.point+  assertBool "Key 2C, Sign1" $ not $ verifyHashSig h sign1 pub2C.point+  assertBool "Key 2C, Sign2" $ verifyHashSig h sign2 pub2C.point+  assertBool "Key 2C, Sign1C" $ not $ verifyHashSig h sign1C pub2C.point+  assertBool "Key 2C, Sign2C" $ verifyHashSig h sign2C pub2C.point  strSecret1, strSecret2, strSecret1C, strSecret2C :: Text strSecret1 = "5HxWvvfubhXpYYpS3tJkw6fq9jE9j18THftkZjHHfmFiWtmAbrj"@@ -433,8 +434,8 @@ strAddressBad :: Text strAddressBad = "1HV9Lc3sNHZxwj4Zk6fB38tEmBryq2cBiF" -pub1, pub2, pub1C, pub2C :: Ctx -> PublicKey-pub1 ctx = derivePublicKey ctx sec1-pub2 ctx = derivePublicKey ctx sec2-pub1C ctx = derivePublicKey ctx sec1C-pub2C ctx = derivePublicKey ctx sec2C+pub1, pub2, pub1C, pub2C :: PublicKey+pub1 = derivePublicKey sec1+pub2 = derivePublicKey sec2+pub1C = derivePublicKey sec1C+pub2C = derivePublicKey sec2C
test/Haskoin/Crypto/SignatureSpec.hs view
@@ -6,10 +6,10 @@  import Control.Monad import Data.Aeson qualified as A+import Data.Aeson.Types qualified as A (parseEither) import Data.Bits (testBit) import Data.ByteString (ByteString) import Data.ByteString qualified as BS-import Data.Aeson.Types qualified as A (parseEither) import Data.Either (isLeft) import Data.List (isInfixOf) import Data.Map.Strict (Map)@@ -31,144 +31,144 @@ import Test.QuickCheck  spec :: Spec-spec = prepareContext $ \ctx -> do-  cashSchnorrSpec ctx+spec = do+  cashSchnorrSpec   describe "Signature property checks" $ do     prop "verifies signature" $-      forAll (arbitrarySignature ctx) $ \(m, key', sig) ->-        verifyHashSig ctx m sig (derivePubKey ctx key')+      forAll arbitrarySignature $ \(m, key', sig) ->+        verifyHashSig m sig (derivePubKey key')     prop "s component less than half order" $-      forAll (arbitrarySignature ctx) $-        isCanonicalHalfOrder ctx . lst3+      forAll arbitrarySignature $+        isCanonicalHalfOrder . lst3     prop "encoded signature is canonical" $-      forAll (arbitrarySignature ctx) $-        testIsCanonical ctx . lst3+      forAll arbitrarySignature $+        testIsCanonical . lst3     prop "decodeStrictSig . exportSig identity" $-      forAll (arbitrarySignature ctx) $-        (\s -> decodeStrictSig ctx (exportSig ctx s) == Just s) . lst3+      forAll arbitrarySignature $+        (\s -> decodeStrictSig (exportSig s) == Just s) . lst3     prop "importSig . exportSig identity" $-      forAll (arbitrarySignature ctx) $-        (\s -> importSig ctx (exportSig ctx s) == Just s) . lst3+      forAll arbitrarySignature $+        (\s -> importSig (exportSig s) == Just s) . lst3     prop "signature JSON identity" $-      forAll (arbitrarySignature ctx) $-        (\s -> (unmarshalJSON ctx . marshalJSON ctx) s == Just s) . lst3+      forAll arbitrarySignature $+        (\s -> (A.decode . A.encode) s == Just s) . lst3     prop "getSig . putSig identity" $-      forAll (arbitrarySignature ctx) $-        (\s -> unmarshal ctx (marshal ctx s) == Right s) . lst3+      forAll arbitrarySignature $+        (\s -> decodeSerial (encodeSerial s) == Right s) . lst3   describe "Signature vectors" $ do     it "passes RFC6979 test vectors" $-      checkDistSig ctx $ \file1 file2 -> do+      checkDistSig $ \file1 file2 -> do         vectors <- readTestFile file1 :: IO [(Text, Text, Text)]         vectorsDER <- readTestFile file2 :: IO [(Text, Text, Text)]-        mapM_ (testRFC6979Vector ctx . toVector) vectors-        mapM_ (testRFC6979DERVector ctx . toVector) vectorsDER+        mapM_ (testRFC6979Vector . toVector) vectors+        mapM_ (testRFC6979DERVector . toVector) vectorsDER   describe "BIP143 signature vectors" $ do     it "agrees with BIP143 p2wpkh example" $-      testBip143p2wpkh ctx+      testBip143p2wpkh     it "agrees with BIP143 p2sh-p2wpkh example" $-      testBip143p2shp2wpkh ctx+      testBip143p2shp2wpkh     it "builds a p2wsh multisig transaction" $-      testP2WSHMulsig ctx+      testP2WSHMulsig     it "agrees with BIP143 p2sh-p2wsh multisig example" $-      testBip143p2shp2wpkhMulsig ctx+      testBip143p2shp2wpkhMulsig   describe "Strict signature decoding" $ do     it "accepts the smallest signature, r = 1 and s = 1" $       -- DER: 30 06 | 02 01 01 | 02 01 01-      fmap (exportSig ctx) (decodeStrictSig ctx (hex "3006020101020101"))+      fmap exportSig (decodeStrictSig (hex "3006020101020101"))         `shouldBe` Just (hex "3006020101020101")     it "refuses a signature whose r is zero" $-      decodeStrictSig ctx (hex "3006020100020101") `shouldBe` Nothing+      decodeStrictSig (hex "3006020100020101") `shouldBe` Nothing     it "refuses a signature whose s is zero" $-      decodeStrictSig ctx (hex "3006020101020100") `shouldBe` Nothing+      decodeStrictSig (hex "3006020101020100") `shouldBe` Nothing     -- BIP 66 is about the encoding only. Low S is a relay rule of Bitcoin     -- Core (SCRIPT_VERIFY_LOW_S), not a consensus rule.     it "accepts a signature whose s is n - 1, above half the curve order" $ do       -- DER: 30 26 | 02 01 01 | 02 21 00 <n - 1>, 3 + 2 + 33 = 38 = 0x26 bytes       let der = hex "3026020101022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"-      fmap (exportSig ctx) (decodeStrictSig ctx der) `shouldBe` Just der-      fmap (isCanonicalHalfOrder ctx) (decodeStrictSig ctx der) `shouldBe` Just False+      fmap exportSig (decodeStrictSig der) `shouldBe` Just der+      fmap isCanonicalHalfOrder (decodeStrictSig der) `shouldBe` Just False     prop "accepts the high-S form of any signature" $-      forAll (arbitrarySignature ctx) $ \(_, _, s) ->-        decodeStrictSig ctx (exportSig ctx (highSVariant ctx s)) == Just (highSVariant ctx s)+      forAll arbitrarySignature $ \(_, _, s) ->+        decodeStrictSig (exportSig (highSVariant s)) == Just (highSVariant s)     it "accepts an r that needs a leading zero byte" $       -- r = 0x80 is written 00 80, since 80 alone would be negative-      fmap (exportSig ctx) (decodeStrictSig ctx (hex "300702020080020101"))+      fmap exportSig (decodeStrictSig (hex "300702020080020101"))         `shouldBe` Just (hex "300702020080020101")     it "refuses a negative r or s" $ do-      decodeStrictSig ctx (hex "3006020181020101") `shouldBe` Nothing-      decodeStrictSig ctx (hex "3006020101020181") `shouldBe` Nothing+      decodeStrictSig (hex "3006020181020101") `shouldBe` Nothing+      decodeStrictSig (hex "3006020101020181") `shouldBe` Nothing     it "refuses an r or s with a leading zero byte that is not needed" $ do-      decodeStrictSig ctx (hex "300702020001020101") `shouldBe` Nothing-      decodeStrictSig ctx (hex "300702010102020001") `shouldBe` Nothing+      decodeStrictSig (hex "300702020001020101") `shouldBe` Nothing+      decodeStrictSig (hex "300702010102020001") `shouldBe` Nothing     it "refuses an r or s of no bytes" $ do-      decodeStrictSig ctx (hex "30050200020101") `shouldBe` Nothing-      decodeStrictSig ctx (hex "30050201010200") `shouldBe` Nothing+      decodeStrictSig (hex "30050200020101") `shouldBe` Nothing+      decodeStrictSig (hex "30050201010200") `shouldBe` Nothing     it "refuses an r or s that is not tagged as an integer" $ do-      decodeStrictSig ctx (hex "3006030101020101") `shouldBe` Nothing-      decodeStrictSig ctx (hex "3006020101030101") `shouldBe` Nothing+      decodeStrictSig (hex "3006030101020101") `shouldBe` Nothing+      decodeStrictSig (hex "3006020101030101") `shouldBe` Nothing     it "refuses a sequence whose length is not that of its content" $ do-      decodeStrictSig ctx (hex "3005020101020101") `shouldBe` Nothing-      decodeStrictSig ctx (hex "3007020101020101") `shouldBe` Nothing+      decodeStrictSig (hex "3005020101020101") `shouldBe` Nothing+      decodeStrictSig (hex "3007020101020101") `shouldBe` Nothing     it "refuses a byte after the sequence" $-      decodeStrictSig ctx (hex "300602010102010100") `shouldBe` Nothing+      decodeStrictSig (hex "300602010102010100") `shouldBe` Nothing     it "refuses a length written in the long form" $-      decodeStrictSig ctx (hex "308106020101020101") `shouldBe` Nothing+      decodeStrictSig (hex "308106020101020101") `shouldBe` Nothing     it "refuses no bytes at all" $-      decodeStrictSig ctx "" `shouldBe` Nothing+      decodeStrictSig "" `shouldBe` Nothing     it "refuses an r at the curve order, which BIP 66 allows but which can never verify" $       -- DER: 30 26 | 02 21 00 <n> | 02 01 01-      decodeStrictSig ctx (hex "3026022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141020101")+      decodeStrictSig (hex "3026022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141020101")         `shouldBe` Nothing   describe "Binary signature decoding" $ do     it "decodes the smallest signature" $-      fmap (exportSig ctx) (unmarshal ctx (hex "3006020101020101"))+      fmap exportSig (decodeSerial (hex "3006020101020101"))         `shouldBe` Right (hex "3006020101020101")     it "refuses an identifier byte other than 0x30" $-      (unmarshal ctx (hex "3106020101020101") :: Either String Sig) `shouldSatisfy` isLeft+      (decodeSerial (hex "3106020101020101") :: Either String Sig) `shouldSatisfy` isLeft     it "refuses the indefinite length form" $-      (unmarshal ctx (hex "3000020101020101") :: Either String Sig) `shouldSatisfy` isLeft+      (decodeSerial (hex "3000020101020101") :: Either String Sig) `shouldSatisfy` isLeft     it "refuses a length of more than one byte" $-      (unmarshal ctx (hex "308106020101020101") :: Either String Sig) `shouldSatisfy` isLeft+      (decodeSerial (hex "308106020101020101") :: Either String Sig) `shouldSatisfy` isLeft     it "refuses a signature cut short" $-      (unmarshal ctx (hex "3006020101") :: Either String Sig) `shouldSatisfy` isLeft+      (decodeSerial (hex "3006020101") :: Either String Sig) `shouldSatisfy` isLeft     it "refuses bytes after the signature" $-      (unmarshal ctx (hex "300602010102010100ffff") :: Either String Sig)+      (decodeSerial (hex "300602010102010100ffff") :: Either String Sig)         `shouldSatisfy` either ("bytes left over" `isInfixOf`) (const False)     it "decodes a signature whose s is n - 1" $-      fmap (exportSig ctx) (unmarshal ctx (hex "3026020101022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"))+      fmap exportSig (decodeSerial (hex "3026020101022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"))         `shouldBe` Right (hex "3026020101022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140")   describe "Signature JSON" $ do     prop "reads a high-S signature, like the binary form" $-      forAll (arbitrarySignature ctx) $ \(_, _, s) ->-        (unmarshalJSON ctx (A.encode (encodeHex (exportSig ctx (highSVariant ctx s)))) :: Maybe Sig)-          == Just (highSVariant ctx s)+      forAll arbitrarySignature $ \(_, _, s) ->+        (A.decode (A.encode (encodeHex (exportSig (highSVariant s)))) :: Maybe Sig)+          == Just (highSVariant s)     it "refuses a signature whose r is zero, like the binary form" $-      (unmarshalJSON ctx "\"3006020100020101\"" :: Maybe Sig) `shouldBe` Nothing+      (A.decode "\"3006020100020101\"" :: Maybe Sig) `shouldBe` Nothing     it "refuses a signature that is not hex" $-      (unmarshalJSON ctx "\"zz\"" :: Maybe Sig) `shouldBe` Nothing+      (A.decode "\"zz\"" :: Maybe Sig) `shouldBe` Nothing     it "does not copy the text it refuses into its error message" $-      (A.parseEither (unmarshalValue ctx) (A.String "zz-attacker-text") :: Either String Sig)+      (A.parseEither A.parseJSON (A.String "zz-attacker-text") :: Either String Sig)         `shouldBe` Left "Error in $: Could not decode signature"   describe "High-S signatures" $ do     prop "are not in canonical half order" $-      forAll (arbitrarySignature ctx) $ \(_, _, s) ->-        not (isCanonicalHalfOrder ctx (highSVariant ctx s))+      forAll arbitrarySignature $ \(_, _, s) ->+        not (isCanonicalHalfOrder (highSVariant s))     prop "still verify after normalisation, as in Bitcoin Core" $-      forAll (arbitrarySignature ctx) $ \(m, key', s) ->-        verifyHashSig ctx m (highSVariant ctx s) (derivePubKey ctx key')+      forAll arbitrarySignature $ \(m, key', s) ->+        verifyHashSig m (highSVariant s) (derivePubKey key')     prop "a signature does not verify for another message" $-      forAll (arbitrarySignature ctx) $ \(m, key', s) ->+      forAll arbitrarySignature $ \(m, key', s) ->         forAll arbitraryHash256 $ \other ->-          other /= m ==> not (verifyHashSig ctx other s (derivePubKey ctx key'))+          other /= m ==> not (verifyHashSig other s (derivePubKey key'))   describe "Bitcoin Core deterministic signature vectors" $     it "signs 'Very deterministic message' as Bitcoin Core does" $-      case getImpl ctx of+      case getImpl of         Just ImplCore -> do           let h = doubleSHA256 ("Very deterministic message" :: ByteString)-          encodeHex (exportSig ctx (signHash ctx coreKey1 h))+          encodeHex (exportSig (signHash coreKey1 h))             `shouldBe` "304402205dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d\                        \022014ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"-          encodeHex (exportSig ctx (signHash ctx coreKey2 h))+          encodeHex (exportSig (signHash coreKey2 h))             `shouldBe` "3044022052d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd5\                        \022061d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d"         _ -> pendingWith "the vector is for the nonce function of Bitcoin Core"@@ -183,19 +183,19 @@  -- | The same signature with s replaced by n - s. It verifies as well, but it -- is not in the low-S form that BIP62 requires.-highSVariant :: Ctx -> Sig -> Sig-highSVariant ctx s =-  fromJust $ importCompactSig ctx $ fromJust $ compactSig (r <> highS)+highSVariant :: Sig -> Sig+highSVariant s =+  fromJust $ importCompactSig $ fromJust $ compactSig (r <> highS)   where-    (r, lowS) = BS.splitAt 32 (exportCompactSig ctx s).get+    (r, lowS) = BS.splitAt 32 (exportCompactSig s).get     n = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141     highS = padTo32 (integerToBS (n - bsToInteger lowS))     padTo32 bs = BS.replicate (32 - BS.length bs) 0 <> bs  -- github.com/bitcoin/bitcoin/blob/master/src/script.cpp -- from function IsCanonicalSignature-testIsCanonical :: Ctx -> Sig -> Bool-testIsCanonical ctx sig =+testIsCanonical :: Sig -> Bool+testIsCanonical sig =   not $     -- Non-canonical signature: too short     (len < 8)@@ -245,7 +245,7 @@           && not (testBit (BS.index s (fromIntegral rlen + 7)) 7)       )   where-    s = exportSig ctx sig+    s = exportSig sig     len = fromIntegral $ BS.length s     rlen = BS.index s 3     slen = BS.index s (fromIntegral rlen + 5)@@ -259,12 +259,11 @@   = ImplCore   | ImplCash -implSig :: Ctx -> Text-implSig ctx =+implSig :: Text+implSig =   encodeHex $-    exportSig ctx $+    exportSig $       signMsg-        ctx         "0000000000000000000000000000000000000000000000000000000000000001"         "0000000000000000000000000000000000000000000000000000000000000000" @@ -284,16 +283,16 @@       )     ] -getImpl :: Ctx -> Maybe ValidImpl-getImpl ctx = implSig ctx `Map.lookup` validImplMap+getImpl :: Maybe ValidImpl+getImpl = implSig `Map.lookup` validImplMap  rfc6979files :: ValidImpl -> (FilePath, FilePath) rfc6979files ImplCore = ("rfc6979core.json", "rfc6979DERcore.json") rfc6979files ImplCash = ("rfc6979cash.json", "rfc6979DERcash.json") -checkDistSig :: Ctx -> (FilePath -> FilePath -> Assertion) -> Assertion-checkDistSig ctx go =-  case rfc6979files <$> getImpl ctx of+checkDistSig :: (FilePath -> FilePath -> Assertion) -> Assertion+checkDistSig go =+  case rfc6979files <$> getImpl of     Just (file1, file2) -> go file1 file2     _ -> assertFailure "invalid RFC6979 signature" @@ -303,33 +302,33 @@ toVector :: (Text, Text, Text) -> (SecKey, ByteString, Text) toVector (prv, m, res) = (fromJust $ (secKey <=< decodeHex) prv, cs m, res) -testRFC6979Vector :: Ctx -> (SecKey, ByteString, Text) -> Assertion-testRFC6979Vector ctx (prv, m, res) = do-  assertEqual "RFC 6979 Vector" res (encodeHex (exportCompactSig ctx s).get)-  assertBool "Signature is valid" $ verifyHashSig ctx h s (derivePubKey ctx prv)-  assertBool "Signature is canonical" $ testIsCanonical ctx s-  assertBool "Signature is normalized" $ isCanonicalHalfOrder ctx s+testRFC6979Vector :: (SecKey, ByteString, Text) -> Assertion+testRFC6979Vector (prv, m, res) = do+  assertEqual "RFC 6979 Vector" res (encodeHex (exportCompactSig s).get)+  assertBool "Signature is valid" $ verifyHashSig h s (derivePubKey prv)+  assertBool "Signature is canonical" $ testIsCanonical s+  assertBool "Signature is normalized" $ isCanonicalHalfOrder s   where     h = sha256 m-    s = signHash ctx prv h+    s = signHash prv h  -- Test vectors from: -- https://crypto.stackexchange.com/questions/20838/request-for-data-to-test-deterministic-ecdsa-signature-algorithm-for-secp256k1 -testRFC6979DERVector :: Ctx -> (SecKey, ByteString, Text) -> Assertion-testRFC6979DERVector ctx (prv, m, res) = do-  assertEqual "RFC 6979 DER Vector" res (encodeHex $ exportSig ctx s)-  assertBool "DER Signature is valid" $ verifyHashSig ctx h s (derivePubKey ctx prv)-  assertBool "DER Signature is canonical" $ testIsCanonical ctx s-  assertBool "DER Signature is normalized" $ isCanonicalHalfOrder ctx s+testRFC6979DERVector :: (SecKey, ByteString, Text) -> Assertion+testRFC6979DERVector (prv, m, res) = do+  assertEqual "RFC 6979 DER Vector" res (encodeHex $ exportSig s)+  assertBool "DER Signature is valid" $ verifyHashSig h s (derivePubKey prv)+  assertBool "DER Signature is canonical" $ testIsCanonical s+  assertBool "DER Signature is normalized" $ isCanonicalHalfOrder s   where     h = sha256 m-    s = signHash ctx prv h+    s = signHash prv h  -- Reproduce the P2WPKH example from BIP 143-testBip143p2wpkh :: Ctx -> Assertion-testBip143p2wpkh ctx =-  case getImpl ctx of+testBip143p2wpkh :: Assertion+testBip143p2wpkh =+  case getImpl of     Just ImplCore ->       assertEqual "BIP143 Core p2wpkh" (Right signedTxCore) generatedSignedTx     Just ImplCash ->@@ -369,20 +368,20 @@     Just key0 =       secHexKey         "bbc27228ddcb9209d7fd6f36b02f7dfa6252af40bb2f1cbc7a557da8027ff866"-    pubKey0 = toPubKey ctx key0+    pubKey0 = toPubKey key0     Just key1 =       secHexKey         "619c335025c7f4012e556c2a58b2506e30b8511b53ade95ea316fd8c3286feb9"     [op0, op1] = (.outpoint) <$> unsignedTx.inputs     sigIn0 = SigInput (PayPK pubKey0) 625000000 op0 sigHashAll Nothing-    Just h = addressHash160 =<< pubKeyWitnessAddr ctx (toPubKey ctx key1)+    Just h = addressHash160 =<< pubKeyWitnessAddr (toPubKey key1)     sigIn1 = SigInput (PayWitnessPKHash h) 600000000 op1 sigHashAll Nothing-    generatedSignedTx = signTx btc ctx unsignedTx [sigIn0, sigIn1] [key0, key1]+    generatedSignedTx = signTx btc unsignedTx [sigIn0, sigIn1] [key0, key1]  -- Reproduce the P2SH-P2WPKH example from BIP 143-testBip143p2shp2wpkh :: Ctx -> Assertion-testBip143p2shp2wpkh ctx =-  case getImpl ctx of+testBip143p2shp2wpkh :: Assertion+testBip143p2shp2wpkh =+  case getImpl of     Just ImplCore ->       assertEqual "BIP143 Core p2sh-p2wpkh" (Right signedTxCore) generatedSignedTx     Just ImplCash ->@@ -416,14 +415,14 @@       secHexKey         "eb696a065ef48a2192da5b28b694f87544b30fae8327c4510137a922f32c6dcf"     op0 = (head unsignedTx.inputs).outpoint-    Just h = addressHash160 =<< pubKeyWitnessAddr ctx (toPubKey ctx key0)+    Just h = addressHash160 =<< pubKeyWitnessAddr (toPubKey key0)     sigIn0 = SigInput (PayWitnessPKHash h) 1000000000 op0 sigHashAll Nothing-    generatedSignedTx = signNestedWitnessTx btc ctx unsignedTx [sigIn0] [key0]+    generatedSignedTx = signNestedWitnessTx btc unsignedTx [sigIn0] [key0]  -- P2WSH multisig example (tested against bitcoin-core 0.19.0.1)-testP2WSHMulsig :: Ctx -> Assertion-testP2WSHMulsig ctx =-  case getImpl ctx of+testP2WSHMulsig :: Assertion+testP2WSHMulsig =+  case getImpl of     Just ImplCore ->       assertEqual "Core p2wsh multisig" (Right signedTxCore) generatedSignedTx     Just ImplCash ->@@ -466,20 +465,20 @@           "3030303030303030303030303030303030303030303030303030303030303032",           "3030303030303030303030303030303030303030303030303030303030303033"         ]-    rdm = PayMulSig (toPubKey ctx <$> keys) 2+    rdm = PayMulSig (toPubKey <$> keys) 2     sigIn =       SigInput-        (either error id $ toP2WSH =<< encodeOutput ctx rdm)+        (either error id $ toP2WSH =<< encodeOutput rdm)         100000000         op0         sigHashAll         (Just rdm)-    generatedSignedTx = signTx btc ctx unsignedTx [sigIn] (take 2 keys)+    generatedSignedTx = signTx btc unsignedTx [sigIn] (take 2 keys)  -- Reproduce the P2SH-P2WSH multisig example from BIP 143-testBip143p2shp2wpkhMulsig :: Ctx -> Assertion-testBip143p2shp2wpkhMulsig ctx =-  case getImpl ctx of+testBip143p2shp2wpkhMulsig :: Assertion+testBip143p2shp2wpkhMulsig =+  case getImpl of     Just ImplCore ->       assertEqual         "BIP143 Core p2sh-p2wsh multisig"@@ -559,19 +558,19 @@         "428a7aee9f0c2af0cd19af3cf1c78149951ea528726989b2e83e4778d2c3f890"       ]     Just keys = traverse secHexKey rawKeys-    rdm = PayMulSig (toPubKey ctx <$> keys) 6-    sigIn sh = SigInput (either error id $ toP2WSH =<< encodeOutput ctx rdm) 987654321 op0 sh (Just rdm)+    rdm = PayMulSig (toPubKey <$> keys) 6+    sigIn sh = SigInput (either error id $ toP2WSH =<< encodeOutput rdm) 987654321 op0 sh (Just rdm)     sigHashesA = [sigHashAll, sigHashNone, sigHashSingle]     sigHashesB = setAnyoneCanPay <$> sigHashesA     sigIns = sigIn <$> (sigHashesA <> sigHashesB)     generatedSignedTx = foldM addSig unsignedTx $ zip sigIns keys-    addSig tx (sigIn', key') = signNestedWitnessTx btc ctx tx [sigIn'] [key']+    addSig tx (sigIn', key') = signNestedWitnessTx btc tx [sigIn'] [key']  secHexKey :: Text -> Maybe SecKey secHexKey = decodeHex >=> secKey -toPubKey :: Ctx -> SecKey -> PublicKey-toPubKey ctx = derivePublicKey ctx . wrapSecKey True+toPubKey :: SecKey -> PublicKey+toPubKey = derivePublicKey . wrapSecKey True  -- | The test vectors of the Schnorr module of Bitcoin Cash Node -- (@src\/secp256k1\/src\/modules\/schnorr\/tests_impl.h@, version 29.0.0):@@ -579,8 +578,7 @@ -- verifies. cashSchnorrVectors :: [(String, Text, Text, Text, Bool)] cashSchnorrVectors =-  [-    ( "1",+  [ ( "1",       "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",       "0000000000000000000000000000000000000000000000000000000000000000",       "787a848e71043d280c50470e8e1532b2dd5d20ee912a45dbdd2bd1dfbf187ef6\@@ -673,12 +671,12 @@     )   ] -cashSchnorrSpec :: Ctx -> Spec-cashSchnorrSpec ctx =+cashSchnorrSpec :: Spec+cashSchnorrSpec =   describe "Schnorr signatures of Bitcoin Cash" $     forM_ cashSchnorrVectors $ \(name, pk, digest, sig, valid) ->       it ("vector " <> name) $ do         let bytes = fromJust . decodeHex-            pub = fromJust (importPubKey ctx (bytes pk))+            pub = fromJust (importPubKey (bytes pk))             h = either error id (S.decode (bytes digest)) :: Hash256-        verifyCashSchnorr ctx pub (bytes sig) h `shouldBe` valid+        verifyCashSchnorr pub (bytes sig) h `shouldBe` valid
test/Haskoin/NetworkSpec.hs view
@@ -137,7 +137,8 @@ addrMessageHex :: Text addrMessageHex =   "f9beb4d9"-    <> "61646472" <> "0000000000000000" -- "addr"+    <> "61646472"+    <> "0000000000000000" -- "addr"     <> "1f000000" -- 31 payload bytes     <> "ed52399b" -- checksum     <> "01" -- one entry@@ -190,7 +191,6 @@ outpointBytes :: Tx -> Word32 -> ByteString outpointBytes tx i = runPutS $ serialize $ OutPoint (txHash tx) i - -- | 'txPaying' [p2pkhScript] serialized: version, one input (outpoint hash -- in internal byte order, index 1, empty script, sequence), one output -- (1000 satoshi, 25-byte script), lock time.@@ -316,24 +316,24 @@     }  spec :: Spec-spec = prepareContext $ \ctx -> do+spec = do   testIdentity identityTests   describe "Custom identity tests" $ do     prop "Data.Serialize Encoding for type Message" $       forAll arbitraryNetwork $ \net ->-        forAll (arbitraryMessage net ctx) $+        forAll (arbitraryMessage net) $           customCerealID (getMessage net) (putMessage net)     prop "Binary encoding/decoding identity for CompactBlock" $       forAll arbitraryNetwork $ \net ->-        forAll (arbitraryCompactBlock net ctx) $ \c ->+        forAll (arbitraryCompactBlock net) $ \c ->           parse (runPutS (serialize c)) == Right c     prop "Binary encoding/decoding identity for BlockTxn" $       forAll arbitraryNetwork $ \net ->-        forAll (arbitraryBlockTxn net ctx) $ \b ->+        forAll (arbitraryBlockTxn net) $ \b ->           parse (runPutS (serialize b)) == Right b     prop "msgType is the command a message is sent with" $       forAll arbitraryNetwork $ \net ->-        forAll (arbitraryMessage net ctx) $ \m ->+        forAll (arbitraryMessage net) $ \m ->           fmap (.cmd) (parse (runPutS (putMessage net m)) :: Either String MessageHeader)             == Right (msgType m)   varIntSpec@@ -346,7 +346,7 @@   smallMessagesSpec   rejectSpec   framingSpec-  bloomSpec ctx+  bloomSpec   compactBlockSpec   blockFilterSpec   constantsSpec@@ -354,7 +354,7 @@   itemLimitSpec   compactPositionSpec   witnessFormatSpec-  bloomMatchSpec ctx+  bloomMatchSpec   boundarySpec  -- VarInt ----------------------------------------------------------------------@@ -744,12 +744,12 @@  -- Bloom filters --------------------------------------------------------------- -bloomSpec :: Ctx -> Spec-bloomSpec ctx = describe "bloom filters" $ do+bloomSpec :: Spec+bloomSpec = describe "bloom filters" $ do   describe "test vectors of Bitcoin Core" $ do     it "bloom filter vector 1" bloomFilter1     it "bloom filter vector 2" bloomFilter2-    it "bloom filter vector 3" $ bloomFilter3 ctx+    it "bloom filter vector 3" $ bloomFilter3   describe "bloomCreate" $ do     it "sizes the filter for the elements and false positive rate" $ do       -- 3 elements at 1%: 3 bytes and 5 hash functions, as in the vectors@@ -875,35 +875,35 @@     it "gives Nothing for a transaction with no matching output" irrelevantOutputNotUpdated     it "leaves the filter as it is for a matching pay-to-pubkey-hash output under BloomUpdateP2PubKeyOnly" $ do       let bf = bloomInsert (bloomCreate 10 0.000001 0 BloomUpdateP2PubKeyOnly) p2pkhHash-      bloomRelevantUpdate ctx bf (txPaying [p2pkhScript]) `shouldBe` Just bf+      bloomRelevantUpdate bf (txPaying [p2pkhScript]) `shouldBe` Just bf     it "inserts the outpoint of a matching pay-to-pubkey output under BloomUpdateP2PubKeyOnly" $ do       let k = fromJust $ fromWif btc "5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C"-          p = derivePublicKey ctx k-          bf = bloomInsert (bloomCreate 10 0.000001 0 BloomUpdateP2PubKeyOnly) (marshal ctx p)-          tx = txPaying [marshal ctx (PayPK p)]-      fmap (`bloomContains` outpointBytes tx 0) (bloomRelevantUpdate ctx bf tx) `shouldBe` Just True+          p = derivePublicKey k+          bf = bloomInsert (bloomCreate 10 0.000001 0 BloomUpdateP2PubKeyOnly) (encodeSerial p)+          tx = txPaying [encodeSerial (PayPK p)]+      fmap (`bloomContains` outpointBytes tx 0) (bloomRelevantUpdate bf tx) `shouldBe` Just True     it "leaves the filter as it is under BloomUpdateNone" $ do       let bf = bloomInsert (bloomCreate 10 0.000001 0 BloomUpdateNone) p2pkhHash-      bloomRelevantUpdate ctx bf (txPaying [p2pkhScript]) `shouldBe` Just bf+      bloomRelevantUpdate bf (txPaying [p2pkhScript]) `shouldBe` Just bf     it "scans a non-standard output script without failing" $ do       let bf = bloomInsert (bloomCreate 10 0.000001 0 BloomUpdateAll) p2pkhHash-      bloomRelevantUpdate ctx bf (txPaying [hex "51"]) `shouldBe` Nothing+      bloomRelevantUpdate bf (txPaying [hex "51"]) `shouldBe` Nothing     it "matches a push inside a non-standard output script" $ do       let bf = bloomInsert (bloomCreate 10 0.000001 0 BloomUpdateAll) p2pkhHash           -- push the hash, drop it, then OP_TRUE           tx = txPaying [hex "14" <> p2pkhHash <> hex "7551"]-      fmap (`bloomContains` outpointBytes tx 0) (bloomRelevantUpdate ctx bf tx) `shouldBe` Just True+      fmap (`bloomContains` outpointBytes tx 0) (bloomRelevantUpdate bf tx) `shouldBe` Just True     it "still finds the matching output next to a non-standard one" $ do       let bf = bloomInsert (bloomCreate 10 0.000001 0 BloomUpdateAll) p2pkhHash           tx = txPaying [hex "51", p2pkhScript]-      fmap (`bloomContains` outpointBytes tx 1) (bloomRelevantUpdate ctx bf tx) `shouldBe` Just True+      fmap (`bloomContains` outpointBytes tx 1) (bloomRelevantUpdate bf tx) `shouldBe` Just True     it "matches every output with an empty filter and changes nothing" $ do       let bf = BloomFilter S.empty 0 0 BloomUpdateAll-      bloomRelevantUpdate ctx bf (txPaying [hex "51"]) `shouldBe` Just bf+      bloomRelevantUpdate bf (txPaying [hex "51"]) `shouldBe` Just bf     it "does not insert the outpoint of an output that does not match" $ do       let bf = bloomInsert (bloomCreate 10 0.000001 0 BloomUpdateAll) p2pkhHash           tx = txPaying [p2pkhScript, hex "76a914" <> B.replicate 20 0x42 <> hex "88ac"]-      fmap (`bloomContains` outpointBytes tx 1) (bloomRelevantUpdate ctx bf tx) `shouldBe` Just False+      fmap (`bloomContains` outpointBytes tx 1) (bloomRelevantUpdate bf tx) `shouldBe` Just False  bloomFilter :: Word32 -> Text -> Expectation bloomFilter n x = do@@ -929,15 +929,15 @@ bloomFilter2 :: Expectation bloomFilter2 = bloomFilter 2147483649 "03ce4299050000000100008001" -bloomFilter3 :: Ctx -> Expectation-bloomFilter3 ctx =+bloomFilter3 :: Expectation+bloomFilter3 =   runPutS (serialize f2) `shouldBe` bs   where     f0 = bloomCreate 2 0.001 0 BloomUpdateAll-    f1 = bloomInsert f0 $ marshal ctx p-    f2 = bloomInsert f1 $ runPutS $ serialize $ fromJust $ addressHash160 $ pubKeyAddr ctx p+    f1 = bloomInsert f0 $ encodeSerial p+    f2 = bloomInsert f1 $ runPutS $ serialize $ fromJust $ addressHash160 $ pubKeyAddr p     k = fromJust $ fromWif btc "5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C"-    p = derivePublicKey ctx k+    p = derivePublicKey k     bs = hex "038fc16b080000000000000001"  -- | The first output of 'relevantTx' pays the hash in the filter. Its@@ -951,18 +951,16 @@   where     bf0 = bloomCreate 10 0.000001 0 BloomUpdateAll     bf1 = bloomInsert bf0 p2pkhHash-    bf2 = fromJust $ bloomRelevantUpdate undefined' bf1 relevantTx+    bf2 = fromJust $ bloomRelevantUpdate bf1 relevantTx     -- txid 57dc904f32ad4daab7b321dd469e8791ad09df784cdd273a73985150a4f225e9     -- in internal byte order     outpoint = hex "e925f2a4505198733a27dd4c78df09ad91879e46dd21b3b7aa4dad324f90dc57"-    undefined' = error "bloomRelevantUpdate must not need the context for pay-to-pubkey-hash under BloomUpdateAll"  irrelevantOutputNotUpdated :: Expectation-irrelevantOutputNotUpdated = bloomRelevantUpdate undefined' bf1 unrelatedTx `shouldBe` Nothing+irrelevantOutputNotUpdated = bloomRelevantUpdate bf1 unrelatedTx `shouldBe` Nothing   where     bf0 = bloomCreate 10 0.000001 0 BloomUpdateAll     bf1 = bloomInsert bf0 p2pkhHash-    undefined' = error "bloomRelevantUpdate must not need the context when nothing matches"  -- Random transaction (57dc904f32ad4daab7b321dd469e8791ad09df784cdd273a73985150a4f225e9) relevantTx :: Tx@@ -1088,7 +1086,8 @@     map (.name) allNets `shouldBe` ["btc", "bch", "btctest", "btctest4", "bchtest4", "bchtest", "btcreg", "bchreg"]     length (nub (map (.magic) allNets)) `shouldBe` 8   it "finds every network by name" $-    forM_ allNets $ \n -> netByName n.name `shouldBe` Just n+    forM_ allNets $+      \n -> netByName n.name `shouldBe` Just n   it "finds nothing for an unknown name" $     netByName "ltc" `shouldBe` Nothing   it "uses the magic bytes of each network" $@@ -1362,18 +1361,30 @@   it "does not read the extended format in a blocktxn or a cmpctblock message on bitcoin cash" $ do     let blockTxn = hex bh1Hex <> hex "01" <> witnessTx         compact = hex (genesisHeaderHex <> "0000000000000000" <> "00" <> "0100") <> witnessTx-    fmap (\m -> case m of MBlockTxn b -> map (\t -> length t.inputs) b.transactions; _ -> [])+    fmap+      (\m -> case m of MBlockTxn b -> map (\t -> length t.inputs) b.transactions; _ -> [])       (runGetS (getMessage bch) (frame bch "blocktxn" blockTxn))       `shouldBe` Right [0]-    fmap (\m -> case m of MCompactBlock c -> map (\x -> length x.tx.inputs) c.prefilled; _ -> [])+    fmap+      (\m -> case m of MCompactBlock c -> map (\x -> length x.tx.inputs) c.prefilled; _ -> [])       (runGetS (getMessage bch) (frame bch "cmpctblock" compact))       `shouldBe` Right [0]   it "reads an empty witness item as an empty byte string" $     -- one input with a witness stack of three empty items     let tx3 =           hex $-            "01000000" <> "0001" <> "01" <> h1Hex <> "00000000" <> "00" <> "ffffffff"-              <> "01" <> "e803000000000000" <> "0151" <> "03000000" <> "00000000"+            "01000000"+              <> "0001"+              <> "01"+              <> h1Hex+              <> "00000000"+              <> "00"+              <> "ffffffff"+              <> "01"+              <> "e803000000000000"+              <> "0151"+              <> "03000000"+              <> "00000000"      in fmap (.witness) (parse tx3 :: Either String Tx) `shouldBe` Right [["", "", ""]]  -- Bloom filter matching -----------------------------------------------------------@@ -1393,10 +1404,10 @@   either error id . parse . hex $     "01000000016bff7fcd4f8565ef406dd5d63d4ff94f318fe82027fd4dc451b04474019f74b4000000008c493046022100da0dc6aecefe1e06efdf05773757deb168820930e3b0d03f46f5fcf150bf990c022100d25b5c87040076e4f253f8262e763e2dd51e7ff0be157727c4bc42807f17bd39014104e6c26ef67dc610d2cd192484789a6cf9aea9930b944b7e2db5342b9d9e5b9ff79aff9a2ee1978dd7fd01dfc522ee02283d3b06a9d03acf8096968d7dbb0f9178ffffffff028ba7940e000000001976a914badeecfdef0507247fc8f74241d73bc039972d7b88ac4094a802000000001976a914c10932483fec93ed51f5fe95e72559f2cc7043f988ac00000000" -bloomMatchSpec :: Ctx -> Spec-bloomMatchSpec ctx = describe "bloom filter matching, the bloom_match case of Bitcoin Core" $ do+bloomMatchSpec :: Spec+bloomMatchSpec = describe "bloom filter matching, the bloom_match case of Bitcoin Core" $ do   let fresh = bloomCreate 10 0.000001 0 BloomUpdateAll-      matches element = bloomRelevantUpdate ctx (bloomInsert fresh element) bloomMatchTx /= Nothing+      matches element = bloomRelevantUpdate (bloomInsert fresh element) bloomMatchTx /= Nothing       -- the outpoint 90c122d7...260b:n that the transaction spends       spent n = hex "0b26e9b7735eb6aabdf358bab62f9816a21ba9ebdb719d5299e88607d722c190" <> hex n   it "matches the transaction hash" $@@ -1419,11 +1430,11 @@     matches (spent "01000000") `shouldBe` False   it "matches the transaction that spends a matched output" $     -- "Simple Bloom filter didn't add output" in Bitcoin Core-    let updated = bloomRelevantUpdate ctx (bloomInsert fresh (hex "04943fdd508053c75000106d3bc6e2754dbcff19")) bloomMatchTx-     in fmap (\f -> bloomRelevantUpdate ctx f bloomSpendingTx /= Nothing) updated `shouldBe` Just True+    let updated = bloomRelevantUpdate (bloomInsert fresh (hex "04943fdd508053c75000106d3bc6e2754dbcff19")) bloomMatchTx+     in fmap (\f -> bloomRelevantUpdate f bloomSpendingTx /= Nothing) updated `shouldBe` Just True   it "leaves the filter as it is when only the transaction hash matches" $     let f = bloomInsert fresh (hex "6bff7fcd4f8565ef406dd5d63d4ff94f318fe82027fd4dc451b04474019f74b4")-     in bloomRelevantUpdate ctx f bloomMatchTx `shouldBe` Just f+     in bloomRelevantUpdate f bloomMatchTx `shouldBe` Just f   describe "pay-to-pubkey test of BloomUpdateP2PubKeyOnly, as Solver in Bitcoin Core" $ do     -- Solver checks the size and the first byte of a key, not the curve.     let hybridKey = hex "06" <> B.replicate 64 0x11@@ -1432,7 +1443,7 @@         inserted key script =           let bf = bloomInsert (bloomCreate 10 0.000001 0 BloomUpdateP2PubKeyOnly) key               tx = txPaying [script]-           in fmap (`bloomContains` outpointBytes tx 0) (bloomRelevantUpdate ctx bf tx)+           in fmap (`bloomContains` outpointBytes tx 0) (bloomRelevantUpdate bf tx)     it "inserts the outpoint of a pay-to-pubkey output with a hybrid key" $       inserted hybridKey (hex "41" <> hybridKey <> hex "ac") `shouldBe` Just True     it "inserts the outpoint of a pay-to-pubkey output whose key is not on the curve" $@@ -1480,7 +1491,9 @@   it "reads a version message with negative fields as negative numbers" $     -- Bitcoin Core reads int nVersion, int64_t nTime and int starting_height     let payload =-          hex "ffffffff" <> hex "0100000000000000" <> hex "ffffffffffffffff"+          hex "ffffffff"+            <> hex "0100000000000000"+            <> hex "ffffffffffffffff"             <> B.drop 20 (hex (T.take 160 versionPayloadHex))             <> hex "00"             <> hex "ffffffff"@@ -1497,7 +1510,8 @@       parse (hex ("00000000" <> "00" <> "03" <> "05" <> "0102030405" <> "0000"))         `shouldBe` Right (NetworkAddressV2 0 0 AddrTorV2 (hex "0102030405") 0)     it "reads the entries after a Tor v2 entry of the wrong length" $-      fmap (\(AddrV2 xs) -> map (.network) xs)+      fmap+        (\(AddrV2 xs) -> map (.network) xs)         (parse (hex ("02" <> "00000000" <> "00" <> "03" <> "05" <> "0102030405" <> "0000" <> "e215104d" <> "01" <> "01" <> "04" <> "0a000001" <> "208d")))         `shouldBe` Right [AddrTorV2, AddrIPv4]     it "has no addr form for an IPv6 entry that holds an IPv4-mapped address" $
test/Haskoin/ScriptSpec.hs view
@@ -38,8 +38,8 @@ import Test.QuickCheck import Text.Read -identityTests :: Ctx -> IdentityTests-identityTests ctx =+identityTests :: IdentityTests+identityTests =   def     { readTests =         [ ReadBox arbitrarySigHash,@@ -47,65 +47,56 @@           ReadBox arbitraryScript,           ReadBox arbitraryPushDataType,           ReadBox arbitraryScriptOp,-          ReadBox ((`arbitraryScriptOutput` ctx) =<< arbitraryNetwork),-          ReadBox ((`arbitraryScriptInput` ctx) =<< arbitraryNetwork)+          ReadBox (arbitraryScriptOutput =<< arbitraryNetwork),+          ReadBox (arbitraryScriptInput =<< arbitraryNetwork)         ],       jsonTests =         [ JsonBox arbitraryScript,           JsonBox arbitraryOutPoint,-          JsonBox arbitrarySigHash+          JsonBox arbitrarySigHash,+          JsonBox (arbitraryScriptOutput =<< arbitraryNetwork),+          JsonBox (fst <$> (arbitrarySigInput =<< arbitraryNetwork))         ],       marshalJsonTests =         [ MarshalJsonBox $ do             n <- arbitraryNetwork-            (_, _, ts) <- arbitraryTxSignature n ctx-            return ((n, ctx), ts),-          MarshalJsonBox $ do-            n <- arbitraryNetwork-            o <- arbitraryScriptOutput n ctx-            return (ctx, o),-          MarshalJsonBox $ do-            n <- arbitraryNetwork-            (i, _) <- arbitrarySigInput n ctx-            return (ctx, i)+            (_, _, ts) <- arbitraryTxSignature n+            return (n, ts)         ],       serialTests =         [ SerialBox arbitraryScriptOp,-          SerialBox arbitraryScript+          SerialBox arbitraryScript,+          SerialBox (arbitraryScriptOutput =<< arbitraryNetwork)         ],       marshalTests =         [ MarshalBox $ do             n <- arbitraryNetwork-            (_, _, ts) <- arbitraryTxSignature n ctx-            return ((n, ctx), ts),-          MarshalBox $ do-            n <- arbitraryNetwork-            o <- arbitraryScriptOutput n ctx-            return (ctx, o),+            (_, _, ts) <- arbitraryTxSignature n+            return (n, ts),           MarshalBox $ do             n <- arbitraryNetwork-            i <- arbitraryScriptInput n ctx-            return ((n, ctx), i)+            i <- arbitraryScriptInput n+            return (n, i)         ]     }  spec :: Spec-spec = prepareContext $ \ctx -> do-  testIdentity $ identityTests ctx+spec = do+  testIdentity $ identityTests   describe "opcodes" opcodeSpec   describe "push operations" pushSpec   describe "small integer opcodes" smallIntSpec-  describe "standard outputs" $ outputSpec ctx-  describe "standard inputs" $ inputSpec ctx+  describe "standard outputs" $ outputSpec+  describe "standard inputs" $ inputSpec   describe "sighash types" sigHashTypeSpec-  describe "sighash digests" $ digestSpec ctx-  describe "transaction signatures" $ txSignatureSpec ctx-  describe "btc scripts" $ props btc ctx-  describe "bch scripts" $ props bch ctx+  describe "sighash digests" $ digestSpec+  describe "transaction signatures" $ txSignatureSpec+  describe "btc scripts" $ props btc+  describe "bch scripts" $ props bch   describe "multi signatures" $-    zipWithM_ (curry (mapMulSigVector ctx)) mulSigVectors [0 ..]+    zipWithM_ (curry mapMulSigVector) mulSigVectors [0 ..]   describe "signature decoding" $-    zipWithM_ (curry (sigDecodeMap btc ctx)) scriptSigSignatures [0 ..]+    zipWithM_ (curry (sigDecodeMap btc)) scriptSigSignatures [0 ..]   describe "Script vectors" $     it "Can encode script vectors" encodeScriptVector @@ -127,8 +118,8 @@   "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\   \483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8" -gKey :: Ctx -> PublicKey-gKey ctx = either error id $ unmarshal ctx $ hex gKeyHex+gKey :: PublicKey+gKey = either error id $ decodeSerial $ hex gKeyHex  gHash :: Hash160 gHash = "751e76e8199196d454941c45d1b3a323f1433bd6"@@ -139,8 +130,8 @@ bip67KeyA = "02ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f8" bip67KeyB = "02fe6f0a5a297eb38c391581c4413e084773ea23954d93f7753db7dc0adc188b2f" -bip67Key :: Ctx -> Text -> PublicKey-bip67Key ctx = either error id . unmarshal ctx . hex+bip67Key :: Text -> PublicKey+bip67Key = either error id . decodeSerial . hex  -- | The 2-of-2 script of the first BIP 67 test vector, keys sorted: 71 bytes. bip67ScriptHex :: Text@@ -155,8 +146,8 @@   "304402205ca6249f43538908151fe67b26d020306c0e59fa206cf9f3ccf641f33357119d\   \02206c82f244d04ac0a48024fb9cc246b66e58598acf206139bdb7b75a2941a2b1e4" -sigDer :: Ctx -> Sig-sigDer ctx = fromJust $ decodeStrictSig ctx $ hex sigDerHex+sigDer :: Sig+sigDer = fromJust $ decodeStrictSig $ hex sigDerHex  -- | The signature with SIGHASH_ALL, pushed in a script. sigAllPushHex :: Text@@ -365,8 +356,8 @@       forM_ [OP_RESERVED, OP_NOP, OP_DUP, OP_CHECKSIG, OP_PUBKEYHASH, OP_INVALIDOPCODE 0xff] $ \op ->         (op, isPushOp op) `shouldBe` (op, False)   describe "isMinimalPush" $ do-    it "is true for the shortest encoding of the data" $-      forM_+    it "is true for the shortest encoding of the data"+      $ forM_         [ OP_0,           OP_1,           OP_16,@@ -378,9 +369,9 @@           OP_PUSHDATA (B.replicate 256 0) OPDATA2,           OP_PUSHDATA (B.replicate 65536 0) OPDATA4         ]-        $ \op -> (B.length (runPutS (serialize op)), isMinimalPush op) `shouldSatisfy` snd-    it "is false for a longer encoding of the same data" $-      forM_+      $ \op -> (B.length (runPutS (serialize op)), isMinimalPush op) `shouldSatisfy` snd+    it "is false for a longer encoding of the same data"+      $ forM_         [ OP_PUSHDATA "" OPCODE,           OP_PUSHDATA "\x01" OPCODE,           OP_PUSHDATA "\x81" OPCODE,@@ -388,7 +379,7 @@           OP_PUSHDATA (B.replicate 255 0) OPDATA2,           OP_PUSHDATA (B.replicate 256 0) OPDATA4         ]-        $ \op -> (B.length (runPutS (serialize op)), isMinimalPush op) `shouldSatisfy` (not . snd)+      $ \op -> (B.length (runPutS (serialize op)), isMinimalPush op) `shouldSatisfy` (not . snd)     it "is false for an opcode that pushes nothing" $       isMinimalPush OP_DUP `shouldBe` False @@ -415,8 +406,8 @@ {- Standard outputs -}  -- | Standard output scripts with their decoded form: name, hex, value.-standardOutputs :: Ctx -> [(String, Text, ScriptOutput)]-standardOutputs ctx =+standardOutputs :: [(String, Text, ScriptOutput)]+standardOutputs =   [ ("P2PK", "21" <> gKeyHex <> "ac", PayPK g),     ("P2PKH", "76a914751e76e8199196d454941c45d1b3a323f1433bd688ac", PayPKHash gHash),     -- The P2SH-P2WPKH example of BIP 143.@@ -442,7 +433,7 @@     ("witness v16 of 40 bytes", "6028" <> T.replicate 40 "01", PayWitness 16 (B.replicate 40 1)),     ("witness v1 of 2 bytes", "51020102", PayWitness 1 "\x01\x02"),     -- The first BIP 67 test vector.-    ("2-of-2 multisig", bip67ScriptHex, PayMulSig [bip67Key ctx bip67KeyB, bip67Key ctx bip67KeyA] 2),+    ("2-of-2 multisig", bip67ScriptHex, PayMulSig [bip67Key bip67KeyB, bip67Key bip67KeyA] 2),     -- 17 and 20 are one-byte pushes, as Bitcoin Core writes counts above 16.     ( "17-of-20 multisig",       "0111" <> T.concat (replicate 20 ("21" <> gKeyHex)) <> "0114ae",@@ -456,7 +447,7 @@     ("OP_RETURN with OP_1NEGATE", "6a4f", DataCarrier ["\x81"])   ]   where-    g = gKey ctx+    g = gKey     thirtyTwo = "5d1b56b63d714eebe542309525f484b7e9d6f686b3781b6f61ef925d66d6f6a0"  -- | Scripts that look like a standard output but are not one: name, hex.@@ -511,16 +502,16 @@     twenty = T.replicate 20 "ab"     thirtyTwo = T.replicate 32 "cd" -outputSpec :: Ctx -> Spec-outputSpec ctx = do-  let g = gKey ctx-      decodeHexOutput = unmarshal ctx . hex :: Text -> Either String ScriptOutput-      encodeHexOutput = fmap (encodeHex . runPutS . serialize) . encodeOutput ctx+outputSpec :: Spec+outputSpec = do+  let g = gKey+      decodeHexOutput = decodeSerial . hex :: Text -> Either String ScriptOutput+      encodeHexOutput = fmap (encodeHex . runPutS . serialize) . encodeOutput   it "decodes the standard output templates" $-    forM_ (standardOutputs ctx) $ \(name, h, out) ->+    forM_ standardOutputs $ \(name, h, out) ->       (name, decodeHexOutput h) `shouldBe` (name, Right out)   it "encodes the standard outputs to their templates" $-    forM_ (standardOutputs ctx) $ \(name, h, out) ->+    forM_ standardOutputs $ \(name, h, out) ->       (name, encodeHexOutput out) `shouldBe` (name, Right h)   it "rejects scripts that only look like a standard output" $     forM_ nonStandardOutputs $ \(name, h) ->@@ -555,22 +546,22 @@   it "has 20 as the most multisig keys" $     maxMultisigKeys `shouldBe` 20   it "refuses to encode a multisig that no script can express" $ do-    encodeOutput ctx (PayMulSig [] 0) `shouldSatisfy` isLeft-    encodeOutput ctx (PayMulSig [g] 0) `shouldSatisfy` isLeft-    encodeOutput ctx (PayMulSig [g] 2) `shouldSatisfy` isLeft-    encodeOutput ctx (PayMulSig (replicate 21 g) 1) `shouldSatisfy` isLeft+    encodeOutput (PayMulSig [] 0) `shouldSatisfy` isLeft+    encodeOutput (PayMulSig [g] 0) `shouldSatisfy` isLeft+    encodeOutput (PayMulSig [g] 2) `shouldSatisfy` isLeft+    encodeOutput (PayMulSig (replicate 21 g) 1) `shouldSatisfy` isLeft   it "refuses to encode a witness program outside the versions and lengths of BIP 141" $ do-    encodeOutput ctx (PayWitness 0 (B.replicate 20 1)) `shouldSatisfy` isLeft-    encodeOutput ctx (PayWitness 17 (B.replicate 20 1)) `shouldSatisfy` isLeft-    encodeOutput ctx (PayWitness 1 "\x01") `shouldSatisfy` isLeft-    encodeOutput ctx (PayWitness 1 (B.replicate 41 1)) `shouldSatisfy` isLeft+    encodeOutput (PayWitness 0 (B.replicate 20 1)) `shouldSatisfy` isLeft+    encodeOutput (PayWitness 17 (B.replicate 20 1)) `shouldSatisfy` isLeft+    encodeOutput (PayWitness 1 "\x01") `shouldSatisfy` isLeft+    encodeOutput (PayWitness 1 (B.replicate 41 1)) `shouldSatisfy` isLeft   it "fails with an error call when marshalling an output that cannot be encoded" $-    evaluate (marshal ctx (PayMulSig [] 0)) `shouldThrow` anyErrorCall+    evaluate (encodeSerial (PayMulSig [] 0)) `shouldThrow` anyErrorCall   it "marshals an output to JSON as the hex of its script" $ do-    marshalValue ctx (PayPKHash gHash) `shouldBe` A.String "76a914751e76e8199196d454941c45d1b3a323f1433bd688ac"-    A.parseMaybe (unmarshalValue ctx) (A.String "76a914751e76e8199196d454941c45d1b3a323f1433bd688ac")+    toJSON (PayPKHash gHash) `shouldBe` A.String "76a914751e76e8199196d454941c45d1b3a323f1433bd688ac"+    A.parseMaybe parseJSON (A.String "76a914751e76e8199196d454941c45d1b3a323f1433bd688ac")       `shouldBe` Just (PayPKHash gHash)-    A.parseMaybe (unmarshalValue ctx) (A.String ("004c14" <> T.replicate 20 "ab"))+    A.parseMaybe parseJSON (A.String ("004c14" <> T.replicate 20 "ab"))       `shouldBe` (Nothing :: Maybe ScriptOutput)   describe "toP2SH and toP2WSH" $ do     it "hashes the redeem script of the P2SH-P2WPKH example of BIP 143" $@@ -603,15 +594,15 @@       maxWitnessScriptSize `shouldBe` 10000   describe "sortMulSig" $ do     it "sorts the keys of the first BIP 67 test vector" $ do-      let unsorted = PayMulSig [bip67Key ctx bip67KeyA, bip67Key ctx bip67KeyB] 2-      encodeHexOutput (sortMulSig ctx unsorted) `shouldBe` Right bip67ScriptHex-      (addrToText btc <$> payToScriptAddress ctx (sortMulSig ctx unsorted))+      let unsorted = PayMulSig [bip67Key bip67KeyA, bip67Key bip67KeyB] 2+      encodeHexOutput (sortMulSig unsorted) `shouldBe` Right bip67ScriptHex+      (addrToText btc <$> payToScriptAddress (sortMulSig unsorted))         `shouldBe` Right (Just "39bgKC7RFbpoCRbtD5KEdkYKtNyhpsNa3Z")     it "leaves any other output unchanged" $-      sortMulSig ctx (PayPKHash gHash) `shouldBe` PayPKHash gHash+      sortMulSig (PayPKHash gHash) `shouldBe` PayPKHash gHash     prop "sorts the keys by their serialized bytes" $-      forAll (arbitraryMSOutput ctx) $ \out ->-        let keyList = map (marshal ctx) (sortMulSig ctx out).keys+      forAll arbitraryMSOutput $ \out ->+        let keyList = map encodeSerial (sortMulSig out).keys          in keyList `shouldBe` sort keyList   it "classifies every output type with exactly its own predicate" $ do     let samples =@@ -649,8 +640,8 @@ {- Standard inputs -}  -- | Standard input scripts with their decoded form: name, hex, value.-standardInputs :: Ctx -> [(String, Text, ScriptInput)]-standardInputs ctx =+standardInputs :: [(String, Text, ScriptInput)]+standardInputs =   [ ("P2PK", sigAllPushHex, RegularInput (SpendPK sig)),     ("P2PKH", sigAllPushHex <> "21" <> gKeyHex, RegularInput (SpendPKHash sig g)),     ("2-of-n multisig", "00" <> sigAllPushHex <> sigAllPushHex, RegularInput (SpendMulSig [sig, sig])),@@ -674,9 +665,9 @@     )   ]   where-    g = gKey ctx-    sig = TxSignature (sigDer ctx) sigHashAll-    multisig = PayMulSig [bip67Key ctx bip67KeyB, bip67Key ctx bip67KeyA] 2+    g = gKey+    sig = TxSignature sigDer sigHashAll+    multisig = PayMulSig [bip67Key bip67KeyB, bip67Key bip67KeyA] 2  -- | Scripts that are not a standard input: name, hex. nonStandardInputs :: [(String, Text)]@@ -702,16 +693,16 @@     ("a non-push opcode", "76")   ] -inputSpec :: Ctx -> Spec-inputSpec ctx = do-  let g = gKey ctx-      decodeHexInput = unmarshal (btc, ctx) . hex :: Text -> Either String ScriptInput-      encodeHexInput = encodeHex . marshal (btc, ctx)+inputSpec :: Spec+inputSpec = do+  let g = gKey+      decodeHexInput = unmarshal btc . hex :: Text -> Either String ScriptInput+      encodeHexInput = encodeHex . marshal btc   it "decodes the standard input scripts" $-    forM_ (standardInputs ctx) $ \(name, h, inp) ->+    forM_ standardInputs $ \(name, h, inp) ->       (name, decodeHexInput h) `shouldBe` (name, Right inp)   it "encodes the standard inputs to their scripts" $-    forM_ (standardInputs ctx) $ \(name, h, inp) ->+    forM_ standardInputs $ \(name, h, inp) ->       (name, encodeHexInput inp) `shouldBe` (name, h)   it "rejects scripts that are not a standard input" $     forM_ nonStandardInputs $ \(name, h) ->@@ -735,9 +726,9 @@   it "reads a single empty push as a pay-to-public-key input with an empty signature" $ do     -- The same script is a multisig input without signatures. Without the     -- output script, the single-signature reading is taken.-    decodeInput btc ctx (Script [OP_0]) `shouldBe` Right (RegularInput (SpendPK TxSignatureEmpty))-    decodeInput btc ctx (Script [OP_0, OP_0]) `shouldBe` Right (RegularInput (SpendMulSig [TxSignatureEmpty]))-    decodeInput btc ctx (Script [OP_0, OP_0, OP_0, OP_0])+    decodeInput btc (Script [OP_0]) `shouldBe` Right (RegularInput (SpendPK TxSignatureEmpty))+    decodeInput btc (Script [OP_0, OP_0]) `shouldBe` Right (RegularInput (SpendMulSig [TxSignatureEmpty]))+    decodeInput btc (Script [OP_0, OP_0, OP_0, OP_0])       `shouldBe` Right (RegularInput (SpendMulSig (replicate 3 TxSignatureEmpty)))   it "writes an empty signature as OP_0" $ do     encodeHexInput (RegularInput (SpendPK TxSignatureEmpty)) `shouldBe` "00"@@ -843,8 +834,8 @@  {- Digests -} -digestSpec :: Ctx -> Spec-digestSpec ctx = do+digestSpec :: Spec+digestSpec = do   it "computes the BIP 143 digest of the P2WPKH example" $     txSigHashForkId btc bip143Tx bip143ScriptCode bip143Value 1 sigHashAll       `shouldBe` Right bip143Digest@@ -863,7 +854,8 @@       `shouldBe` Right "c46030820cbc48402a47cc5b5d3d41648f4e3a711f56b804d601d09dc112a6a4"     txSigHash btc bip143Tx bip143ScriptCode bip143Value 1 0x101       `shouldBe` Right "8e4ac2d7b4f759fdd01de9b78a2c46fe361316f397b214c7f0f98f073128aa4c"-  it "computes the fork id digest of Bitcoin Cash for each of its six hash types" $+  it "computes the fork id digest of Bitcoin Cash for each of its six hash types"+    $     -- The fork id of Bitcoin Cash is 0, so the last four bytes of the     -- preimage are the hash type byte and three zero bytes     forM_@@ -874,8 +866,8 @@         (0xc2, "e58ebfd50f957a45c5f68439e55c6ae6054a3310ff2a116efa07d2bda2527bd3"),         (0xc3, "4e303851715b6ee36582740f43cc288c969e88afc641f14e3e8e68d32c406c1b")       ]-      $ \(sh, digest) ->-        (sh, txSigHashForkId bch bip143Tx bip143ScriptCode bip143Value 1 sh) `shouldBe` (sh, Right digest)+    $ \(sh, digest) ->+      (sh, txSigHashForkId bch bip143Tx bip143ScriptCode bip143Value 1 sh) `shouldBe` (sh, Right digest)   it "fails for an input index the transaction does not have" $ do     txSigHash btc bip143Tx bip143ScriptCode bip143Value 2 sigHashAll `shouldSatisfy` isLeft     txSigHash btc bip143Tx bip143ScriptCode bip143Value (-1) sigHashAll `shouldSatisfy` isLeft@@ -902,87 +894,87 @@  {- Transaction signatures -} -txSignatureSpec :: Ctx -> Spec-txSignatureSpec ctx = do-  let sig = sigDer ctx+txSignatureSpec :: Spec+txSignatureSpec = do+  let sig = sigDer   it "writes the signature followed by its hash type byte" $ do-    encodeTxSig btc ctx (TxSignature sig sigHashAll) `shouldBe` hex (sigDerHex <> "01")-    encodeTxSig btc ctx (TxSignature sig 0x81) `shouldBe` hex (sigDerHex <> "81")-    encodeTxSig bch ctx (TxSignature sig 0x41) `shouldBe` hex (sigDerHex <> "41")+    encodeTxSig btc (TxSignature sig sigHashAll) `shouldBe` hex (sigDerHex <> "01")+    encodeTxSig btc (TxSignature sig 0x81) `shouldBe` hex (sigDerHex <> "81")+    encodeTxSig bch (TxSignature sig 0x41) `shouldBe` hex (sigDerHex <> "41")   it "writes an empty signature as the empty string" $-    encodeTxSig btc ctx TxSignatureEmpty `shouldBe` ""+    encodeTxSig btc TxSignatureEmpty `shouldBe` ""   it "reads a signature with its hash type byte" $ do-    decodeTxSig btc ctx (hex (sigDerHex <> "01")) `shouldBe` Right (TxSignature sig 0x01)-    decodeTxSig btc ctx (hex (sigDerHex <> "82")) `shouldBe` Right (TxSignature sig 0x82)-    decodeTxSig bch ctx (hex (sigDerHex <> "c3")) `shouldBe` Right (TxSignature sig 0xc3)+    decodeTxSig btc (hex (sigDerHex <> "01")) `shouldBe` Right (TxSignature sig 0x01)+    decodeTxSig btc (hex (sigDerHex <> "82")) `shouldBe` Right (TxSignature sig 0x82)+    decodeTxSig bch (hex (sigDerHex <> "c3")) `shouldBe` Right (TxSignature sig 0xc3)   it "reads the empty string as an empty signature" $-    decodeTxSig btc ctx "" `shouldBe` Right TxSignatureEmpty+    decodeTxSig btc "" `shouldBe` Right TxSignatureEmpty   it "requires the SIGHASH_FORKID flag exactly on networks with a fork id" $ do-    decodeTxSig btc ctx (hex (sigDerHex <> "41")) `shouldSatisfy` isLeft-    decodeTxSig btc ctx (hex (sigDerHex <> "c1")) `shouldSatisfy` isLeft-    decodeTxSig bch ctx (hex (sigDerHex <> "01")) `shouldSatisfy` isLeft-    decodeTxSig bch ctx (hex (sigDerHex <> "81")) `shouldSatisfy` isLeft+    decodeTxSig btc (hex (sigDerHex <> "41")) `shouldSatisfy` isLeft+    decodeTxSig btc (hex (sigDerHex <> "c1")) `shouldSatisfy` isLeft+    decodeTxSig bch (hex (sigDerHex <> "01")) `shouldSatisfy` isLeft+    decodeTxSig bch (hex (sigDerHex <> "81")) `shouldSatisfy` isLeft   it "rejects a hash type byte that no node accepts" $     forM_ ["00", "04", "20", "21", "ff"] $ \sh ->-      (sh, decodeTxSig btc ctx (hex (sigDerHex <> sh))) `shouldSatisfy` (isLeft . snd)+      (sh, decodeTxSig btc (hex (sigDerHex <> sh))) `shouldSatisfy` (isLeft . snd)   it "rejects a signature with a high S, the LOW_S rule of the relay policy" $ do     -- r = 1 and s = n - 1. The encoding is strict DER, and consensus     -- accepts it. decodeStrictSig reads it, decodeTxSig does not.     let highS = "3026020101022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"-    decodeTxSig btc ctx (hex (highS <> "01"))+    decodeTxSig btc (hex (highS <> "01"))       `shouldBe` Left "Failed reading: Non-canonical signature: S value is unnecessarily high\nEmpty call stack\n"-    isJust (decodeStrictSig ctx (hex highS)) `shouldBe` True+    isJust (decodeStrictSig (hex highS)) `shouldBe` True   it "names the rule when it rejects an undefined hash type byte, the STRICTENC rule" $-    decodeTxSig btc ctx (hex (sigDerHex <> "04"))+    decodeTxSig btc (hex (sigDerHex <> "04"))       `shouldBe` Left "Failed reading: Non-canonical signature: unknown hashtype byte\nEmpty call stack\n"   it "rejects a signature whose r is padded with a zero byte, the DERSIG rule of BIP 66" $     -- 02 02 00 01 is the integer 1 with a needless leading zero-    decodeTxSig btc ctx (hex "300702020001020101" <> "\x01") `shouldSatisfy` isLeft+    decodeTxSig btc (hex "300702020001020101" <> "\x01") `shouldSatisfy` isLeft   it "rejects bytes after the hash type byte" $-    decodeTxSig btc ctx (hex (sigDerHex <> "0101")) `shouldSatisfy` isLeft+    decodeTxSig btc (hex (sigDerHex <> "0101")) `shouldSatisfy` isLeft   it "rejects bytes after the hash type byte in the binary form too" $-    (unmarshal (btc, ctx) (hex (sigDerHex <> "01deadbeef")) :: Either String TxSignature)+    (unmarshal btc (hex (sigDerHex <> "01deadbeef")) :: Either String TxSignature)       `shouldSatisfy` isLeft   it "does not read a Schnorr signature on Bitcoin Cash, which this type cannot hold" $     -- 64 bytes and the hash type byte 0x41. Bitcoin Cash Node takes a     -- 64-byte signature as Schnorr.-    decodeTxSig bch ctx (B.replicate 64 0x11 <> "\x41") `shouldSatisfy` isLeft+    decodeTxSig bch (B.replicate 64 0x11 <> "\x41") `shouldSatisfy` isLeft   it "does not read SIGHASH_UTXOS on Bitcoin Cash, which the digest does not support" $     -- 0x61 is SIGHASH_ALL with SIGHASH_UTXOS and SIGHASH_FORKID-    decodeTxSig bch ctx (hex (sigDerHex <> "61"))+    decodeTxSig bch (hex (sigDerHex <> "61"))       `shouldBe` Left "Failed reading: Non-canonical signature: unknown hashtype byte\nEmpty call stack\n"   it "rejects a signature without a hash type byte" $-    decodeTxSig btc ctx (hex sigDerHex) `shouldSatisfy` isLeft+    decodeTxSig btc (hex sigDerHex) `shouldSatisfy` isLeft   it "rejects a signature that is not strict DER" $-    decodeTxSig btc ctx (hex ("3045022100" <> T.drop 8 sigDerHex <> "01")) `shouldSatisfy` isLeft+    decodeTxSig btc (hex ("3045022100" <> T.drop 8 sigDerHex <> "01")) `shouldSatisfy` isLeft   it "marshals a signature to JSON as its hex" $ do-    marshalValue (btc, ctx) (TxSignature sig sigHashAll) `shouldBe` A.String (sigDerHex <> "01")-    A.parseMaybe (unmarshalValue (btc, ctx)) (A.String (sigDerHex <> "01")) `shouldBe` Just (TxSignature sig sigHashAll)-    A.parseMaybe (unmarshalValue (btc, ctx)) (A.String (sigDerHex <> "41")) `shouldBe` (Nothing :: Maybe TxSignature)+    marshalValue btc (TxSignature sig sigHashAll) `shouldBe` A.String (sigDerHex <> "01")+    A.parseMaybe (unmarshalValue btc) (A.String (sigDerHex <> "01")) `shouldBe` Just (TxSignature sig sigHashAll)+    A.parseMaybe (unmarshalValue btc) (A.String (sigDerHex <> "41")) `shouldBe` (Nothing :: Maybe TxSignature)  {- Per-network properties and vectors -} -props :: Network -> Ctx -> Spec-props net ctx = do-  standardSpec net ctx-  strictSigSpec net ctx-  scriptSpec net ctx+props :: Network -> Spec+props net = do+  standardSpec net+  strictSigSpec net+  scriptSpec net   txSigHashForkIdSpec net-  forkIdScriptSpec net ctx-  sigHashSpec net ctx+  forkIdScriptSpec net+  sigHashSpec net   txSigHashSpec net -standardSpec :: Network -> Ctx -> Spec-standardSpec net ctx = do+standardSpec :: Network -> Spec+standardSpec net = do   prop "has decodeOutput . encodeOutput identity" $-    forAll (arbitraryScriptOutput net ctx) $ \so ->-      (decodeOutput ctx =<< encodeOutput ctx so) `shouldBe` Right so+    forAll (arbitraryScriptOutput net) $ \so ->+      (decodeOutput =<< encodeOutput so) `shouldBe` Right so   prop "has decodeInput . encodeInput identity" $-    forAll (arbitraryScriptInput net ctx) $ \si ->-      (decodeInput net ctx . encodeInput net ctx) si `shouldBe` Right si+    forAll (arbitraryScriptInput net) $ \si ->+      (decodeInput net . encodeInput net) si `shouldBe` Right si   prop "gives every encodable output a script that decodes to it" $-    forAll (arbitraryScriptOutput net ctx) $ \so ->-      unmarshal ctx (marshal ctx so) `shouldBe` Right so+    forAll (arbitraryScriptOutput net) $ \so ->+      decodeSerial (encodeSerial so) `shouldBe` Right so  -- | The file @data/script_tests.json@ is not the @script_tests.json@ of -- Bitcoin Core, which has more than a thousand vectors for its interpreter.@@ -1001,8 +993,8 @@ -- * One vector, about the fork id flag, is not in Bitcoin Core. -- -- So 45 vectors run: 9 valid spends and 36 refusals.-scriptSpec :: Network -> Ctx -> Spec-scriptSpec net ctx =+scriptSpec :: Network -> Spec+scriptSpec net =   when (net.name == "btc") $     it "verifies the 45 standard-template vectors selected from script_tests.json of Bitcoin Core" $ do       xs <- readTestFile "script_tests.json" :: IO [A.Value]@@ -1023,10 +1015,10 @@       forM_ enabled $ \([val], siStr, soStr, _, res, desc) -> do         let scriptSig = parseScript siStr             scriptPubKey = parseScript soStr-            out = unmarshal ctx scriptPubKey+            out = decodeSerial scriptPubKey             sat = val * 100000000             tx = spendTx scriptPubKey sat scriptSig-            ver o = verifyStdInput net ctx tx [(o, sat, (head tx.inputs).outpoint)] 0+            ver o = verifyStdInput net tx [(o, sat, (head tx.inputs).outpoint)] 0             valid = either (const False) ver out         assertBool desc $ if res == "OK" then valid else not valid         -- A vector refused for the form of its input, not for a wrong@@ -1034,7 +1026,7 @@         -- tells such a refusal from an unrelated one.         when (res `elem` encodingErrors) $           assertBool (desc <> ": the input is not in the relay form") $-            isLeft (decodeInput net ctx =<< runGetS deserialize scriptSig)+            isLeft (decodeInput net =<< runGetS deserialize scriptSig)   where     -- The results of Bitcoin Core that name a rule on the form of an input,     -- and NONSTRICT, which this file uses for a form only consensus accepts@@ -1048,8 +1040,8 @@         "NONSTRICT"       ] -forkIdScriptSpec :: Network -> Ctx -> Spec-forkIdScriptSpec net ctx =+forkIdScriptSpec :: Network -> Spec+forkIdScriptSpec net =   when (isJust net.sigHashForkId) $     it "can verify scripts from forkid_script_tests.json file" $ do       xs <- readTestFile "forkid_script_tests.json" :: IO [A.Value]@@ -1068,9 +1060,9 @@         let val = valBTC * 100000000             scriptSig = parseScript siStr             scriptPubKey = parseScript soStr-            out = unmarshal ctx scriptPubKey+            out = decodeSerial scriptPubKey             tx = spendTx scriptPubKey val scriptSig-            ver o = verifyStdInput net ctx tx [(o, val, (head tx.inputs).outpoint)] 0+            ver o = verifyStdInput net tx [(o, val, (head tx.inputs).outpoint)] 0             valid = either (const False) ver out         case res of           "OK" -> valid `shouldBe` True@@ -1114,8 +1106,8 @@   Just opcode -> "0x" <> cs (encodeHex $ runPutS $ serialize (opcode :: ScriptOp))   _ -> str -strictSigSpec :: Network -> Ctx -> Spec-strictSigSpec net ctx =+strictSigSpec :: Network -> Spec+strictSigSpec net =   when (net.name == "btc") $ do     it "can decode strict signatures" $ do       xs <- readTestFile "sig_strict.json"@@ -1123,7 +1115,7 @@       length vectors `shouldBe` 3       forM_ vectors $ \sig ->         let eitherSig :: Either String TxSignature-            eitherSig = decodeTxSig net ctx sig+            eitherSig = decodeTxSig net sig          in eitherSig `shouldSatisfy` isRight     it "refuses the non-strict signatures, each for the rule its label names" $ do       xs <- readTestFile "sig_nonstrict.json" :: IO [Text]@@ -1133,8 +1125,8 @@       length labelled `shouldBe` 17       forM_ labelled $ \(label, sig) -> do         let name = cs label <> " " <> cs (encodeHex sig)-            strictDer = isJust (decodeStrictSig ctx (B.init sig))-            refusal = either id (const "accepted") (decodeTxSig net ctx sig)+            strictDer = isJust (decodeStrictSig (B.init sig))+            refusal = either id (const "accepted") (decodeTxSig net sig)         case label of           -- Strict DER, and a hash type byte that is not defined           "hashtype:" -> do@@ -1211,27 +1203,26 @@         res `shouldSatisfy` isJust         eitherToMaybe (txSigHashForkId net tx s val i sh) `shouldBe` res -sigHashSpec :: Network -> Ctx -> Spec-sigHashSpec net ctx = do+sigHashSpec :: Network -> Spec+sigHashSpec net = do   it "can decodeTxSig . encode a TxSignature" $     property $-      forAll (arbitraryTxSignature net ctx) $ \(_, _, ts) ->-        let f = decodeTxSig net ctx . encodeTxSig net ctx+      forAll (arbitraryTxSignature net) $ \(_, _, ts) ->+        let f = decodeTxSig net . encodeTxSig net          in f ts `shouldBe` Right ts   if isNothing net.sigHashForkId     then       it "can produce the sighash one" $         property $-          forAll (arbitraryTx net ctx) $+          forAll (arbitraryTx net) $             forAll arbitraryScript . testSigHashOne net-    else-      it "never produces the sighash one, since the fork id digest has no such case" $-        property $-          forAll (arbitraryTx net ctx) $ \tx ->-            forAll arbitraryScript $ \s ->-              not (null tx.inputs) ==>-                txSigHash net tx s 0 (length tx.inputs - 1) (setForkIdFlag sigHashSingle)-                  `shouldSatisfy` \res -> isRight res && res /= Right sigHashOne+    else it "never produces the sighash one, since the fork id digest has no such case" $+      property $+        forAll (arbitraryTx net) $ \tx ->+          forAll arbitraryScript $ \s ->+            not (null tx.inputs) ==>+              txSigHash net tx s 0 (length tx.inputs - 1) (setForkIdFlag sigHashSingle)+                `shouldSatisfy` \res -> isRight res && res /= Right sigHashOne  -- | The digest that the legacy algorithm gives for SIGHASH_SINGLE without a -- matching output.@@ -1253,33 +1244,33 @@  {- Parse tests from bitcoin-qt repository -} -mapMulSigVector :: Ctx -> ((Text, Text), Int) -> Spec-mapMulSigVector ctx (v, i) =-  it name $ runMulSigVector ctx v+mapMulSigVector :: ((Text, Text), Int) -> Spec+mapMulSigVector (v, i) =+  it name $ runMulSigVector v   where     name = "check multisig vector " <> show i -runMulSigVector :: Ctx -> (Text, Text) -> Assertion-runMulSigVector ctx (a, ops) = assertBool "multisig vector" $ Just a == b+runMulSigVector :: (Text, Text) -> Assertion+runMulSigVector (a, ops) = assertBool "multisig vector" $ Just a == b   where     s = do       s' <- decodeHex ops       eitherToMaybe $ runGetS deserialize s'     b = do       o <- s-      d <- eitherToMaybe $ decodeOutput ctx o-      addrToText btc =<< eitherToMaybe (payToScriptAddress ctx d)+      d <- eitherToMaybe $ decodeOutput o+      addrToText btc =<< eitherToMaybe (payToScriptAddress d) -sigDecodeMap :: Network -> Ctx -> (Text, Int) -> Spec-sigDecodeMap net ctx (_, i) =+sigDecodeMap :: Network -> (Text, Int) -> Spec+sigDecodeMap net (_, i) =   it ("check signature " ++ show i) func   where-    func = testSigDecode net ctx $ scriptSigSignatures !! i+    func = testSigDecode net $ scriptSigSignatures !! i -testSigDecode :: Network -> Ctx -> Text -> Assertion-testSigDecode net ctx str =+testSigDecode :: Network -> Text -> Assertion+testSigDecode net str =   let bs = fromJust $ decodeHex str-      eitherSig = decodeTxSig net ctx bs+      eitherSig = decodeTxSig net bs    in assertBool         ( unwords             [ "Decode failed:",
test/Haskoin/Transaction/PsbtSpec.hs view
@@ -10,15 +10,15 @@ module Haskoin.Transaction.PsbtSpec (spec) where  import Control.Monad (foldM, forM_)+import Crypto.Hash (Digest, SHA256, digestFromByteString) import Data.Aeson ((.:), (.:?)) import Data.Aeson qualified as Json-import Data.ByteString (ByteString) import Data.Bits (xor)+import Data.ByteString (ByteString) import Data.ByteString qualified as B-import Data.List (isPrefixOf, isSuffixOf)-import Crypto.Hash (Digest, SHA256, digestFromByteString) import Data.Bytes.Put (runPutS) import Data.Bytes.Serial (serialize)+import Data.List (isPrefixOf, isSuffixOf) import Data.Map.Strict qualified as Map import Data.Maybe (fromJust, fromMaybe, isJust, listToMaybe, mapMaybe) import Data.Serialize qualified as S@@ -106,8 +106,8 @@ secretThree = "0000000000000000000000000000000000000000000000000000000000000003"  -- | The compressed public key of a secret key-compressedKey :: Ctx -> SecKey -> PublicKey-compressedKey ctx secret = PublicKey (derivePubKey ctx secret) True+compressedKey :: SecKey -> PublicKey+compressedKey secret = PublicKey (derivePubKey secret) True  -- | The map of the input, or of the output, at the index inputAt, outputAt :: Int -> Psbt -> PsbtMap@@ -127,24 +127,24 @@   vectors <- runIO (readTestFile "psbt_bip174.json" :: IO Vectors)   vectors370 <- runIO (readTestFile "psbt_bip370.json" :: IO Vectors370)   vectors371 <- runIO (readTestFile "psbt_bip371.json" :: IO Vectors371)-  prepareContext $ \ctx -> do+  do     vectorsSpec vectors     vectors370Spec vectors370-    rolesSpec ctx vectors+    rolesSpec vectors     version2Spec     bytesSpec vectors-    fieldsSpec ctx vectors-    signingSpec ctx-    signerChecksSpec ctx-    signerScopeSpec ctx-    coinsSpec ctx+    fieldsSpec vectors+    signingSpec+    signerChecksSpec+    signerScopeSpec+    coinsSpec     version2FieldsSpec-    taprootChecksSpec ctx vectors371+    taprootChecksSpec vectors371     decoderChecksSpec-    taprootSpec ctx vectors371-    complexSpec ctx-    core32Spec ctx-    propertiesSpec ctx+    taprootSpec vectors371+    complexSpec+    core32Spec+    propertiesSpec  {- The vectors of BIP 370 -} @@ -288,8 +288,8 @@     forM_ [v | v <- vectors.roles, v.vecCase /= (combiner vectors).vecCase] $ \v ->       it v.vecCase $ (encodePsbt <$> decodePsbt (bytesOf v)) `shouldBe` Right (bytesOf v) -rolesSpec :: Ctx -> Vectors -> Spec-rolesSpec ctx vectors =+rolesSpec :: Vectors -> Spec+rolesSpec vectors =   describe "The roles of BIP 174" $ do     it "the creator's PSBT is the unsigned transaction with empty maps" $ do       psbt <- psbtOfVector (creator vectors)@@ -322,11 +322,11 @@     it "a signer that trusts witness outputs makes the first signer's PSBT of the BIP from the updater's, and the second signer's" $ do       psbt <- psbtOfVector (updaterWithSigHash vectors)       let master = fromJust (xPrvImport btcTest "tprv8ZgxMBicQKsPd9TeAdPADNnSyH9SSUUbTVeFszDE23Ki6TBB5nCefAdHkK8Fm3qMQR6sHwA56zqRmKmxnHk37JkiFzvncDqoKmPWubu7hDF")-          trusting = (xPrvSigner ctx master Nothing) {requirePreviousTx = False}+          trusting = (xPrvSigner master Nothing) {requirePreviousTx = False}           holding paths = trusting {keyOfRecord = \public derivation -> if derivation.path `elem` paths then trusting.keyOfRecord public derivation else Nothing}-      (encodePsbt <$> signPsbt btcTest ctx (holding ["m/0'/0'/0'", "m/0'/0'/2'"]) psbt) `shouldBe` Right (bytesOf (firstSigner vectors))-      (encodePsbt <$> signPsbt btcTest ctx (holding ["m/0'/0'/1'", "m/0'/0'/3'"]) psbt) `shouldBe` Right (bytesOf (secondSigner vectors))-      signPsbt btcTest ctx (xPrvSigner ctx master Nothing) psbt+      (encodePsbt <$> signPsbt btcTest (holding ["m/0'/0'/0'", "m/0'/0'/2'"]) psbt) `shouldBe` Right (bytesOf (firstSigner vectors))+      (encodePsbt <$> signPsbt btcTest (holding ["m/0'/0'/1'", "m/0'/0'/3'"]) psbt) `shouldBe` Right (bytesOf (secondSigner vectors))+      signPsbt btcTest (xPrvSigner master Nothing) psbt         `shouldBe` Left "Input 1: the coin is given as a witness output only, and the signer requires the previous transaction of a SegWit version 0 coin"      -- The four cases the BIP lists under "Fails Signer checks", signed@@ -334,29 +334,29 @@     -- signature. The numbers are the partial signatures of each input.     describe "a signer adds no signature to the input at fault of the PSBTs that fail the signer checks of the BIP" $ do       let master = fromJust (xPrvImport btcTest "tprv8ZgxMBicQKsPd9TeAdPADNnSyH9SSUUbTVeFszDE23Ki6TBB5nCefAdHkK8Fm3qMQR6sHwA56zqRmKmxnHk37JkiFzvncDqoKmPWubu7hDF")-          trusting = (xPrvSigner ctx master Nothing) {requirePreviousTx = False}-          counts = mapM (fmap length . partialSignatures ctx) . (.inputs)+          trusting = (xPrvSigner master Nothing) {requirePreviousTx = False}+          counts = mapM (fmap length . partialSignatures) . (.inputs)           failing i = psbtOfVector (vectors.valid !! i)       -- No record names a key, so the signer holds none: nothing is signed       it "a witness output for a legacy coin" $ do         psbt <- failing 10         counts psbt `shouldBe` Right [0, 0]-        (counts =<< signPsbt btcTest ctx trusting psbt) `shouldBe` Right [0, 0]+        (counts =<< signPsbt btcTest trusting psbt) `shouldBe` Right [0, 0]       -- The redeem script of input 0 is no standard script, and does not       -- hash to the coin. Input 1 is sound and is signed.       it "a redeem script that does not match the coin, with the previous transaction" $ do         psbt <- failing 11         counts psbt `shouldBe` Right [1, 1]-        (counts =<< signPsbt btcTest ctx trusting psbt) `shouldBe` Right [1, 2]+        (counts =<< signPsbt btcTest trusting psbt) `shouldBe` Right [1, 2]       it "a redeem script that does not match the coin, with the witness output" $ do         psbt <- failing 12-        signPsbt btcTest ctx trusting psbt `shouldBe` Left "Input 1: the redeem script of the input does not hash to its coin"+        signPsbt btcTest trusting psbt `shouldBe` Left "Input 1: the redeem script of the input does not hash to its coin"       -- The witness script of input 1 is no standard script. Input 0 is       -- sound and is signed.       it "a witness script that does not match the redeem script" $ do         psbt <- failing 13         counts psbt `shouldBe` Right [1, 1]-        (counts =<< signPsbt btcTest ctx trusting psbt) `shouldBe` Right [2, 1]+        (counts =<< signPsbt btcTest trusting psbt) `shouldBe` Right [2, 1]      -- The spec does not say in which order a combiner writes the keys of a     -- map. The BIP's combiner lists the two signatures of the second input@@ -393,11 +393,11 @@      it "the finalizer's PSBT is the combiner's PSBT finalized" $ do       psbt <- psbtOfVector (combiner vectors)-      (encodePsbt <$> finalizePsbt btc ctx psbt) `shouldBe` Right (bytesOf (finalizer vectors))+      (encodePsbt <$> finalizePsbt btc psbt) `shouldBe` Right (bytesOf (finalizer vectors))      it "the finalizer leaves an input without enough signatures as it is" $ do       psbt <- psbtOfVector (firstSigner vectors)-      finalizePsbt btc ctx psbt `shouldBe` Right psbt+      finalizePsbt btc psbt `shouldBe` Right psbt  {- The roles of version 2 -} @@ -614,16 +614,16 @@  -- The literal values below are those Bitcoin Core 25.0 shows for the -- vectors with decodepsbt.-fieldsSpec :: Ctx -> Vectors -> Spec-fieldsSpec ctx vectors =+fieldsSpec :: Vectors -> Spec+fieldsSpec vectors =   describe "The fields of a PSBT" $ do-    let publicKey text = forceRight (unmarshal ctx (hexBytes text)) :: PublicKey+    let publicKey text = forceRight (decodeSerial (hexBytes text)) :: PublicKey         shown :: [(PublicKey, Derivation)] -> [(Text, Derivation)]-        shown records = [(encodeHex (marshal ctx key), derivation) | (key, derivation) <- records]+        shown records = [(encodeHex (encodeSerial key), derivation) | (key, derivation) <- records]      it "read the derivation records of an input: the public key, the fingerprint of the master key and the path" $ do       psbt <- psbtOfVector (updater vectors)-      records <- expectRight $ inputDerivations ctx (inputAt 0 psbt)+      records <- expectRight $ inputDerivations (inputAt 0 psbt)       shown records         `shouldBe` [ (firstKey, Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/0'"),                      ("02dab61ff49a14db6a7d02b0cd1fbb78fc4b18312b5b4e54dae4dba2fbfef536d7", Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/1'")@@ -631,16 +631,16 @@      it "read the derivation records of an output" $ do       psbt <- psbtOfVector (updater vectors)-      records <- expectRight $ outputDerivations ctx (outputAt 0 psbt)+      records <- expectRight $ outputDerivations (outputAt 0 psbt)       shown records `shouldBe` [("03a9a4c37f5996d3aa25dbac6b570af0650394492942460b354753ed9eeca58771", Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/4'")]      -- The path is 0' (0x80000000) three times, each over four bytes,     -- little-endian     it "write a derivation record as the public key under the type, and the fingerprint then the path, four bytes an index" $ do       let key = publicKey firstKey-      Map.toList (insertInputDerivation ctx key (Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/0'") Map.empty)+      Map.toList (insertInputDerivation key (Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/0'") Map.empty)         `shouldBe` [(Key 0x06 (hexBytes firstKey), hexBytes ("d90c6a4f" <> "00000080" <> "00000080" <> "00000080"))]-      Map.keys (insertOutputDerivation ctx key (Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/4'") Map.empty)+      Map.keys (insertOutputDerivation key (Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/4'") Map.empty)         `shouldBe` [Key 0x02 (hexBytes firstKey)]      it "read the sighash type of an input, when it has one" $ do@@ -682,11 +682,11 @@     -- the last byte 01 of the signature     it "read the partial signatures of an input: the public key, and the signature with its sighash byte" $ do       psbt <- psbtOfVector (firstSigner vectors)-      records <- expectRight (partialSignatures ctx (inputAt 0 psbt))-      [(encodeHex (marshal ctx key), encodeHex signature) | (key, signature) <- records] `shouldBe` [(firstKey, firstSignature)]+      records <- expectRight (partialSignatures (inputAt 0 psbt))+      [(encodeHex (encodeSerial key), encodeHex signature) | (key, signature) <- records] `shouldBe` [(firstKey, firstSignature)]      it "write a partial signature under the type 0x02 with the public key, and drop them all as a finalizer does" $ do-      let m = insertPartialSignature ctx (publicKey firstKey) (hexBytes firstSignature) (insertSigHashType sigHashAll Map.empty)+      let m = insertPartialSignature (publicKey firstKey) (hexBytes firstSignature) (insertSigHashType sigHashAll Map.empty)       Map.toList m `shouldBe` [(Key 0x02 (hexBytes firstKey), hexBytes firstSignature), (Key 0x03 "", hexBytes "01000000")]       Map.toList (deletePartialSignatures m) `shouldBe` [(Key 0x03 "", hexBytes "01000000")] @@ -737,19 +737,19 @@      it "read the extended public keys of the global map, with their derivations, and write them under the type 0x01" $ do       psbt <- psbtOfVector (vectors.valid !! 7)-      let xpub = fromJust $ xPubImport btc ctx "xpub6CpGH79LXVkeiux2ZPWMpEubBrRfgcGCgy2HiagyN6NW3qdioJaqFYyD1fG6LDfxWEhMXJqcDuU5VneKt5UQYUGPa5Mfxdw2D2NArwX5TBm"+      let xpub = fromJust $ xPubImport btc "xpub6CpGH79LXVkeiux2ZPWMpEubBrRfgcGCgy2HiagyN6NW3qdioJaqFYyD1fG6LDfxWEhMXJqcDuU5VneKt5UQYUGPa5Mfxdw2D2NArwX5TBm"           record = (xpub, Derivation (fingerprintOf "27569c50") "m/49'/0'/0'")-      xpubRecords btc ctx psbt.globals `shouldBe` Right [record]-      let m = insertXpubRecord btc ctx xpub (snd record) Map.empty-      Map.keys m `shouldBe` [Key 0x01 (marshal (btc, ctx) xpub)]-      xpubRecords btc ctx m `shouldBe` Right [record]+      xpubRecords btc psbt.globals `shouldBe` Right [record]+      let m = insertXpubRecord btc xpub (snd record) Map.empty+      Map.keys m `shouldBe` [Key 0x01 (marshal btc xpub)]+      xpubRecords btc m `shouldBe` Right [record]      -- The two keys of the vector are of the test network     it "leave aside the extended public keys of another network" $ do       psbt <- psbtOfVector (vectors.valid !! 5)-      let tpub text = fromJust $ xPubImport btcTest ctx text-      xpubRecords btc ctx psbt.globals `shouldBe` Right []-      xpubRecords btcTest ctx psbt.globals+      let tpub text = fromJust $ xPubImport btcTest text+      xpubRecords btc psbt.globals `shouldBe` Right []+      xpubRecords btcTest psbt.globals         `shouldBe` Right           [ (tpub "tpubDBkJeJo2X94Yq3RVz65DoUgyLUkaDrkfyrn2VcgyCRSKCRonvKvCF2FpYDGJWDkdRHBajXJGpc63GnumUt63ySvqCu2XaTRGVTKMYGuFk9H", Derivation (fingerprintOf "d90c6a4f") "m/174'/0'"),             (tpub "tpubDBkJeJo2X94YsvtBEU1eKoibEWiNv51nW5iHhs6VZp59jsE6nen8KZMFyGHuGbCvqjRqirgeMcfpVBkttpUUT6brm4duzSGoZeTbhqCNUu6", Derivation (fingerprintOf "d90c6a4f") "m/174'/1'")@@ -773,10 +773,10 @@ -- two outputs, as a PSBT with the coin on its input: the whole previous -- transaction, or the output alone for a Taproot coin, whose signature -- commits to the output of every input (BIP 341)-spendingPsbt :: Ctx -> ScriptOutput -> (Psbt, [(ScriptOutput, Word64, OutPoint)])-spendingPsbt ctx coinScript = (Psbt Version0 tx Map.empty [input] [Map.empty, Map.empty], [(coinScript, 200000000, outpoint)])+spendingPsbt :: ScriptOutput -> (Psbt, [(ScriptOutput, Word64, OutPoint)])+spendingPsbt coinScript = (Psbt Version0 tx Map.empty [input] [Map.empty, Map.empty], [(coinScript, 200000000, outpoint)])   where-    parent = Tx 1 [TxIn (OutPoint "e567952fb6cc33857f392efa3a46c995a28f69cca4bb1b37e0204dab1ec7a389" 1) "" 0xffffffff] [TxOut 200000000 (marshal ctx coinScript)] [] 0+    parent = Tx 1 [TxIn (OutPoint "e567952fb6cc33857f392efa3a46c995a28f69cca4bb1b37e0204dab1ec7a389" 1) "" 0xffffffff] [TxOut 200000000 (encodeSerial coinScript)] [] 0     outpoint = OutPoint (txHash parent) 0     tx =       Tx@@ -788,129 +788,129 @@         []         1257139     input = case coinScript of-      PayWitness 1 _ -> insertWitnessUtxo (TxOut 200000000 (marshal ctx coinScript)) Map.empty+      PayWitness 1 _ -> insertWitnessUtxo (TxOut 200000000 (encodeSerial coinScript)) Map.empty       _ -> insertNonWitnessUtxo parent Map.empty  -- | A derivation record of a key, which a signer needs: the fingerprint -- and the path are those of the BIP's first signer-recordOf :: Ctx -> PublicKey -> PsbtMap -> PsbtMap-recordOf ctx public = insertInputDerivation ctx public (Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/0'")+recordOf :: PublicKey -> PsbtMap -> PsbtMap+recordOf public = insertInputDerivation public (Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/0'")  -- | A signer holding the keys-keysSigner :: Ctx -> [PrivateKey] -> Signer-keysSigner ctx keys =+keysSigner :: [PrivateKey] -> Signer+keysSigner keys =   Signer-    { keyOfRecord = \public derivation -> listToMaybe (mapMaybe (\key -> (keySigner ctx key.key).keyOfRecord public derivation) keys),-      keyOfHash = \h -> listToMaybe (mapMaybe (\key -> (keySigner ctx key.key).keyOfHash h) keys),+    { keyOfRecord = \public derivation -> listToMaybe (mapMaybe (\key -> (keySigner key.key).keyOfRecord public derivation) keys),+      keyOfHash = \h -> listToMaybe (mapMaybe (\key -> (keySigner key.key).keyOfHash h) keys),       acceptedSigHashes = defaultSigHashes,       requirePreviousTx = True     }  -- | Whether the transaction of the PSBT, once signed with the keys and -- finalized, verifies against the coins it spends-signsAndVerifies :: Network -> Ctx -> [PrivateKey] -> (Psbt, [(ScriptOutput, Word64, OutPoint)]) -> Either String Bool-signsAndVerifies net ctx keys (psbt, coins) = do-  signed <- signPsbt net ctx (keysSigner ctx keys) psbt-  final <- finalizePsbt net ctx signed+signsAndVerifies :: Network -> [PrivateKey] -> (Psbt, [(ScriptOutput, Word64, OutPoint)]) -> Either String Bool+signsAndVerifies net keys (psbt, coins) = do+  signed <- signPsbt net (keysSigner keys) psbt+  final <- finalizePsbt net signed   tx <- psbtTransaction final-  return (verifyStdTx net ctx tx coins)+  return (verifyStdTx net tx coins) -signingSpec :: Ctx -> Spec-signingSpec ctx =+signingSpec :: Spec+signingSpec =   describe "Signing and finalizing" $ do     prop "a P2PKH coin, signed with the key of its address and finalized, verifies" $-      forAll (arbitraryKeyPair ctx) $ \(secret, public) ->-        let (psbt, coins) = spendingPsbt ctx (PayPKHash (addressHash (marshal ctx public)))-            withRecord = withInputs (recordOf ctx public <$> psbt.inputs) psbt-         in signsAndVerifies btc ctx [secret] (withRecord, coins) === Right True+      forAll arbitraryKeyPair $ \(secret, public) ->+        let (psbt, coins) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))+            withRecord = withInputs (recordOf public <$> psbt.inputs) psbt+         in signsAndVerifies btc [secret] (withRecord, coins) === Right True      -- The finalized input keeps its coin, its final script, and the     -- fields of version 2: the transaction it spends from, the output     -- index and the sequence     prop "a P2PKH coin of a PSBT of version 2, signed and finalized, verifies, and the PSBT stays of version 2 with the fields of its input" $-      forAll (arbitraryKeyPair ctx) $ \(secret, public) ->-        let (psbt, coins) = spendingPsbt ctx (PayPKHash (addressHash (marshal ctx public)))-            version2 = withVersion Version2 (withInputs (recordOf ctx public <$> psbt.inputs) psbt)-            final = finalizePsbt btc ctx =<< signPsbt btc ctx (keysSigner ctx [secret]) version2-         in (signsAndVerifies btc ctx [secret] (version2, coins), (.version) <$> final, Map.keys . inputAt 0 <$> final)+      forAll arbitraryKeyPair $ \(secret, public) ->+        let (psbt, coins) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))+            version2 = withVersion Version2 (withInputs (recordOf public <$> psbt.inputs) psbt)+            final = finalizePsbt btc =<< signPsbt btc (keysSigner [secret]) version2+         in (signsAndVerifies btc [secret] (version2, coins), (.version) <$> final, Map.keys . inputAt 0 <$> final)               === (Right True, Right Version2, Right [Key 0x00 "", Key 0x07 "", Key 0x0e "", Key 0x0f "", Key 0x10 ""])      prop "a P2SH multisig coin, signed with enough of its keys and finalized, verifies" $       -- At most 7 keys: the redeem script of more uncompressed keys would be       -- over the 520 bytes a P2SH redeem script can have-      forAll ((,) <$> arbitraryP2SHMSParam <*> arbitraryKeyPair ctx) $ \((m, n), _) ->-        forAll (vectorOf n (arbitraryKeyPair ctx)) $ \pairs ->-          let redeem = either error id $ encodeOutput ctx (PayMulSig (snd <$> pairs) m)-              (psbt, coins) = spendingPsbt ctx (either error id (toP2SH redeem))-              withFields = withInputs ((insertInputRedeemScript redeem . foldr (\(_, public) f -> recordOf ctx public . f) id pairs) <$> psbt.inputs) psbt-           in signsAndVerifies btc ctx (fst <$> take m pairs) (withFields, coins) === Right True+      forAll ((,) <$> arbitraryP2SHMSParam <*> arbitraryKeyPair) $ \((m, n), _) ->+        forAll (vectorOf n arbitraryKeyPair) $ \pairs ->+          let redeem = either error id $ encodeOutput (PayMulSig (snd <$> pairs) m)+              (psbt, coins) = spendingPsbt (either error id (toP2SH redeem))+              withFields = withInputs ((insertInputRedeemScript redeem . foldr (\(_, public) f -> recordOf public . f) id pairs) <$> psbt.inputs) psbt+           in signsAndVerifies btc (fst <$> take m pairs) (withFields, coins) === Right True      -- The keys are compressed: a SegWit version 0 coin is not signed with     -- an uncompressed key, which 'signerScopeSpec' tests     prop "a P2WPKH coin, and a P2SH-P2WPKH one with its redeem script, signed and finalized, verify" $-      forAll (arbitraryKeyPairC ctx) $ \(secret, public) ->-        let program = PayWitnessPKHash (addressHash (marshal ctx public))-            (native, nativeCoins) = spendingPsbt ctx program-            redeem = either error id $ encodeOutput ctx program-            (nested, nestedCoins) = spendingPsbt ctx (either error id (toP2SH redeem))-            nativeWithRecord = withInputs (recordOf ctx public <$> native.inputs) native-            nestedWithFields = withInputs ((insertInputRedeemScript redeem . recordOf ctx public) <$> nested.inputs) nested-         in signsAndVerifies btc ctx [secret] (nativeWithRecord, nativeCoins) === Right True-              .&&. signsAndVerifies btc ctx [secret] (nestedWithFields, nestedCoins) === Right True+      forAll arbitraryKeyPairC $ \(secret, public) ->+        let program = PayWitnessPKHash (addressHash (encodeSerial public))+            (native, nativeCoins) = spendingPsbt program+            redeem = either error id $ encodeOutput program+            (nested, nestedCoins) = spendingPsbt (either error id (toP2SH redeem))+            nativeWithRecord = withInputs (recordOf public <$> native.inputs) native+            nestedWithFields = withInputs ((insertInputRedeemScript redeem . recordOf public) <$> nested.inputs) nested+         in signsAndVerifies btc [secret] (nativeWithRecord, nativeCoins) === Right True+              .&&. signsAndVerifies btc [secret] (nestedWithFields, nestedCoins) === Right True      prop "a P2WSH multisig coin with its witness script, nested in P2SH or not, signed and finalized, verifies" $       forAll arbitraryMSParam $ \(m, n) ->-        forAll (vectorOf n (arbitraryKeyPairC ctx)) $ \pairs ->-          let witness = either error id $ encodeOutput ctx (PayMulSig (snd <$> pairs) m)+        forAll (vectorOf n arbitraryKeyPairC) $ \pairs ->+          let witness = either error id $ encodeOutput (PayMulSig (snd <$> pairs) m)               program = either error id (toP2WSH witness)-              records = foldr (\(_, public) f -> recordOf ctx public . f) id pairs-              (native, nativeCoins) = spendingPsbt ctx program-              (nested, nestedCoins) = spendingPsbt ctx (either error id (toP2SH programScript))+              records = foldr (\(_, public) f -> recordOf public . f) id pairs+              (native, nativeCoins) = spendingPsbt program+              (nested, nestedCoins) = spendingPsbt (either error id (toP2SH programScript))               nativeWithFields = withInputs ((insertInputWitnessScript witness . records) <$> native.inputs) native               nestedWithFields = withInputs ((insertInputRedeemScript programScript . insertInputWitnessScript witness . records) <$> nested.inputs) nested-              programScript = either error id $ encodeOutput ctx program-           in signsAndVerifies btc ctx (fst <$> take m pairs) (nativeWithFields, nativeCoins) === Right True-                .&&. signsAndVerifies btc ctx (fst <$> take m pairs) (nestedWithFields, nestedCoins) === Right True+              programScript = either error id $ encodeOutput program+           in signsAndVerifies btc (fst <$> take m pairs) (nativeWithFields, nativeCoins) === Right True+                .&&. signsAndVerifies btc (fst <$> take m pairs) (nestedWithFields, nestedCoins) === Right True      it "signs with the sighash the input asks for when the signer accepts it, SIGHASH_ALL when it asks for none" $ do       let secret = PrivateKey secretOne True-          public = derivePublicKey ctx secret-          (psbt, _) = spendingPsbt ctx (PayPKHash (addressHash (marshal ctx public)))-          asking sh = withInputs ((recordOf ctx public . maybe id insertSigHashType sh) <$> psbt.inputs) psbt-          sighashOf signed = map (B.last . snd) <$> partialSignatures ctx (inputAt 0 signed)-          acceptingNone = (keySigner ctx secret.key) {acceptedSigHashes = sigHashNone : defaultSigHashes}-      (sighashOf =<< signPsbt btc ctx (keySigner ctx secret.key) (asking Nothing)) `shouldBe` Right [0x01]-      (sighashOf =<< signPsbt btc ctx (keySigner ctx secret.key) (asking (Just sigHashAll))) `shouldBe` Right [0x01]+          public = derivePublicKey secret+          (psbt, _) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))+          asking sh = withInputs ((recordOf public . maybe id insertSigHashType sh) <$> psbt.inputs) psbt+          sighashOf signed = map (B.last . snd) <$> partialSignatures (inputAt 0 signed)+          acceptingNone = (keySigner secret.key) {acceptedSigHashes = sigHashNone : defaultSigHashes}+      (sighashOf =<< signPsbt btc (keySigner secret.key) (asking Nothing)) `shouldBe` Right [0x01]+      (sighashOf =<< signPsbt btc (keySigner secret.key) (asking (Just sigHashAll))) `shouldBe` Right [0x01]       -- SIGHASH_NONE leaves the outputs unsigned, so the signer must agree to it-      signPsbt btc ctx (keySigner ctx secret.key) (asking (Just sigHashNone)) `shouldBe` Left "Input 0: the sighash type 2 is not one the signer accepts"-      (sighashOf =<< signPsbt btc ctx acceptingNone (asking (Just sigHashNone))) `shouldBe` Right [0x02]+      signPsbt btc (keySigner secret.key) (asking (Just sigHashNone)) `shouldBe` Left "Input 0: the sighash type 2 is not one the signer accepts"+      (sighashOf =<< signPsbt btc acceptingNone (asking (Just sigHashNone))) `shouldBe` Right [0x02]      it "leaves an input without its coin, or signed already, as it is" $ do       let secret = PrivateKey secretOne True-          public = derivePublicKey ctx secret-          (psbt, _) = spendingPsbt ctx (PayPKHash (addressHash (marshal ctx public)))-          withoutCoin = withInputs [recordOf ctx public Map.empty] psbt-          final = withInputs ((insertFinalScriptSig "a script" . recordOf ctx public) <$> psbt.inputs) psbt-      signPsbt btc ctx (keySigner ctx secret.key) withoutCoin `shouldBe` Right withoutCoin-      signPsbt btc ctx (keySigner ctx secret.key) final `shouldBe` Right final+          public = derivePublicKey secret+          (psbt, _) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))+          withoutCoin = withInputs [recordOf public Map.empty] psbt+          final = withInputs ((insertFinalScriptSig "a script" . recordOf public) <$> psbt.inputs) psbt+      signPsbt btc (keySigner secret.key) withoutCoin `shouldBe` Right withoutCoin+      signPsbt btc (keySigner secret.key) final `shouldBe` Right final      it "refuses a previous transaction that is not the one the input spends" $ do-      let public = compressedKey ctx secretOne-          (psbt, _) = spendingPsbt ctx (PayPKHash (addressHash (marshal ctx public)))+      let public = compressedKey secretOne+          (psbt, _) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))           wrong = withInputs [insertNonWitnessUtxo emptyTx Map.empty] psbt-      signPsbt btc ctx (Signer (\_ _ -> Nothing) (const Nothing) defaultSigHashes True) wrong `shouldBe` Left "Input 0: the previous transaction is not the one the input spends"+      signPsbt btc (Signer (\_ _ -> Nothing) (const Nothing) defaultSigHashes True) wrong `shouldBe` Left "Input 0: the previous transaction is not the one the input spends"      -- The derivation records name keys by the master key, b4a6ba67 with     -- the full path, or by the extended key given, with the path from it     it "finds the key an extended private key derives, by its own fingerprint or by the origin given" $ do       let root = makeXPrvKey "PSBT signer test"-          rootFingerprint = xPubFP ctx (deriveXPubKey ctx root)-          account = derivePath ctx (Deriv :| 444 :: HardPath) root-          accountFingerprint = xPubFP ctx (deriveXPubKey ctx account)-          secretAt path = (derivePath ctx (path :: DerivPath) root).key-          publicOf secret = PublicKey (derivePubKey ctx secret) True-          signer = xPrvSigner ctx account (Just (Derivation rootFingerprint "m/444'"))-          unknownOrigin = xPrvSigner ctx account Nothing+          rootFingerprint = xPubFP (deriveXPubKey root)+          account = derivePath (Deriv :| 444 :: HardPath) root+          accountFingerprint = xPubFP (deriveXPubKey account)+          secretAt path = (derivePath (path :: DerivPath) root).key+          publicOf secret = PublicKey (derivePubKey secret) True+          signer = xPrvSigner account (Just (Derivation rootFingerprint "m/444'"))+          unknownOrigin = xPrvSigner account Nothing       signer.keyOfRecord (publicOf (secretAt "m/444'/0")) (Derivation rootFingerprint "m/444'/0") `shouldBe` Just (secretAt "m/444'/0")       signer.keyOfRecord (publicOf (secretAt "m/444'/1")) (Derivation accountFingerprint "m/1") `shouldBe` Just (secretAt "m/444'/1")       signer.keyOfRecord (publicOf (secretAt "m/444'/1")) (Derivation rootFingerprint "m/445'/1") `shouldBe` Nothing@@ -918,7 +918,7 @@       unknownOrigin.keyOfRecord (publicOf (secretAt "m/444'/0")) (Derivation rootFingerprint "m/444'/0") `shouldBe` Nothing       unknownOrigin.keyOfRecord (publicOf (secretAt "m/444'/0")) (Derivation accountFingerprint "m/0") `shouldBe` Just (secretAt "m/444'/0")       -- An extended key cannot know which path a hash is at-      signer.keyOfHash (addressHash (marshal ctx (publicOf (secretAt "m/444'/0")))) `shouldBe` Nothing+      signer.keyOfHash (addressHash (encodeSerial (publicOf (secretAt "m/444'/0")))) `shouldBe` Nothing  {- A PSBT of every kind of coin -} @@ -945,13 +945,13 @@     where       psbtAt o name = either fail return . decodePsbtBase64 . encodeUtf8 =<< o .: name -complexSpec :: Ctx -> Spec-complexSpec ctx = do+complexSpec :: Spec+complexSpec = do   -- data/complex_psbt.json is the file of an older Bitcoin Core, in   -- version 0. Each wallet finalized the coins it could complete alone.   describe "The PSBT of nine coins of every kind, which twelve wallets of Bitcoin Core signed one at a time" $ do     complex <- runIO (readTestFile "complex_psbt.json" :: IO Complex)-    complexChecks ctx complex+    complexChecks complex    -- data/psbt_complex_core32.json is the file of Bitcoin Core 32.1, in   -- version 2. The wallets signed with finalize=false, so that the@@ -963,12 +963,12 @@       length complex.combinedPsbt.inputs `shouldBe` 9       -- Types 0x07 and 0x08 are the final script and the final witness       length [key | input <- complex.combinedPsbt.inputs, key <- Map.keys input, key.keyType `elem` [0x07, 0x08]] `shouldBe` 0-    complexChecks ctx complex+    complexChecks complex  -- | What holds for both files: the library combines, finalizes and -- extracts what Bitcoin Core combined, finalized and extracted-complexChecks :: Ctx -> Complex -> Spec-complexChecks ctx complex = do+complexChecks :: Complex -> Spec+complexChecks complex = do   -- The PSBT Core created has no entry that a signed one lacks   it "adds nothing to a signed PSBT when the PSBT Core created is combined with it" $     mapM (combinePsbt complex.initialPsbt) complex.signedPsbts `shouldBe` Right complex.signedPsbts@@ -979,7 +979,7 @@       [] -> expectationFailure "No signed PSBT"    it "finalizes into the PSBT Core finalized" $-    finalizePsbt btc ctx complex.combinedPsbt `shouldBe` Right complex.completePsbt+    finalizePsbt btc complex.combinedPsbt `shouldBe` Right complex.completePsbt    it "gives the transaction Core extracted" $     psbtTransaction complex.completePsbt `shouldBe` Right complex.finalTx@@ -1009,8 +1009,8 @@     where       psbtAt o name = either fail return . decodePsbtBase64 . encodeUtf8 =<< o .: name -core32Spec :: Ctx -> Spec-core32Spec ctx =+core32Spec :: Spec+core32Spec =   describe "The files of Bitcoin Core 32.1, which writes version 2 unless asked for version 0" $ do     core <- runIO (readTestFile "psbt_core32.json" :: IO Core32)     it "are the same payment in both versions: the version 2 file is the version 0 file converted, and back" $ do@@ -1020,7 +1020,7 @@       withVersion Version0 core.preparedV2 `shouldBe` core.preparedV0      it "finalize into the PSBT Core finalized" $-      finalizePsbt btc ctx core.signedV2 `shouldBe` Right core.finalizedV2+      finalizePsbt btc core.signedV2 `shouldBe` Right core.finalizedV2      it "give the transaction Core extracted" $       psbtTransaction core.finalizedV2 `shouldBe` Right core.extractedTx@@ -1031,28 +1031,28 @@     -- key.     it "are signed with the account key the records name, into a transaction that verifies" $ do       let account = fromJust (xPrvImport btc "xprv9yHxeaLAZvxXb9VtJNesqk8avfN8misGAW9DUW9eacZJNqsfZxqKLmK5jfmvFideQqGesviJeagzSQYCuQySjgvt7TdfowKja5aJqbgyuNh")-          signer = xPrvSigner ctx account (Just (Derivation (fingerprintOf "bc560f95") "m/44'/0'/0'"))-      coin <- expectRight (unmarshal ctx (hexBytes "76a914c80d55223e2f1061363add2a7b0363c285bf298d88ac"))-      final <- expectRight (finalizePsbt btc ctx =<< signPsbt btc ctx signer core.preparedV2)+          signer = xPrvSigner account (Just (Derivation (fingerprintOf "bc560f95") "m/44'/0'/0'"))+      coin <- expectRight (decodeSerial (hexBytes "76a914c80d55223e2f1061363add2a7b0363c285bf298d88ac"))+      final <- expectRight (finalizePsbt btc =<< signPsbt btc signer core.preparedV2)       tx <- expectRight (psbtTransaction final)       final.version `shouldBe` Version2-      verifyStdTx btc ctx tx [(coin, 5000000000, OutPoint "fede72ccadbf9f16f826e3078578b0660526a37b48d4f894ab26f4cf5a95e89c" 0)] `shouldBe` True+      verifyStdTx btc tx [(coin, 5000000000, OutPoint "fede72ccadbf9f16f826e3078578b0660526a37b48d4f894ab26f4cf5a95e89c" 0)] `shouldBe` True  {- The checks of the signer and the finalizer -} -signerChecksSpec :: Ctx -> Spec-signerChecksSpec ctx =+signerChecksSpec :: Spec+signerChecksSpec =   describe "The checks of the signer and the finalizer" $ do     let secret = PrivateKey secretOne True-        public = derivePublicKey ctx secret-        otherPublic = compressedKey ctx secretTwo-        (psbt, coins) = spendingPsbt ctx (PayPKHash (addressHash (marshal ctx public)))+        public = derivePublicKey secret+        otherPublic = compressedKey secretTwo+        (psbt, coins) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))         parent = fromJust (either (const Nothing) id (nonWitnessUtxo (inputAt 0 psbt)))         coin = head parent.outputs         withInput m = withInputs [m] psbt-        signer = keySigner ctx secret.key-        signed m = signPsbt btc ctx signer (withInput (recordOf ctx public m))-        signatureCount s = fmap length (partialSignatures ctx (inputAt 0 s))+        signer = keySigner secret.key+        signed m = signPsbt btc signer (withInput (recordOf public m))+        signatureCount s = fmap length (partialSignatures (inputAt 0 s))      it "refuses to sign a legacy coin known from its witness output only, which only a witness signature may use" $       signed (insertWitnessUtxo coin Map.empty)@@ -1067,54 +1067,54 @@       signed (insertSigHashType 0 (insertNonWitnessUtxo parent Map.empty)) `shouldBe` Left "Input 0: the sighash type 0 is not one a node accepts"       signed (insertSigHashType 0x21 (insertNonWitnessUtxo parent Map.empty)) `shouldBe` Left "Input 0: the sighash type 33 is not one a node accepts"       signed (insertSigHashType (setForkIdFlag sigHashAll) (insertNonWitnessUtxo parent Map.empty)) `shouldBe` Left "Input 0: the sighash type has a fork id flag the network does not use"-      signPsbt bch ctx signer (withInput (recordOf ctx public (insertSigHashType sigHashAll (insertNonWitnessUtxo parent Map.empty))))+      signPsbt bch signer (withInput (recordOf public (insertSigHashType sigHashAll (insertNonWitnessUtxo parent Map.empty))))         `shouldBe` Left "Input 0: the sighash type lacks the fork id flag the network requires"       -- With the flag, the Bitcoin Cash digest signs-      (signatureCount =<< signPsbt bch ctx signer (withInput (recordOf ctx public (insertSigHashType (setForkIdFlag sigHashAll) (insertNonWitnessUtxo parent Map.empty))))) `shouldBe` Right 1+      (signatureCount =<< signPsbt bch signer (withInput (recordOf public (insertSigHashType (setForkIdFlag sigHashAll) (insertNonWitnessUtxo parent Map.empty))))) `shouldBe` Right 1      it "refuses a sighash type the signer does not accept, and signs with it once the signer lists it" $ do       let acceptingSingle = signer {acceptedSigHashes = [sigHashSingle]}           askingSingle = insertSigHashType sigHashSingle (insertNonWitnessUtxo parent Map.empty)       signed askingSingle `shouldBe` Left "Input 0: the sighash type 3 is not one the signer accepts"-      (signatureCount =<< signPsbt btc ctx acceptingSingle (withInput (recordOf ctx public askingSingle))) `shouldBe` Right 1+      (signatureCount =<< signPsbt btc acceptingSingle (withInput (recordOf public askingSingle))) `shouldBe` Right 1       -- ANYONECANPAY makes another type: 0x81 is not 0x01       signed (insertSigHashType (setAnyoneCanPay sigHashAll) (insertNonWitnessUtxo parent Map.empty)) `shouldBe` Left "Input 0: the sighash type 129 is not one the signer accepts"      -- Two coins of the same script, spent by one transaction with one     -- output: input 1 has no output at its index     it "refuses SIGHASH_SINGLE on a legacy coin whose input has no output at its index, and signs it on a SegWit coin" $ do-      let witnessCoin = TxOut 200000000 (marshal ctx (PayWitnessPKHash (addressHash (marshal ctx public))))+      let witnessCoin = TxOut 200000000 (encodeSerial (PayWitnessPKHash (addressHash (encodeSerial public))))           parentOf c = Tx 1 [TxIn (OutPoint "e567952fb6cc33857f392efa3a46c995a28f69cca4bb1b37e0204dab1ec7a389" 1) "" 0xffffffff] [c, c] [] 0           spendingBoth p = Tx 2 [TxIn (OutPoint (txHash p) 0) "" 0xfffffffe, TxIn (OutPoint (txHash p) 1) "" 0xfffffffe] [TxOut 399999000 (hexBytes "76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac")] [] 0-          askingSingle p = recordOf ctx public (insertSigHashType sigHashSingle (insertNonWitnessUtxo p Map.empty))+          askingSingle p = recordOf public (insertSigHashType sigHashSingle (insertNonWitnessUtxo p Map.empty))           psbtOf p = Psbt Version0 (spendingBoth p) Map.empty [askingSingle p, askingSingle p] [Map.empty]           acceptingSingle = signer {acceptedSigHashes = [sigHashSingle]}-      signPsbt btc ctx acceptingSingle (psbtOf (parentOf coin)) `shouldBe` Left "Input 1: makeSignature: SIGHASH_SINGLE without an output at the input index"+      signPsbt btc acceptingSingle (psbtOf (parentOf coin)) `shouldBe` Left "Input 1: makeSignature: SIGHASH_SINGLE without an output at the input index"       -- The BIP 143 digest commits to the coin, so the SegWit signature is fine-      (signatureCount =<< signPsbt btc ctx acceptingSingle (psbtOf (parentOf witnessCoin))) `shouldBe` Right 1-      (fmap length . partialSignatures ctx . inputAt 1 =<< signPsbt btc ctx acceptingSingle (psbtOf (parentOf witnessCoin))) `shouldBe` Right 1+      (signatureCount =<< signPsbt btc acceptingSingle (psbtOf (parentOf witnessCoin))) `shouldBe` Right 1+      (fmap length . partialSignatures . inputAt 1 =<< signPsbt btc acceptingSingle (psbtOf (parentOf witnessCoin))) `shouldBe` Right 1      it "refuses a redeem script that does not hash to the coin, and one on a coin that is not pay-to-script-hash" $ do       let ms = PayMulSig [public, otherPublic] 1-          msScript = either error id (encodeOutput ctx ms)-          wrongScript = either error id (encodeOutput ctx (PayMulSig [otherPublic, public] 1))-          (p2sh, _) = spendingPsbt ctx (either error id (toP2SH msScript))+          msScript = either error id (encodeOutput ms)+          wrongScript = either error id (encodeOutput (PayMulSig [otherPublic, public] 1))+          (p2sh, _) = spendingPsbt (either error id (toP2SH msScript))           p2shParent = fromJust (either (const Nothing) id (nonWitnessUtxo (inputAt 0 p2sh)))-          p2shInput m = withInputs [recordOf ctx public (insertNonWitnessUtxo p2shParent m)] p2sh-      (signatureCount =<< signPsbt btc ctx signer (p2shInput (insertInputRedeemScript msScript Map.empty))) `shouldBe` Right 1-      signPsbt btc ctx signer (p2shInput (insertInputRedeemScript wrongScript Map.empty))+          p2shInput m = withInputs [recordOf public (insertNonWitnessUtxo p2shParent m)] p2sh+      (signatureCount =<< signPsbt btc signer (p2shInput (insertInputRedeemScript msScript Map.empty))) `shouldBe` Right 1+      signPsbt btc signer (p2shInput (insertInputRedeemScript wrongScript Map.empty))         `shouldBe` Left "Input 0: the redeem script of the input does not hash to its coin"       signed (insertInputRedeemScript msScript (insertNonWitnessUtxo parent Map.empty))         `shouldBe` Left "Input 0: the input has a redeem script, but its coin is not pay-to-script-hash"      it "refuses a witness script that does not hash to the witness program" $ do       let ms = PayMulSig [public, otherPublic] 1-          msScript = either error id (encodeOutput ctx ms)-          wrongScript = either error id (encodeOutput ctx (PayMulSig [otherPublic, public] 1))-          (p2wsh, _) = spendingPsbt ctx (either error id (toP2WSH msScript))-          p2wshInput m = withInputs [recordOf ctx public (Map.union m (inputAt 0 p2wsh))] p2wsh-      (signatureCount =<< signPsbt btc ctx signer (p2wshInput (insertInputWitnessScript msScript Map.empty))) `shouldBe` Right 1-      signPsbt btc ctx signer (p2wshInput (insertInputWitnessScript wrongScript Map.empty))+          msScript = either error id (encodeOutput ms)+          wrongScript = either error id (encodeOutput (PayMulSig [otherPublic, public] 1))+          (p2wsh, _) = spendingPsbt (either error id (toP2WSH msScript))+          p2wshInput m = withInputs [recordOf public (Map.union m (inputAt 0 p2wsh))] p2wsh+      (signatureCount =<< signPsbt btc signer (p2wshInput (insertInputWitnessScript msScript Map.empty))) `shouldBe` Right 1+      signPsbt btc signer (p2wshInput (insertInputWitnessScript wrongScript Map.empty))         `shouldBe` Left "Input 0: the witness script of the input does not hash to its witness program"       signed (insertInputWitnessScript msScript (insertNonWitnessUtxo parent Map.empty))         `shouldBe` Left "Input 0: the input has a witness script, but its coin is not pay-to-witness-script-hash"@@ -1125,48 +1125,48 @@           op0 = OutPoint (txHash parent2) 0           op1 = OutPoint (txHash parent2) 1           tx = Tx 2 [TxIn op0 "" 0xfffffffe, TxIn op1 "" 0xfffffffe] psbt.unsignedTx.outputs [] 0-          both = Psbt Version0 tx Map.empty [recordOf ctx public (insertNonWitnessUtxo parent2 Map.empty), insertNonWitnessUtxo parent2 Map.empty] [Map.empty, Map.empty]-      s <- expectRight (signPsbt btc ctx signer both)+          both = Psbt Version0 tx Map.empty [recordOf public (insertNonWitnessUtxo parent2 Map.empty), insertNonWitnessUtxo parent2 Map.empty] [Map.empty, Map.empty]+      s <- expectRight (signPsbt btc signer both)       map hasPartialSignatures s.inputs `shouldBe` [True, False]-      f <- expectRight (finalizePsbt btc ctx s)+      f <- expectRight (finalizePsbt btc s)       map (isJust . finalScriptSig) f.inputs `shouldBe` [True, False]      it "signs a coin whose key it holds without a derivation record, by the hash of the key" $ do-      (signatureCount =<< signPsbt btc ctx signer (withInput (insertNonWitnessUtxo parent Map.empty))) `shouldBe` Right 1+      (signatureCount =<< signPsbt btc signer (withInput (insertNonWitnessUtxo parent Map.empty))) `shouldBe` Right 1       -- A multisig coin names its keys       let ms = PayMulSig [public, otherPublic] 1-          msScript = either error id (encodeOutput ctx ms)-          (p2sh, p2shCoins) = spendingPsbt ctx (either error id (toP2SH msScript))+          msScript = either error id (encodeOutput ms)+          (p2sh, p2shCoins) = spendingPsbt (either error id (toP2SH msScript))           p2shParent = fromJust (either (const Nothing) id (nonWitnessUtxo (inputAt 0 p2sh)))           p2shFields = withInputs [insertInputRedeemScript msScript (insertNonWitnessUtxo p2shParent Map.empty)] p2sh-      s <- expectRight (signPsbt btc ctx signer p2shFields)+      s <- expectRight (signPsbt btc signer p2shFields)       signatureCount s `shouldBe` Right 1-      signsAndVerifies btc ctx [secret] (p2shFields, p2shCoins) `shouldBe` Right True+      signsAndVerifies btc [secret] (p2shFields, p2shCoins) `shouldBe` Right True       -- The other key is not held-      (signatureCount =<< signPsbt btc ctx (keySigner ctx secret.key) (fst (spendingPsbt ctx (PayPKHash (addressHash (marshal ctx otherPublic)))))) `shouldBe` Right 0+      (signatureCount =<< signPsbt btc (keySigner secret.key) (fst (spendingPsbt (PayPKHash (addressHash (encodeSerial otherPublic)))))) `shouldBe` Right 0       coins `seq` return ()      it "the finalizer refuses a signature that is not a signature, one with another sighash type than the input asks, and one that does not verify" $ do       s <- expectRight (signed (insertNonWitnessUtxo parent Map.empty))-      signature <- case either error id (partialSignatures ctx (inputAt 0 s)) of+      signature <- case either error id (partialSignatures (inputAt 0 s)) of         [(_, sig)] -> return sig         _ -> fail "one signature"-      let withSig sig m = withInput (insertPartialSignature ctx public sig m)-          keyHex = show (encodeHex (marshal ctx public))-      finalizePsbt btc ctx (withSig "3045aa" (insertNonWitnessUtxo parent Map.empty))+      let withSig sig m = withInput (insertPartialSignature public sig m)+          keyHex = show (encodeHex (encodeSerial public))+      finalizePsbt btc (withSig "3045aa" (insertNonWitnessUtxo parent Map.empty))         `shouldBe` Left ("Input 0: the signature of the key " <> keyHex <> " is not a valid signature")-      finalizePsbt btc ctx (withSig signature (insertSigHashType sigHashNone (insertNonWitnessUtxo parent Map.empty)))+      finalizePsbt btc (withSig signature (insertSigHashType sigHashNone (insertNonWitnessUtxo parent Map.empty)))         `shouldBe` Left ("Input 0: the signature of the key " <> keyHex <> " does not use the sighash type of the input")       -- The signature of the same key on another transaction-      let sameKeyOther = withInputs [recordOf ctx public (insertNonWitnessUtxo parent Map.empty)] (Psbt Version0 (Tx 2 psbt.unsignedTx.inputs [] [] 0) Map.empty psbt.inputs [])-      elsewhere <- expectRight (signPsbt btc ctx signer sameKeyOther)-      foreignSig <- case either error id (partialSignatures ctx (inputAt 0 elsewhere)) of+      let sameKeyOther = withInputs [recordOf public (insertNonWitnessUtxo parent Map.empty)] (Psbt Version0 (Tx 2 psbt.unsignedTx.inputs [] [] 0) Map.empty psbt.inputs [])+      elsewhere <- expectRight (signPsbt btc signer sameKeyOther)+      foreignSig <- case either error id (partialSignatures (inputAt 0 elsewhere)) of         [(_, sig)] -> return sig         _ -> fail "one signature"-      finalizePsbt btc ctx (withSig foreignSig (insertNonWitnessUtxo parent Map.empty))+      finalizePsbt btc (withSig foreignSig (insertNonWitnessUtxo parent Map.empty))         `shouldBe` Left ("Input 0: the signature of the key " <> keyHex <> " does not verify")       -- The right signature finalizes-      f <- expectRight (finalizePsbt btc ctx (withSig signature (insertNonWitnessUtxo parent Map.empty)))+      f <- expectRight (finalizePsbt btc (withSig signature (insertNonWitnessUtxo parent Map.empty)))       isJust (finalScriptSig (inputAt 0 f)) `shouldBe` True  {- Taproot -}@@ -1195,8 +1195,8 @@     "is not a control block"   ] -taprootSpec :: Ctx -> Vectors371 -> Spec-taprootSpec ctx vectors =+taprootSpec :: Vectors371 -> Spec+taprootSpec vectors =   describe "The Taproot fields of BIP 371" $ do     describe "the invalid PSBTs are refused, each for its reason" $       forM_ (zip vectors.refused371 refusals371) $ \(v, reason) ->@@ -1207,14 +1207,14 @@         it v.vecCase $ (encodePsbt <$> decodePsbt (bytesOf v)) `shouldBe` Right (bytesOf v)      let vectorAt i = psbtOfVector (vectors.accepted371 !! i)-        xOnly text = fromJust (importXOnlyPubKey ctx (hexBytes text))+        xOnly text = fromJust (importXOnlyPubKey (hexBytes text))         digest text = fromJust (digestFromByteString (hexBytes text)) :: Digest SHA256         keyScript text = Script [opPushData (hexBytes text), OP_CHECKSIG]      it "read the internal key and the derivation of a key path input" $ do       psbt <- vectorAt 0-      inputTapInternalKey ctx (inputAt 0 psbt) `shouldBe` Right (Just (xOnly "fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa232"))-      inputTapDerivations ctx (inputAt 0 psbt) `shouldBe` Right [(xOnly "fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa232", TapDerivation [] (Derivation (fingerprintOf "772b2da7") "m/86'/1'/0'/1/0"))]+      inputTapInternalKey (inputAt 0 psbt) `shouldBe` Right (Just (xOnly "fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa232"))+      inputTapDerivations (inputAt 0 psbt) `shouldBe` Right [(xOnly "fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa232", TapDerivation [] (Derivation (fingerprintOf "772b2da7") "m/86'/1'/0'/1/0"))]       inputTapMerkleRoot (inputAt 0 psbt) `shouldBe` Right Nothing       tapKeySig (inputAt 0 psbt) `shouldBe` Right Nothing @@ -1223,22 +1223,22 @@       let sigHex = "bb53ec917bad9d906af1ba87181c48b86ace5aae2b53605a725ca74625631476fc6f5baedaf4f2ee0f477f36f58f3970d5b8273b7e497b97af2e3f125c97af34"           sig = fromJust (schnorrSig (hexBytes sigHex))       tapKeySig (inputAt 0 psbt) `shouldBe` (Just <$> taprootSignature sig sigHashDefault)-      final <- expectRight (finalizePsbt btc ctx psbt)+      final <- expectRight (finalizePsbt btc psbt)       finalScriptWitness (inputAt 0 final) `shouldBe` Right (Just [hexBytes sigHex])       Map.keys (inputAt 0 final) `shouldBe` [Key 0x01 "", Key 0x08 ""]       tx <- expectRight (psbtTransaction final)       let coin = TxOut 5000000000 (hexBytes "51205a2c2cf5b52cf31f83ad2e8da63ff03183ecd8f609c7510ae8a48e03910a0757")-      verifyStdTx btc ctx tx [(either error id (unmarshal ctx coin.script), coin.value, (head tx.inputs).outpoint)] `shouldBe` True+      verifyStdTx btc tx [(either error id (decodeSerial coin.script), coin.value, (head tx.inputs).outpoint)] `shouldBe` True      it "read the internal key and the derivation of a key path output" $ do       psbt <- vectorAt 2-      outputTapInternalKey ctx (outputAt 0 psbt) `shouldBe` Right (Just (xOnly "1124da7aec92ccd06c954562647f437b138b95721a84be2bf2276bbddab3e671"))-      outputTapDerivations ctx (outputAt 0 psbt) `shouldBe` Right [(xOnly "1124da7aec92ccd06c954562647f437b138b95721a84be2bf2276bbddab3e671", TapDerivation [] (Derivation (fingerprintOf "772b2da7") "m/86'/1'/0'/0/5"))]+      outputTapInternalKey (outputAt 0 psbt) `shouldBe` Right (Just (xOnly "1124da7aec92ccd06c954562647f437b138b95721a84be2bf2276bbddab3e671"))+      outputTapDerivations (outputAt 0 psbt) `shouldBe` Right [(xOnly "1124da7aec92ccd06c954562647f437b138b95721a84be2bf2276bbddab3e671", TapDerivation [] (Derivation (fingerprintOf "772b2da7") "m/86'/1'/0'/0/5"))]       outputTapTree (outputAt 0 psbt) `shouldBe` Right Nothing      it "read the leaf scripts, the derivations with their leaves, the internal key and the Merkle root of a script path input" $ do       psbt <- vectorAt 3-      leaves <- expectRight (tapLeafScripts ctx (inputAt 0 psbt))+      leaves <- expectRight (tapLeafScripts (inputAt 0 psbt))       map (.script) leaves         `shouldBe` [ keyScript "2cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2",                      keyScript "4320b0bf16f011b53ea7be615924aa7f27e5d29ad20ea1155d848676c3bad1b2",@@ -1246,9 +1246,9 @@                    ]       map (.leafVersion) leaves `shouldBe` [0xc0, 0xc0, 0xc0]       map (B.length . (.controlBlock)) leaves `shouldBe` [97, 65, 97]-      inputTapInternalKey ctx (inputAt 0 psbt) `shouldBe` Right (Just (xOnly "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0"))+      inputTapInternalKey (inputAt 0 psbt) `shouldBe` Right (Just (xOnly "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0"))       inputTapMerkleRoot (inputAt 0 psbt) `shouldBe` Right (Just (digest "f0362e2f75a6f420a5bde3eb221d96ae6720cf25f81890c95b1d775acb515e65"))-      records <- expectRight (inputTapDerivations ctx (inputAt 0 psbt))+      records <- expectRight (inputTapDerivations (inputAt 0 psbt))       lookup (xOnly "2cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2") records         `shouldBe` Just (TapDerivation [digest "cd970e15f53fc0c82f950fd560ffa919b76172be017368a89913af074f400b09"] (Derivation (fingerprintOf "772b2da7") "m/86'/1'/2'/0/0"))       lookup (xOnly "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0") records@@ -1256,10 +1256,10 @@       -- The leaf hash of the record is the hash of the leaf script       leafHash 0xc0 (keyScript "2cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2") `shouldBe` digest "cd970e15f53fc0c82f950fd560ffa919b76172be017368a89913af074f400b09"       -- The control blocks commit the leaves to the output key, with the Merkle root-      let outKey = fromJust (importXOnlyPubKey ctx (hexBytes "c2247efbfd92ac47f6f40b8d42d169175a19fa9fa10e4a25d7f35eb4dd85b692"))+      let outKey = fromJust (importXOnlyPubKey (hexBytes "c2247efbfd92ac47f6f40b8d42d169175a19fa9fa10e4a25d7f35eb4dd85b692"))       forM_ leaves $ \leaf -> do-        (v, internal, proof) <- expectRight (decodeControlBlock ctx leaf.controlBlock)-        verifyScriptPathData ctx outKey (ScriptPathData Nothing [] leaf.script (odd v) 0xc0 internal proof Nothing) `shouldBe` True+        (v, internal, proof) <- expectRight (decodeControlBlock leaf.controlBlock)+        verifyScriptPathData outKey (ScriptPathData Nothing [] leaf.script (odd v) 0xc0 internal proof Nothing) `shouldBe` True      it "read the script tree of a script path output, whose leaves build the tree of its output key" $ do       psbt <- vectorAt 4@@ -1269,109 +1269,112 @@               TapLeaf 1 0xc0 (keyScript "44faa49a0338de488c8dfffecdfb6f329f380bd566ef20c8df6d813eab1c4273")             ]       outputTapTree (outputAt 0 psbt) `shouldBe` Right (Just leaves)-      outputTapInternalKey ctx (outputAt 0 psbt) `shouldBe` Right (Just (xOnly "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0"))+      outputTapInternalKey (outputAt 0 psbt) `shouldBe` Right (Just (xOnly "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0"))       let tree = fromJust (tapTreeFromLeaves leaves)           output = TaprootOutput (xOnly "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0") (Just tree)-      marshal ctx (taprootScriptOutput ctx output) `shouldBe` (head psbt.unsignedTx.outputs).script+      encodeSerial (taprootScriptOutput output) `shouldBe` (head psbt.unsignedTx.outputs).script       Map.lookup (Key 0x06 "") (insertOutputTapTree leaves Map.empty) `shouldBe` Map.lookup (Key 0x06 "") (outputAt 0 psbt)-      records <- expectRight (outputTapDerivations ctx (outputAt 0 psbt))+      records <- expectRight (outputTapDerivations (outputAt 0 psbt))       length records `shouldBe` 4      it "read the script path signatures of a signed input, and finalize it with the first leaf that has one" $ do       psbt <- vectorAt 5-      sigs <- expectRight (tapScriptSigs ctx (inputAt 0 psbt))-      map (\((k, h), s) -> (exportXOnlyPubKey ctx k, h, B.length (encodeTaprootSig s))) sigs+      sigs <- expectRight (tapScriptSigs (inputAt 0 psbt))+      map (\((k, h), s) -> (exportXOnlyPubKey k, h, B.length (encodeTaprootSig s))) sigs         `shouldBe` [ (hexBytes "2cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2", digest "cd970e15f53fc0c82f950fd560ffa919b76172be017368a89913af074f400b09", 64),                      (hexBytes "4320b0bf16f011b53ea7be615924aa7f27e5d29ad20ea1155d848676c3bad1b2", digest "115f2e490af7cc45c4f78511f36057ce5c5a5c56325a29fb44dfc203f356e1f8", 64),                      (hexBytes "fa0f7a3cef3b1d0c0a6ce7d26e17ada0b2e5c92d19efad48b41859cb8a451ca9", digest "6f7d62059e9497a1a4a267569d9876da60101aff38e3529b9b939ce7f91ae970", 64)                    ]-      final <- expectRight (finalizePsbt btc ctx psbt)+      final <- expectRight (finalizePsbt btc psbt)       witness <- expectRight (finalScriptWitness (inputAt 0 final))       fmap (map B.length) witness `shouldBe` Just [64, 34, 97]       tx <- expectRight (psbtTransaction final)       let coin = TxOut 5000000000 (hexBytes "5120c2247efbfd92ac47f6f40b8d42d169175a19fa9fa10e4a25d7f35eb4dd85b692")-      verifyStdTx btc ctx tx [(either error id (unmarshal ctx coin.script), coin.value, (head tx.inputs).outpoint)] `shouldBe` True+      verifyStdTx btc tx [(either error id (decodeSerial coin.script), coin.value, (head tx.inputs).outpoint)] `shouldBe` True      it "write the fields back as they were read" $       forM_ [0 .. 5] $ \i -> do         psbt <- vectorAt i         forM_ psbt.inputs $ \m -> do-          key <- expectRight (inputTapInternalKey ctx m)-          forM_ key $ \k -> Map.lookup (Key 0x17 "") (insertInputTapInternalKey ctx k Map.empty) `shouldBe` Map.lookup (Key 0x17 "") m+          key <- expectRight (inputTapInternalKey m)+          forM_ key $ \k -> Map.lookup (Key 0x17 "") (insertInputTapInternalKey k Map.empty) `shouldBe` Map.lookup (Key 0x17 "") m           root <- expectRight (inputTapMerkleRoot m)           forM_ root $ \r -> Map.lookup (Key 0x18 "") (insertInputTapMerkleRoot r Map.empty) `shouldBe` Map.lookup (Key 0x18 "") m           sig <- expectRight (tapKeySig m)           forM_ sig $ \s -> Map.lookup (Key 0x13 "") (insertTapKeySig s Map.empty) `shouldBe` Map.lookup (Key 0x13 "") m-          leaves <- expectRight (tapLeafScripts ctx m)+          leaves <- expectRight (tapLeafScripts m)           Map.toList (foldr insertTapLeafScript Map.empty leaves) `shouldBe` [(k, v) | (k, v) <- Map.toList m, k.keyType == 0x15]-          records <- expectRight (inputTapDerivations ctx m)-          Map.toList (foldr (uncurry (insertInputTapDerivation ctx)) Map.empty records) `shouldBe` [(k, v) | (k, v) <- Map.toList m, k.keyType == 0x16]-          sigs <- expectRight (tapScriptSigs ctx m)-          Map.toList (foldr (\((k, h), s) -> insertTapScriptSig ctx k h s) Map.empty sigs) `shouldBe` [(k, v) | (k, v) <- Map.toList m, k.keyType == 0x14]+          records <- expectRight (inputTapDerivations m)+          Map.toList (foldr (uncurry insertInputTapDerivation) Map.empty records) `shouldBe` [(k, v) | (k, v) <- Map.toList m, k.keyType == 0x16]+          sigs <- expectRight (tapScriptSigs m)+          Map.toList (foldr (\((k, h), s) -> insertTapScriptSig k h s) Map.empty sigs) `shouldBe` [(k, v) | (k, v) <- Map.toList m, k.keyType == 0x14]         forM_ psbt.outputs $ \m -> do-          key <- expectRight (outputTapInternalKey ctx m)-          forM_ key $ \k -> Map.lookup (Key 0x05 "") (insertOutputTapInternalKey ctx k Map.empty) `shouldBe` Map.lookup (Key 0x05 "") m-          records <- expectRight (outputTapDerivations ctx m)-          Map.toList (foldr (uncurry (insertOutputTapDerivation ctx)) Map.empty records) `shouldBe` [(k, v) | (k, v) <- Map.toList m, k.keyType == 0x07]+          key <- expectRight (outputTapInternalKey m)+          forM_ key $ \k -> Map.lookup (Key 0x05 "") (insertOutputTapInternalKey k Map.empty) `shouldBe` Map.lookup (Key 0x05 "") m+          records <- expectRight (outputTapDerivations m)+          Map.toList (foldr (uncurry insertOutputTapDerivation) Map.empty records) `shouldBe` [(k, v) | (k, v) <- Map.toList m, k.keyType == 0x07]      prop "a Taproot coin without script tree, signed by its key path with the internal key and finalized, verifies" $-      forAll (arbitraryKeyPair ctx) $ \(secret, public) ->-        let coinScript = taprootScriptOutput ctx (TaprootOutput public.point Nothing)-            (psbt, coins) = spendingPsbt ctx coinScript-            fields = insertInputTapInternalKey ctx public.point . insertInputTapDerivation ctx public.point (TapDerivation [] (Derivation (fingerprintOf "d90c6a4f") "m/86'/0'/0'/0/0"))+      forAll arbitraryKeyPair $ \(secret, public) ->+        let coinScript = taprootScriptOutput (TaprootOutput public.point Nothing)+            (psbt, coins) = spendingPsbt coinScript+            fields = insertInputTapInternalKey public.point . insertInputTapDerivation public.point (TapDerivation [] (Derivation (fingerprintOf "d90c6a4f") "m/86'/0'/0'/0/0"))             withFields = withInputs (fields <$> psbt.inputs) psbt-            signed = signPsbt btc ctx (keySigner ctx secret.key) withFields-         in (signsAndVerifies btc ctx [secret] (withFields, coins), fmap (fmap (fmap (.hash)) . tapKeySig . inputAt 0) signed) === (Right True, Right (Right (Just sigHashDefault)))+            signed = signPsbt btc (keySigner secret.key) withFields+         in (signsAndVerifies btc [secret] (withFields, coins), fmap (fmap (fmap (.hash)) . tapKeySig . inputAt 0) signed) === (Right True, Right (Right (Just sigHashDefault)))      prop "a Taproot coin with a leaf that checks one key, signed by that leaf and finalized, verifies" $-      forAll ((,) <$> arbitraryKeyPair ctx <*> arbitraryKeyPair ctx) $ \((secret, public), (_, internal)) ->-        let leaf = Script [opPushData (exportXOnlyPubKey ctx public.point), OP_CHECKSIG]+      forAll ((,) <$> arbitraryKeyPair <*> arbitraryKeyPair) $ \((secret, public), (_, internal)) ->+        let leaf = Script [opPushData (exportXOnlyPubKey public.point), OP_CHECKSIG]             tree = MASTBranch (MASTLeaf 0xc0 leaf) (MASTLeaf 0xc0 (Script [OP_RETURN]))             output = TaprootOutput internal.point (Just tree)-            coinScript = taprootScriptOutput ctx output-            (psbt, coins) = spendingPsbt ctx coinScript+            coinScript = taprootScriptOutput output+            (psbt, coins) = spendingPsbt coinScript             proof = case getMerkleProofs tree of               (_, _, p) : _ -> p               [] -> []-            control = encodeControlBlock ctx (0xc0 + keyParity ctx (taprootOutputKey ctx output)) internal.point proof+            control = encodeControlBlock (0xc0 + keyParity (taprootOutputKey output)) internal.point proof             fields =-              insertInputTapInternalKey ctx internal.point+              insertInputTapInternalKey internal.point                 . insertInputTapMerkleRoot (mastCommitment tree)                 . insertTapLeafScript (TapLeafScript control leaf 0xc0)-                . insertInputTapDerivation ctx public.point (TapDerivation [leafHash 0xc0 leaf] (Derivation (fingerprintOf "d90c6a4f") "m/86'/0'/0'/0/1"))+                . insertInputTapDerivation public.point (TapDerivation [leafHash 0xc0 leaf] (Derivation (fingerprintOf "d90c6a4f") "m/86'/0'/0'/0/1"))             withFields = withInputs (fields <$> psbt.inputs) psbt-         in signsAndVerifies btc ctx [secret] (withFields, coins) === Right True+         in signsAndVerifies btc [secret] (withFields, coins) === Right True      it "the signer refuses a sighash type a Taproot signature may not use, and an internal key that does not give the coin" $ do       let secret = PrivateKey secretOne True-          public = derivePublicKey ctx secret-          other = compressedKey ctx secretTwo-          coinScript = taprootScriptOutput ctx (TaprootOutput public.point Nothing)-          (psbt, _) = spendingPsbt ctx coinScript-          withFields m = withInputs [m (insertInputTapInternalKey ctx public.point (inputAt 0 psbt))] psbt-      signPsbt btc ctx (keySigner ctx secret.key) (withFields (insertSigHashType (setForkIdFlag sigHashAll))) `shouldBe` Left "Input 0: the sighash type 65 is not one a Taproot signature may use"-      signPsbt btc ctx (keySigner ctx secret.key) (withInputs [insertInputTapInternalKey ctx other.point (inputAt 0 psbt)] psbt) `shouldBe` Left "Input 0: the internal key and the Merkle root do not give the output key of the coin"+          public = derivePublicKey secret+          other = compressedKey secretTwo+          coinScript = taprootScriptOutput (TaprootOutput public.point Nothing)+          (psbt, _) = spendingPsbt coinScript+          withFields m = withInputs [m (insertInputTapInternalKey public.point (inputAt 0 psbt))] psbt+      signPsbt btc (keySigner secret.key) (withFields (insertSigHashType (setForkIdFlag sigHashAll))) `shouldBe` Left "Input 0: the sighash type 65 is not one a Taproot signature may use"+      signPsbt btc (keySigner secret.key) (withInputs [insertInputTapInternalKey other.point (inputAt 0 psbt)] psbt) `shouldBe` Left "Input 0: the internal key and the Merkle root do not give the output key of the coin"       -- Without the internal key, the input is left alone-      signPsbt btc ctx (keySigner ctx secret.key) psbt `shouldBe` Right psbt+      signPsbt btc (keySigner secret.key) psbt `shouldBe` Right psbt  {- Properties -} -propertiesSpec :: Ctx -> Spec-propertiesSpec ctx =+propertiesSpec :: Spec+propertiesSpec =   describe "Any PSBT" $ do     prop "is read back as it was written" $-      forAll (arbitraryPsbt btc ctx) $ \psbt -> decodePsbt (encodePsbt psbt) == Right psbt+      forAll (arbitraryPsbt btc) $+        \psbt -> decodePsbt (encodePsbt psbt) == Right psbt      prop "is read back from its base64 text" $-      forAll (arbitraryPsbt btc ctx) $ \psbt -> decodePsbtBase64 (encodePsbtBase64 psbt) == Right psbt+      forAll (arbitraryPsbt btc) $+        \psbt -> decodePsbtBase64 (encodePsbtBase64 psbt) == Right psbt      prop "combined with itself is itself" $-      forAll (arbitraryPsbt btc ctx) $ \psbt -> combinePsbt psbt psbt == Right psbt+      forAll (arbitraryPsbt btc) $+        \psbt -> combinePsbt psbt psbt == Right psbt      -- The combiner of BIP 174 keeps every entry that either PSBT has. The     -- key type 0x7e is one no map knows.     prop "combined with a copy that has one more entry in every map, in either order, is that copy" $-      forAll (arbitraryPsbt btc ctx) $ \psbt ->+      forAll (arbitraryPsbt btc) $ \psbt ->         let oneMore = Map.insert (Key 0x7e "combiner test") "one more entry"             copy = Psbt psbt.version psbt.unsignedTx (oneMore psbt.globals) (oneMore <$> psbt.inputs) (oneMore <$> psbt.outputs)          in combinePsbt psbt copy == Right copy && combinePsbt copy psbt == Right copy@@ -1555,76 +1558,76 @@     tx = Tx 2 [TxIn (OutPoint (txHash parent) 0) "" 0xfffffffe, TxIn (OutPoint (txHash parent) 1) "" 0xfffffffe] [TxOut 399990000 (hexBytes "76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac")] [] 0     input = insertNonWitnessUtxo parent Map.empty -signerScopeSpec :: Ctx -> Spec-signerScopeSpec ctx =+signerScopeSpec :: Spec+signerScopeSpec =   describe "What the signer and the finalizer sign, and what they leave alone" $ do     let secret = PrivateKey secretOne True-        public = derivePublicKey ctx secret-        otherPublic = compressedKey ctx secretTwo-        signer = keySigner ctx secretOne-        ownScript = marshal ctx (PayPKHash (addressHash (marshal ctx public)))-        otherScript = marshal ctx (PayPKHash (addressHash (marshal ctx otherPublic)))-        (psbt, _) = spendingPsbt ctx (PayPKHash (addressHash (marshal ctx public)))+        public = derivePublicKey secret+        otherPublic = compressedKey secretTwo+        signer = keySigner secretOne+        ownScript = encodeSerial (PayPKHash (addressHash (encodeSerial public)))+        otherScript = encodeSerial (PayPKHash (addressHash (encodeSerial otherPublic)))+        (psbt, _) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))         parent = fromJust (either (const Nothing) id (nonWitnessUtxo (inputAt 0 psbt)))         coin = head parent.outputs-        signatureCounts = mapM (fmap length . partialSignatures ctx) . (.inputs)-        keyHex = show (encodeHex (marshal ctx public))+        signatureCounts = mapM (fmap length . partialSignatures) . (.inputs)+        keyHex = show (encodeHex (encodeSerial public))      -- BIP 32 gives a key a depth of one byte, so no key is 256 steps below     -- another     it "a signer built from an extended key holds no key for a record whose path has 256 steps" $ do       let master = makeXPrvKey "PSBT signer test"-          tooDeep = Derivation (xPubFP ctx (deriveXPubKey ctx master)) (listToPath (replicate 256 0))-      (xPrvSigner ctx master Nothing).keyOfRecord public tooDeep `shouldBe` Nothing+          tooDeep = Derivation (xPubFP (deriveXPubKey master)) (listToPath (replicate 256 0))+      (xPrvSigner master Nothing).keyOfRecord public tooDeep `shouldBe` Nothing      it "signing leaves unsigned an input whose record names the signer's key with a path of 256 steps" $ do       let master = makeXPrvKey "PSBT signer test"-          tooDeep = Derivation (xPubFP ctx (deriveXPubKey ctx master)) (listToPath (replicate 256 0))-          withRecord = withInputs (insertInputDerivation ctx public tooDeep <$> psbt.inputs) psbt-      (signatureCounts =<< signPsbt btc ctx (xPrvSigner ctx master Nothing) withRecord) `shouldBe` Right [0]+          tooDeep = Derivation (xPubFP (deriveXPubKey master)) (listToPath (replicate 256 0))+          withRecord = withInputs (insertInputDerivation public tooDeep <$> psbt.inputs) psbt+      (signatureCounts =<< signPsbt btc (xPrvSigner master Nothing) withRecord) `shouldBe` Right [0]      -- The second record names a key the coin does not pay. A signer that     -- derives a key for every record can be made to work without end.     it "asks the signer for the key of a record only when the script of the coin names that key" $ do       let onlyOwn = signer {keyOfRecord = \asked _ -> if asked == public then Just secretOne else error "asked for the key of a record the coin does not name"}-          withRecords = withInputs ((recordOf ctx public . recordOf ctx otherPublic) <$> psbt.inputs) psbt-      (signatureCounts =<< signPsbt btc ctx onlyOwn withRecords) `shouldBe` Right [1]+          withRecords = withInputs ((recordOf public . recordOf otherPublic) <$> psbt.inputs) psbt+      (signatureCounts =<< signPsbt btc onlyOwn withRecords) `shouldBe` Right [1]      -- The coin pays the hash of key 2, and the record names key 1, which     -- the signer holds. BIP 174: "If a Signer cannot sign a transaction, it     -- must not add a Partial Signature."     it "adds no signature for a key the script of the coin does not name, even when a derivation record names it" $ do-      let (other, _) = spendingPsbt ctx (PayPKHash (addressHash (marshal ctx otherPublic)))-      (signatureCounts =<< signPsbt btc ctx signer (withInputs (recordOf ctx public <$> other.inputs) other)) `shouldBe` Right [0]+      let (other, _) = spendingPsbt (PayPKHash (addressHash (encodeSerial otherPublic)))+      (signatureCounts =<< signPsbt btc signer (withInputs (recordOf public <$> other.inputs) other)) `shouldBe` Right [0]      it "adds no signature to a P2WSH coin whose witness script is missing, nor to a P2SH coin whose redeem script is missing" $ do-      let multisig = forceRight (encodeOutput ctx (PayMulSig [public, otherPublic] 2))-          (p2wsh, _) = spendingPsbt ctx (forceRight (toP2WSH multisig))-          (p2sh, _) = spendingPsbt ctx (forceRight (toP2SH multisig))-      (signatureCounts =<< signPsbt btc ctx signer (withInputs (recordOf ctx public <$> p2wsh.inputs) p2wsh)) `shouldBe` Right [0]-      (signatureCounts =<< signPsbt btc ctx signer (withInputs (recordOf ctx public <$> p2sh.inputs) p2sh)) `shouldBe` Right [0]+      let multisig = forceRight (encodeOutput (PayMulSig [public, otherPublic] 2))+          (p2wsh, _) = spendingPsbt (forceRight (toP2WSH multisig))+          (p2sh, _) = spendingPsbt (forceRight (toP2SH multisig))+      (signatureCounts =<< signPsbt btc signer (withInputs (recordOf public <$> p2wsh.inputs) p2wsh)) `shouldBe` Right [0]+      (signatureCounts =<< signPsbt btc signer (withInputs (recordOf public <$> p2sh.inputs) p2sh)) `shouldBe` Right [0]      it "signs a P2SH-P2WPKH coin with its redeem script by the hash of its key, without a derivation record" $ do-      let redeem = forceRight (encodeOutput ctx (PayWitnessPKHash (addressHash (marshal ctx public))))-          (nested, _) = spendingPsbt ctx (forceRight (toP2SH redeem))-      (signatureCounts =<< signPsbt btc ctx signer (withInputs (insertInputRedeemScript redeem <$> nested.inputs) nested)) `shouldBe` Right [1]+      let redeem = forceRight (encodeOutput (PayWitnessPKHash (addressHash (encodeSerial public))))+          (nested, _) = spendingPsbt (forceRight (toP2SH redeem))+      (signatureCounts =<< signPsbt btc signer (withInputs (insertInputRedeemScript redeem <$> nested.inputs) nested)) `shouldBe` Right [1]      -- 0x41 is SIGHASH_ALL (0x01) with SIGHASH_FORKID (0x40)     it "on the Bitcoin Cash networks, signs an input that asks for no sighash type with SIGHASH_ALL and the fork id flag" $       forM_ [bch, bchTest, bchTest4, bchRegTest] $ \net ->-        (map (B.last . snd) <$> (partialSignatures ctx . inputAt 0 =<< signPsbt net ctx signer psbt)) `shouldBe` Right [0x41]+        (map (B.last . snd) <$> (partialSignatures . inputAt 0 =<< signPsbt net signer psbt)) `shouldBe` Right [0x41]      -- Input 0 is a coin of key 1. Input 1 is a P2WSH coin of someone else,     -- whose witness script is <key 2> OP_CHECKSIGVERIFY <144>     -- OP_CHECKSEQUENCEVERIFY, which is no template the library knows.     it "signs and finalizes its own input, and leaves alone an input whose witness script is not a standard template" $ do-      let timelocked = Script [opPushData (marshal ctx otherPublic), OP_CHECKSIGVERIFY, opPushData "\x90\x00", OP_CHECKSEQUENCEVERIFY]-          both = spendingTwo ownScript (marshal ctx (forceRight (toP2WSH timelocked)))+      let timelocked = Script [opPushData (encodeSerial otherPublic), OP_CHECKSIGVERIFY, opPushData "\x90\x00", OP_CHECKSEQUENCEVERIFY]+          both = spendingTwo ownScript (encodeSerial (forceRight (toP2WSH timelocked)))           withScript = withInputs [inputAt 0 both, insertInputWitnessScript timelocked (inputAt 1 both)] both-      signed <- expectRight (signPsbt btc ctx signer withScript)+      signed <- expectRight (signPsbt btc signer withScript)       signatureCounts signed `shouldBe` Right [1, 0]       inputAt 1 signed `shouldBe` inputAt 1 withScript-      final <- expectRight (finalizePsbt btc ctx signed)+      final <- expectRight (finalizePsbt btc signed)       map (isJust . finalScriptSig) final.inputs `shouldBe` [True, False]       inputAt 1 final `shouldBe` inputAt 1 withScript @@ -1634,70 +1637,70 @@     it "leaves alone a legacy coin known from its witness output only when it holds no key for it, and signs its own input" $ do       let both = spendingTwo ownScript otherScript           witnessOnly = withInputs [inputAt 0 both, insertWitnessUtxo (TxOut 200000000 otherScript) Map.empty] both-      (signatureCounts =<< signPsbt btc ctx signer witnessOnly) `shouldBe` Right [1, 0]+      (signatureCounts =<< signPsbt btc signer witnessOnly) `shouldBe` Right [1, 0]      -- Bitcoin Core refuses the whole PSBT too: a sighash type that the     -- caller did not ask for is a mismatch on any input that has its coin     it "refuses a PSBT in which another party's input asks for a sighash type the signer does not accept" $ do       let both = spendingTwo ownScript otherScript           asking = withInputs [inputAt 0 both, insertSigHashType (setAnyoneCanPay sigHashSingle) (inputAt 1 both)] both-      signPsbt btc ctx signer asking `shouldBe` Left "Input 1: the sighash type 131 is not one the signer accepts"+      signPsbt btc signer asking `shouldBe` Left "Input 1: the sighash type 131 is not one the signer accepts"      it "refuses to sign a SegWit version 0 coin with an uncompressed key" $ do       let uncompressed = PublicKey public.point False-          (p2wpkh, _) = spendingPsbt ctx (PayWitnessPKHash (addressHash (marshal ctx uncompressed)))-      signPsbt btc ctx signer p2wpkh `shouldBe` Left "Input 0: a SegWit version 0 coin may not be signed with an uncompressed key"+          (p2wpkh, _) = spendingPsbt (PayWitnessPKHash (addressHash (encodeSerial uncompressed)))+      signPsbt btc signer p2wpkh `shouldBe` Left "Input 0: a SegWit version 0 coin may not be signed with an uncompressed key"      -- The signature is a real one of key 1, on another coin. The finalizer     -- must refuse it for the form of the key, whatever it signs.     it "the finalizer refuses a signature of an uncompressed key on a SegWit version 0 coin" $ do       let uncompressed = PublicKey public.point False-          (p2wpkh, _) = spendingPsbt ctx (PayWitnessPKHash (addressHash (marshal ctx uncompressed)))-      signed <- expectRight (signPsbt btc ctx signer psbt)-      signature <- case partialSignatures ctx (inputAt 0 signed) of+          (p2wpkh, _) = spendingPsbt (PayWitnessPKHash (addressHash (encodeSerial uncompressed)))+      signed <- expectRight (signPsbt btc signer psbt)+      signature <- case partialSignatures (inputAt 0 signed) of         Right [(_, sig)] -> return sig         _ -> fail "one signature"-      finalizePsbt btc ctx (withInputs (insertPartialSignature ctx uncompressed signature <$> p2wpkh.inputs) p2wpkh)-        `shouldBe` Left ("Input 0: the signature of the key " <> show (encodeHex (marshal ctx uncompressed)) <> " is of an uncompressed key, which a SegWit version 0 coin may not be spent with")+      finalizePsbt btc (withInputs (insertPartialSignature uncompressed signature <$> p2wpkh.inputs) p2wpkh)+        `shouldBe` Left ("Input 0: the signature of the key " <> show (encodeHex (encodeSerial uncompressed)) <> " is of an uncompressed key, which a SegWit version 0 coin may not be spent with")      -- The second signature is the one of key 1, filed under key 2: it does     -- not verify for key 2. The coin does not name key 2, so the finalizer     -- has no reason to look at it.     it "the finalizer does not look at a partial signature of a key the script of the coin does not name" $ do-      signed <- expectRight (signPsbt btc ctx signer psbt)-      signature <- case partialSignatures ctx (inputAt 0 signed) of+      signed <- expectRight (signPsbt btc signer psbt)+      signature <- case partialSignatures (inputAt 0 signed) of         Right [(_, sig)] -> return sig         _ -> fail "one signature"-      let withStray = withInputs (insertPartialSignature ctx otherPublic signature <$> signed.inputs) signed-      (finalScriptSig . inputAt 0 <$> finalizePsbt btc ctx withStray) `shouldBe` (finalScriptSig . inputAt 0 <$> finalizePsbt btc ctx signed)-      (isJust . finalScriptSig . inputAt 0 <$> finalizePsbt btc ctx withStray) `shouldBe` Right True+      let withStray = withInputs (insertPartialSignature otherPublic signature <$> signed.inputs) signed+      (finalScriptSig . inputAt 0 <$> finalizePsbt btc withStray) `shouldBe` (finalScriptSig . inputAt 0 <$> finalizePsbt btc signed)+      (isJust . finalScriptSig . inputAt 0 <$> finalizePsbt btc withStray) `shouldBe` Right True      -- Bitcoin Core takes SIGHASH_ALL for an input that names no sighash     -- type, and gives no final script when a signature uses another     it "the finalizer refuses a SIGHASH_NONE signature on an input that names no sighash type" $ do       let acceptingNone = signer {acceptedSigHashes = [sigHashNone]}-      signed <- expectRight (signPsbt btc ctx acceptingNone (withInputs (insertSigHashType sigHashNone <$> psbt.inputs) psbt))-      finalizePsbt btc ctx (withInputs (deleteSigHashType <$> signed.inputs) signed)+      signed <- expectRight (signPsbt btc acceptingNone (withInputs (insertSigHashType sigHashNone <$> psbt.inputs) psbt))+      finalizePsbt btc (withInputs (deleteSigHashType <$> signed.inputs) signed)         `shouldBe` Left ("Input 0: the signature of the key " <> keyHex <> " does not use SIGHASH_ALL, and the input names no sighash type")      it "the finalizer leaves alone a signed legacy coin that is known from its witness output only" $ do-      signed <- expectRight (signPsbt btc ctx signer psbt)+      signed <- expectRight (signPsbt btc signer psbt)       let witnessOnly = withInputs [insertWitnessUtxo coin (Map.delete (Key 0x00 "") (inputAt 0 signed))] signed-      finalizePsbt btc ctx witnessOnly `shouldBe` Right witnessOnly+      finalizePsbt btc witnessOnly `shouldBe` Right witnessOnly      -- A signer written by a caller may answer with a key that is not the     -- one asked for. Its signature would be of no use to anyone.     it "signs with a key the signer gives only when it is the key the coin names" $ do       let wrongByRecord = signer {keyOfRecord = \_ _ -> Just secretTwo, keyOfHash = const Nothing}           wrongByHash = signer {keyOfRecord = \_ _ -> Nothing, keyOfHash = const (Just (PrivateKey secretTwo True))}-          withRecord = withInputs (recordOf ctx public <$> psbt.inputs) psbt-      (signatureCounts =<< signPsbt btc ctx wrongByRecord withRecord) `shouldBe` Right [0]-      (signatureCounts =<< signPsbt btc ctx wrongByHash psbt) `shouldBe` Right [0]+          withRecord = withInputs (recordOf public <$> psbt.inputs) psbt+      (signatureCounts =<< signPsbt btc wrongByRecord withRecord) `shouldBe` Right [0]+      (signatureCounts =<< signPsbt btc wrongByHash psbt) `shouldBe` Right [0]      it "a signer of one key holds no key for the record of another key" $ do       let record = Derivation (fingerprintOf "00000000") "m/0"-      (keySigner ctx secretOne).keyOfRecord otherPublic record `shouldBe` Nothing-      (keySigner ctx secretOne).keyOfRecord public record `shouldBe` Just secretOne+      (keySigner secretOne).keyOfRecord otherPublic record `shouldBe` Nothing+      (keySigner secretOne).keyOfRecord public record `shouldBe` Just secretOne      -- The time lock 100 is below 500,000,000, so it would be read as a height     it "a constructor refuses an input whose map breaks the spec, such as a required time lock below 500000000" $ do@@ -1739,103 +1742,103 @@ flipValue key value = (key, flipLastBit value) flipKeyData key value = (Key key.keyType (flipLastBit key.keyData), value) -taprootChecksSpec :: Ctx -> Vectors371 -> Spec-taprootChecksSpec ctx vectors =+taprootChecksSpec :: Vectors371 -> Spec+taprootChecksSpec vectors =   describe "The checks on Taproot signatures" $ do     let vectorAt i = psbtOfVector (vectors.accepted371 !! i)-        internal = derivePubKey ctx secretOne-        leafKey = derivePubKey ctx secretTwo-        leaf = Script [opPushData (exportXOnlyPubKey ctx leafKey), OP_CHECKSIG]+        internal = derivePubKey secretOne+        leafKey = derivePubKey secretTwo+        leaf = Script [opPushData (exportXOnlyPubKey leafKey), OP_CHECKSIG]         tree = MASTBranch (MASTLeaf 0xc0 leaf) (MASTLeaf 0xc0 (Script [OP_RETURN]))         output = TaprootOutput internal (Just tree)-        control = encodeControlBlock ctx (0xc0 + keyParity ctx (taprootOutputKey ctx output)) internal [leafHash 0xc0 (Script [OP_RETURN])]-        (withTree, _) = spendingPsbt ctx (taprootScriptOutput ctx output)-        treeFields = insertInputTapInternalKey ctx internal . insertInputTapMerkleRoot (mastCommitment tree) . insertTapLeafScript (TapLeafScript control leaf 0xc0)+        control = encodeControlBlock (0xc0 + keyParity (taprootOutputKey output)) internal [leafHash 0xc0 (Script [OP_RETURN])]+        (withTree, _) = spendingPsbt (taprootScriptOutput output)+        treeFields = insertInputTapInternalKey internal . insertInputTapMerkleRoot (mastCommitment tree) . insertTapLeafScript (TapLeafScript control leaf 0xc0)         derivation = Derivation (fingerprintOf "d90c6a4f") "m/86'/0'/0'/0/0"         -- A signer that finds its keys by derivation record only, as one         -- built from an extended key does-        byRecord secret = (keySigner ctx secret) {keyOfHash = const Nothing}+        byRecord secret = (keySigner secret) {keyOfHash = const Nothing}      it "the finalizer refuses a key path signature that does not verify" $ do       psbt <- vectorAt 1-      finalizePsbt btc ctx (onInputs (onKeyType 0x13 flipValue) psbt)+      finalizePsbt btc (onInputs (onKeyType 0x13 flipValue) psbt)         `shouldBe` Left "Input 0: the key path signature does not verify"      it "the finalizer refuses a script path signature that does not verify" $ do       psbt <- vectorAt 5-      finalizePsbt btc ctx (onInputs (onKeyType 0x14 flipValue) psbt)+      finalizePsbt btc (onInputs (onKeyType 0x14 flipValue) psbt)         `shouldBe` Left "Input 0: the script path signature does not verify"      it "the finalizer refuses a leaf whose control block does not commit it to the output key" $ do       psbt <- vectorAt 5-      finalizePsbt btc ctx (onInputs (onKeyType 0x15 flipKeyData) psbt)+      finalizePsbt btc (onInputs (onKeyType 0x15 flipKeyData) psbt)         `shouldBe` Left "Input 0: the control block of the leaf does not commit it to the output key"      -- The signatures of both vectors are 64 bytes, which is SIGHASH_DEFAULT     it "the finalizer refuses a Taproot signature that does not use the sighash type the input names" $ do       keyPath <- vectorAt 1       scriptPath <- vectorAt 5-      finalizePsbt btc ctx (onInputs (insertSigHashType sigHashAll) keyPath) `shouldBe` Left "Input 0: a Taproot signature does not use the sighash type of the input"-      finalizePsbt btc ctx (onInputs (insertSigHashType sigHashAll) scriptPath) `shouldBe` Left "Input 0: a Taproot signature does not use the sighash type of the input"+      finalizePsbt btc (onInputs (insertSigHashType sigHashAll) keyPath) `shouldBe` Left "Input 0: a Taproot signature does not use the sighash type of the input"+      finalizePsbt btc (onInputs (insertSigHashType sigHashAll) scriptPath) `shouldBe` Left "Input 0: a Taproot signature does not use the sighash type of the input"      -- Bitcoin Core takes SIGHASH_DEFAULT for a Taproot input that names no     -- sighash type, and then wants every signature to be 64 bytes     it "the finalizer refuses a SIGHASH_ALL key path signature on an input that names no sighash type" $ do-      let (keyOnly, _) = spendingPsbt ctx (taprootScriptOutput ctx (TaprootOutput internal Nothing))-          asking = onInputs (insertSigHashType sigHashAll . insertInputTapInternalKey ctx internal) keyOnly-      signed <- expectRight (signPsbt btc ctx (keySigner ctx secretOne) asking)+      let (keyOnly, _) = spendingPsbt (taprootScriptOutput (TaprootOutput internal Nothing))+          asking = onInputs (insertSigHashType sigHashAll . insertInputTapInternalKey internal) keyOnly+      signed <- expectRight (signPsbt btc (keySigner secretOne) asking)       (fmap (fmap (.hash)) . tapKeySig . inputAt 0) signed `shouldBe` Right (Just sigHashAll)-      finalizePsbt btc ctx (onInputs deleteSigHashType signed)+      finalizePsbt btc (onInputs deleteSigHashType signed)         `shouldBe` Left "Input 0: a Taproot signature does not use SIGHASH_DEFAULT, and the input names no sighash type"      it "the signer refuses a Taproot coin that asks for a sighash type the signer does not accept" $ do-      let (keyOnly, _) = spendingPsbt ctx (taprootScriptOutput ctx (TaprootOutput internal Nothing))-      signPsbt btc ctx (keySigner ctx secretOne) (onInputs (insertSigHashType sigHashSingle . insertInputTapInternalKey ctx internal) keyOnly)+      let (keyOnly, _) = spendingPsbt (taprootScriptOutput (TaprootOutput internal Nothing))+      signPsbt btc (keySigner secretOne) (onInputs (insertSigHashType sigHashSingle . insertInputTapInternalKey internal) keyOnly)         `shouldBe` Left "Input 0: the sighash type 3 is not one the signer accepts"      -- BIP 371: the leaf hashes of a record "are of the leaves which involve     -- this public key". A key that is the internal key and also a leaf key     -- has a record with a leaf hash, and Bitcoin Core writes it that way.     it "signs the key path of a Taproot coin when the record of its internal key lists a leaf" $ do-      let record = insertInputTapDerivation ctx internal (TapDerivation [leafHash 0xc0 leaf] derivation)-      signed <- expectRight (signPsbt btc ctx (byRecord secretOne) (onInputs (record . treeFields) withTree))+      let record = insertInputTapDerivation internal (TapDerivation [leafHash 0xc0 leaf] derivation)+      signed <- expectRight (signPsbt btc (byRecord secretOne) (onInputs (record . treeFields) withTree))       (fmap isJust . tapKeySig . inputAt 0) signed `shouldBe` Right True      it "signs a leaf with the key of a record that lists that leaf, and not with one that lists another leaf" $ do-      let listing hashes = insertInputTapDerivation ctx leafKey (TapDerivation hashes derivation)-          signatures f = fmap length . tapScriptSigs ctx . inputAt 0 =<< signPsbt btc ctx (byRecord secretTwo) (onInputs (f . treeFields) withTree)+      let listing hashes = insertInputTapDerivation leafKey (TapDerivation hashes derivation)+          signatures f = fmap length . tapScriptSigs . inputAt 0 =<< signPsbt btc (byRecord secretTwo) (onInputs (f . treeFields) withTree)       signatures (listing [leafHash 0xc0 leaf]) `shouldBe` Right 1       signatures (listing [leafHash 0xc0 (Script [OP_RETURN])]) `shouldBe` Right 0      -- The leaf is in no tree of the coin: its control block names another     -- internal key     it "signs no leaf whose control block does not commit it to the coin" $ do-      let stray = encodeControlBlock ctx 0xc0 leafKey [leafHash 0xc0 (Script [OP_RETURN])]-          fields = insertInputTapInternalKey ctx internal . insertInputTapMerkleRoot (mastCommitment tree) . insertTapLeafScript (TapLeafScript stray leaf 0xc0)-      signed <- expectRight (signPsbt btc ctx (keySigner ctx secretTwo) (onInputs fields withTree))-      (fmap length . tapScriptSigs ctx . inputAt 0) signed `shouldBe` Right 0+      let stray = encodeControlBlock 0xc0 leafKey [leafHash 0xc0 (Script [OP_RETURN])]+          fields = insertInputTapInternalKey internal . insertInputTapMerkleRoot (mastCommitment tree) . insertTapLeafScript (TapLeafScript stray leaf 0xc0)+      signed <- expectRight (signPsbt btc (keySigner secretTwo) (onInputs fields withTree))+      (fmap length . tapScriptSigs . inputAt 0) signed `shouldBe` Right 0      it "signs a Taproot coin of a PSBT of version 2 by its key path, and the PSBT stays of version 2" $ do-      let (keyOnly, coins) = spendingPsbt ctx (taprootScriptOutput ctx (TaprootOutput internal Nothing))-          version2 = withVersion Version2 (onInputs (insertInputTapInternalKey ctx internal) keyOnly)-      final <- expectRight (finalizePsbt btc ctx =<< signPsbt btc ctx (keySigner ctx secretOne) version2)+      let (keyOnly, coins) = spendingPsbt (taprootScriptOutput (TaprootOutput internal Nothing))+          version2 = withVersion Version2 (onInputs (insertInputTapInternalKey internal) keyOnly)+      final <- expectRight (finalizePsbt btc =<< signPsbt btc (keySigner secretOne) version2)       final.version `shouldBe` Version2       tx <- expectRight (psbtTransaction final)-      verifyStdTx btc ctx tx coins `shouldBe` True+      verifyStdTx btc tx coins `shouldBe` True  {- The coins of a PSBT, and the previous transaction a signer may require -} -coinsSpec :: Ctx -> Spec-coinsSpec ctx =+coinsSpec :: Spec+coinsSpec =   describe "The coins of a PSBT" $ do-    let public = compressedKey ctx secretOne-        signer = keySigner ctx secretOne-        program = PayWitnessPKHash (addressHash (marshal ctx public))-        (psbt, _) = spendingPsbt ctx program+    let public = compressedKey secretOne+        signer = keySigner secretOne+        program = PayWitnessPKHash (addressHash (encodeSerial public))+        (psbt, _) = spendingPsbt program         parent = fromJust (either (const Nothing) id (nonWitnessUtxo (inputAt 0 psbt)))         output = head parent.outputs         witnessOnly = withInputs [insertWitnessUtxo output Map.empty] psbt-        signatureCounts = mapM (fmap length . partialSignatures ctx) . (.inputs)+        signatureCounts = mapM (fmap length . partialSignatures) . (.inputs)      it "tells the coin of each input, and whether it comes from the previous transaction of the input" $ do       inputCoins psbt `shouldBe` Right [Just (InputCoin output True)]@@ -1858,13 +1861,13 @@     -- BIP 174: "The Signer may choose to fail to sign a segwit input if a     -- non-witness UTXO is not provided."     it "a signer refuses a SegWit version 0 coin known from its witness output only, and signs it with its previous transaction" $ do-      signPsbt btc ctx signer witnessOnly+      signPsbt btc signer witnessOnly         `shouldBe` Left "Input 0: the coin is given as a witness output only, and the signer requires the previous transaction of a SegWit version 0 coin"-      (signatureCounts =<< signPsbt btc ctx signer psbt) `shouldBe` Right [1]-      (signatureCounts =<< signPsbt btc ctx signer (withInputs [insertWitnessUtxo output (inputAt 0 psbt)] psbt)) `shouldBe` Right [1]+      (signatureCounts =<< signPsbt btc signer psbt) `shouldBe` Right [1]+      (signatureCounts =<< signPsbt btc signer (withInputs [insertWitnessUtxo output (inputAt 0 psbt)] psbt)) `shouldBe` Right [1]      it "a signer told to trust witness outputs signs a SegWit version 0 coin known from its witness output only" $-      (signatureCounts =<< signPsbt btc ctx (signer {requirePreviousTx = False}) witnessOnly) `shouldBe` Right [1]+      (signatureCounts =<< signPsbt btc (signer {requirePreviousTx = False}) witnessOnly) `shouldBe` Right [1]      -- CVE-2020-14199. The signer holds two coins of 15 and 20 BTC. The     -- writer of the PSBT understates the first as 5 BTC and overstates the@@ -1872,16 +1875,16 @@     -- alone, so the signature of the second input would be valid in a     -- transaction that burns the 10 BTC of difference as fee.     it "a signer refuses a PSBT that states the amounts of its SegWit version 0 coins without their previous transactions" $ do-      let both = spendingTwo (marshal ctx program) (marshal ctx program)-          claimed = withInputs [insertWitnessUtxo (TxOut 500000000 (marshal ctx program)) Map.empty, insertWitnessUtxo (TxOut 2000000000 (marshal ctx program)) Map.empty] both-      signPsbt btc ctx signer claimed+      let both = spendingTwo (encodeSerial program) (encodeSerial program)+          claimed = withInputs [insertWitnessUtxo (TxOut 500000000 (encodeSerial program)) Map.empty, insertWitnessUtxo (TxOut 2000000000 (encodeSerial program)) Map.empty] both+      signPsbt btc signer claimed         `shouldBe` Left "Input 0: the coin is given as a witness output only, and the signer requires the previous transaction of a SegWit version 0 coin"      -- A Taproot signature commits to the amount of every coin (BIP 341)     it "a signer signs a Taproot coin known from its witness output only" $ do-      let internal = derivePubKey ctx secretOne-          (taproot, _) = spendingPsbt ctx (taprootScriptOutput ctx (TaprootOutput internal Nothing))-      (fmap isJust . tapKeySig . inputAt 0 =<< signPsbt btc ctx signer (withInputs (insertInputTapInternalKey ctx internal <$> taproot.inputs) taproot)) `shouldBe` Right True+      let internal = derivePubKey secretOne+          (taproot, _) = spendingPsbt (taprootScriptOutput (TaprootOutput internal Nothing))+      (fmap isJust . tapKeySig . inputAt 0 =<< signPsbt btc signer (withInputs (insertInputTapInternalKey internal <$> taproot.inputs) taproot)) `shouldBe` Right True  {- The fields of version 2, read one by one -} 
test/Haskoin/Transaction/TaprootSpec.hs view
@@ -38,21 +38,21 @@ import Test.QuickCheck  spec :: Spec-spec = prepareContext $ \ctx -> do+spec = do   TestVector {testScriptPubKey, testKeyPath} <-     runIO $-      readTestFileParser (testVectorParseJSON ctx) "bip341.json"+      readTestFileParser testVectorParseJSON "bip341.json"   describe "Script trees and output keys, from the scriptPubKey vectors of BIP 341" $ do     it "calculate the leaf hashes and the Merkle root" $       mapM_ testHashes testScriptPubKey     it "build the output key" $-      mapM_ (testOutputKey ctx) testScriptPubKey+      mapM_ testOutputKey testScriptPubKey     it "build the script output" $-      mapM_ (testScriptOutput ctx) testScriptPubKey+      mapM_ testScriptOutput testScriptPubKey     it "build the control blocks, which verify the script path" $-      mapM_ (testControlBlocks ctx) testScriptPubKey+      mapM_ testControlBlocks testScriptPubKey     it "give the address" $-      mapM_ (testAddress ctx) testScriptPubKey+      mapM_ testAddress testScriptPubKey     it "list the leaves of a tree depth first and build the tree back from them" $       mapM_ testTreeLeaves testScriptPubKey @@ -60,62 +60,62 @@     -- BIP 341 tweaks the x-only internal key, so the output does not     -- depend on the parity of the y coordinate of the key given     prop "is the same for a key and its negation" $-      forAll (arbitraryKeyPair ctx) $ \(_, p) ->-        let x = exportXOnlyPubKey ctx p.point-            negated = (.point) (either error id (unmarshal ctx (BS.cons (if keyParity ctx p.point == 0 then 0x03 else 0x02) x)) :: PublicKey)-         in taprootScriptOutput ctx (TaprootOutput negated Nothing) === taprootScriptOutput ctx (TaprootOutput p.point Nothing)+      forAll arbitraryKeyPair $ \(_, p) ->+        let x = exportXOnlyPubKey p.point+            negated = (.point) (either error id (decodeSerial (BS.cons (if keyParity p.point == 0 then 0x03 else 0x02) x)) :: PublicKey)+         in taprootScriptOutput (TaprootOutput negated Nothing) === taprootScriptOutput (TaprootOutput p.point Nothing)      prop "has the x coordinate of the public key of the output secret key" $-      forAll (arbitraryKeyPair ctx) $ \(k, p) ->-        let tweaked = fromJust (taprootOutputSecKey ctx k.key Nothing)-         in exportXOnlyPubKey ctx (derivePubKey ctx tweaked) === exportXOnlyPubKey ctx (taprootOutputKey ctx (TaprootOutput p.point Nothing))+      forAll arbitraryKeyPair $ \(k, p) ->+        let tweaked = fromJust (taprootOutputSecKey k.key Nothing)+         in exportXOnlyPubKey (derivePubKey tweaked) === exportXOnlyPubKey (taprootOutputKey (TaprootOutput p.point Nothing))      -- The test vectors of BIP 86: the keys at m/86'/0'/0'/0/0, 0/1 and     -- 1/0 of the mnemonic "abandon ... about"     forM_ bip86Vectors $ \(path, internalKey, outputKey, address) ->       it ("of the BIP 86 key at " <> show path <> " is " <> show outputKey) $ do         let root = fromJust (xPrvImport btc "xprv9s21ZrQH143K3GJpoapnV8SFfukcVBSfeCficPSGfubmSFDxo1kuHnLisriDvSnRRuL2Qrg5ggqHKNVpxR86QEC8w35uxmGoggxtQTPvfUu")-            secret = (derivePath ctx (path :: DerivPath) root).key-            output = TaprootOutput (derivePubKey ctx secret) Nothing-        encodeHex (exportXOnlyPubKey ctx (derivePubKey ctx secret)) `shouldBe` internalKey-        encodeHex (exportXOnlyPubKey ctx (taprootOutputKey ctx output)) `shouldBe` outputKey-        encodeHex (marshal ctx (taprootScriptOutput ctx output)) `shouldBe` "5120" <> outputKey-        (addrToText btc =<< outputAddress btc ctx (taprootScriptOutput ctx output)) `shouldBe` Just address+            secret = (derivePath (path :: DerivPath) root).key+            output = TaprootOutput (derivePubKey secret) Nothing+        encodeHex (exportXOnlyPubKey (derivePubKey secret)) `shouldBe` internalKey+        encodeHex (exportXOnlyPubKey (taprootOutputKey output)) `shouldBe` outputKey+        encodeHex (encodeSerial (taprootScriptOutput output)) `shouldBe` "5120" <> outputKey+        (addrToText btc =<< outputAddress btc (taprootScriptOutput output)) `shouldBe` Just address         -- The output secret key signs for the output key-        fmap (encodeHex . exportXOnlyPubKey ctx . derivePubKey ctx) (taprootOutputSecKey ctx secret Nothing) `shouldBe` Just outputKey+        fmap (encodeHex . exportXOnlyPubKey . derivePubKey) (taprootOutputSecKey secret Nothing) `shouldBe` Just outputKey    describe "Key path spending, from the keyPathSpending vector of BIP 341" $ do     forM_ testKeyPath.cases $ \c ->       it ("input " <> show c.index <> ": the tweak, the digest and the signature, with hash type " <> show (fromIntegral c.hashType :: Word32)) $ do-        let output = TaprootOutput (derivePubKey ctx c.internalSecret) (MASTCommitment <$> c.merkleRoot)+        let output = TaprootOutput (derivePubKey c.internalSecret) (MASTCommitment <$> c.merkleRoot)             program = BS.drop 2 (testKeyPath.spent !! c.index).script-        encodeHex (exportXOnlyPubKey ctx (derivePubKey ctx c.internalSecret)) `shouldBe` c.internalPubKey-        exportXOnlyPubKey ctx (taprootOutputKey ctx output) `shouldBe` program-        let tweaked = fromJust (taprootOutputSecKey ctx c.internalSecret (MASTCommitment <$> c.merkleRoot))+        encodeHex (exportXOnlyPubKey (derivePubKey c.internalSecret)) `shouldBe` c.internalPubKey+        exportXOnlyPubKey (taprootOutputKey output) `shouldBe` program+        let tweaked = fromJust (taprootOutputSecKey c.internalSecret (MASTCommitment <$> c.merkleRoot))         tweaked `shouldBe` fromJust (secKey (hexBytes c.tweakedSecret))         digest <- expectRight (taprootSigHash testKeyPath.unsignedTx testKeyPath.spent c.index c.hashType Nothing Nothing)         encodeHex (runPutS (serialize digest)) `shouldBe` c.sigHash         -- The signature of the vector was made with 32 zero bytes of         -- auxiliary randomness, as signSchnorr signs-        fmap (encodeHex . encodeTaprootSig) (taprootSignature (signSchnorr ctx tweaked (hashToMsg digest)) c.hashType) `shouldBe` Right (head c.witness)+        fmap (encodeHex . encodeTaprootSig) (taprootSignature (signSchnorr tweaked (hashToMsg digest)) c.hashType) `shouldBe` Right (head c.witness)      it "the fully signed transaction of the vector verifies against the coins it spends" $-      verifyStdTx btc ctx testKeyPath.signedTx (coinsOf ctx testKeyPath) `shouldBe` True+      verifyStdTx btc testKeyPath.signedTx (coinsOf testKeyPath) `shouldBe` True      it "the fully signed transaction of the vector does not verify when a Taproot coin is given a wrong amount" $ do-      let coins = [(so, if i == (0 :: Int) then v + 1 else v, op) | (i, (so, v, op)) <- zip [0 ..] (coinsOf ctx testKeyPath)]-      verifyStdTx btc ctx testKeyPath.signedTx coins `shouldBe` False+      let coins = [(so, if i == (0 :: Int) then v + 1 else v, op) | (i, (so, v, op)) <- zip [0 ..] (coinsOf testKeyPath)]+      verifyStdTx btc testKeyPath.signedTx coins `shouldBe` False      it "signTx signs the Taproot inputs of the vector by their key path with the internal keys, and the result verifies" $ do       let tx = testKeyPath.unsignedTx-          coins = coinsOf ctx testKeyPath+          coins = coinsOf testKeyPath           -- The internal keys of the Taproot inputs, with the key of the           -- output as signTx finds it: the tweak of a key without a tree           -- is the output only when the vector has no Merkle root           noTree = [c | c <- testKeyPath.cases, isNothing c.merkleRoot]           sigInputs = [SigInput so v op c.hashType Nothing | c <- noTree, let (so, v, op) = coins !! c.index]           others = [SigInput so v op sigHashAll Nothing | (i, (so, v, op)) <- zip [0 ..] coins, i `notElem` map (.index) noTree]-      signed <- expectRight (signTx btc ctx tx (sigInputs <> others) (map (.internalSecret) noTree))+      signed <- expectRight (signTx btc tx (sigInputs <> others) (map (.internalSecret) noTree))       forM_ noTree $ \c ->         (signed.witness !! c.index) `shouldBe` [hexBytes (head c.witness)] @@ -123,8 +123,8 @@     -- signer against the BIP for all seven inputs and hash types     it "signTaprootInput signs each Taproot input of the vector with its output secret key, and gives the witness of the vector" $       forM_ testKeyPath.cases $ \c -> do-        let tweaked = fromJust (taprootOutputSecKey ctx c.internalSecret (MASTCommitment <$> c.merkleRoot))-        signed <- expectRight (signTaprootInput ctx testKeyPath.unsignedTx testKeyPath.spent c.index c.hashType tweaked)+        let tweaked = fromJust (taprootOutputSecKey c.internalSecret (MASTCommitment <$> c.merkleRoot))+        signed <- expectRight (signTaprootInput testKeyPath.unsignedTx testKeyPath.spent c.index c.hashType tweaked)         (signed.witness !! c.index) `shouldBe` [hexBytes (head c.witness)]      it "taprootSigHash refuses an index out of range, a hash type a Taproot signature may not use, missing coins and SIGHASH_SINGLE without an output" $ do@@ -185,79 +185,79 @@       sigHashDefault `shouldBe` 0    describe "Witnesses" $ do-    let (_, p) = bip86Key ctx+    let (_, p) = bip86Key         -- The internal key as a control block gives it back: the point of even y-        internalKey = fromJust (importXOnlyPubKey ctx (exportXOnlyPubKey ctx p.point))+        internalKey = fromJust (importXOnlyPubKey (exportXOnlyPubKey p.point))         leaf = Script [OP_2DROP, OP_1]         tree = MASTBranch (MASTLeaf tapscriptLeafVersion leaf) (MASTLeaf tapscriptLeafVersion (Script [OP_1]))         output = TaprootOutput internalKey (Just tree)-        outputKey = taprootOutputKey ctx output+        outputKey = taprootOutputKey output         [(_, _, proof), _] = getMerkleProofs tree-        spend = ScriptPathData {annex = Nothing, stack = ["aa", "bbbb"], script = leaf, extIsOdd = odd (keyParity ctx outputKey), leafVersion = tapscriptLeafVersion, internalKey, control = proof, opaqueScript = Nothing}-        control = encodeControlBlock ctx (tapscriptLeafVersion + keyParity ctx outputKey) internalKey proof+        spend = ScriptPathData {annex = Nothing, stack = ["aa", "bbbb"], script = leaf, extIsOdd = odd (keyParity outputKey), leafVersion = tapscriptLeafVersion, internalKey, control = proof, opaqueScript = Nothing}+        control = encodeControlBlock (tapscriptLeafVersion + keyParity outputKey) internalKey proof         scriptBytes = runPutS (serialize leaf)      it "a key path spend is one signature, with the annex after it when there is one" $ do-      encodeTaprootWitness ctx (KeyPathSpend "sig" Nothing) `shouldBe` Right ["sig"]-      encodeTaprootWitness ctx (KeyPathSpend "sig" (Just "\x50\&annex")) `shouldBe` Right ["sig", "\x50\&annex"]-      viewTaprootWitness ctx ["sig"] `shouldBe` Just (KeyPathSpend "sig" Nothing)-      viewTaprootWitness ctx ["sig", "\x50\&annex"] `shouldBe` Just (KeyPathSpend "sig" (Just "\x50\&annex"))+      encodeTaprootWitness (KeyPathSpend "sig" Nothing) `shouldBe` Right ["sig"]+      encodeTaprootWitness (KeyPathSpend "sig" (Just "\x50\&annex")) `shouldBe` Right ["sig", "\x50\&annex"]+      viewTaprootWitness ["sig"] `shouldBe` Just (KeyPathSpend "sig" Nothing)+      viewTaprootWitness ["sig", "\x50\&annex"] `shouldBe` Just (KeyPathSpend "sig" (Just "\x50\&annex"))       -- One item is the signature even when it starts with the annex byte-      viewTaprootWitness ctx ["\x50sig"] `shouldBe` Just (KeyPathSpend "\x50sig" Nothing)-      viewTaprootWitness ctx [] `shouldBe` Nothing+      viewTaprootWitness ["\x50sig"] `shouldBe` Just (KeyPathSpend "\x50sig" Nothing)+      viewTaprootWitness [] `shouldBe` Nothing      it "a script path spend is the stack, the script and the control block, in the order of BIP 341, then the annex" $ do-      encodeTaprootWitness ctx (ScriptPathSpend spend) `shouldBe` Right ["aa", "bbbb", scriptBytes, control]-      encodeTaprootWitness ctx (ScriptPathSpend spend {annex = Just "\x50"}) `shouldBe` Right ["aa", "bbbb", scriptBytes, control, "\x50"]-      viewTaprootWitness ctx ["aa", "bbbb", scriptBytes, control] `shouldBe` Just (ScriptPathSpend spend)-      viewTaprootWitness ctx ["aa", "bbbb", scriptBytes, control, "\x50"] `shouldBe` Just (ScriptPathSpend spend {annex = Just "\x50"})-      viewTaprootWitness ctx [scriptBytes, control] `shouldBe` Just (ScriptPathSpend spend {stack = []})+      encodeTaprootWitness (ScriptPathSpend spend) `shouldBe` Right ["aa", "bbbb", scriptBytes, control]+      encodeTaprootWitness (ScriptPathSpend spend {annex = Just "\x50"}) `shouldBe` Right ["aa", "bbbb", scriptBytes, control, "\x50"]+      viewTaprootWitness ["aa", "bbbb", scriptBytes, control] `shouldBe` Just (ScriptPathSpend spend)+      viewTaprootWitness ["aa", "bbbb", scriptBytes, control, "\x50"] `shouldBe` Just (ScriptPathSpend spend {annex = Just "\x50"})+      viewTaprootWitness [scriptBytes, control] `shouldBe` Just (ScriptPathSpend spend {stack = []})       -- The control block and the script in the other order are not a       -- spend: the script is not a control block-      viewTaprootWitness ctx [control, scriptBytes] `shouldBe` Nothing+      viewTaprootWitness [control, scriptBytes] `shouldBe` Nothing      -- BIP 342: a Tapscript that holds an OP_SUCCESSx opcode succeeds, "even     -- if later bytes in the tapscript would fail to decode otherwise". 50 is     -- OP_SUCCESS80, and 4c is an OP_PUSHDATA1 with no length after it.     it "a script path spend is read whatever the bytes of its script are" $ do       let opaque = "\x50\x4c"-          opaqueControl = encodeControlBlock ctx 0xc0 internalKey []+          opaqueControl = encodeControlBlock 0xc0 internalKey []           expected = ScriptPathData {annex = Nothing, stack = [], script = Script [], extIsOdd = False, leafVersion = 0xc0, internalKey, control = [], opaqueScript = Just opaque}-      viewTaprootWitness ctx [opaque, opaqueControl] `shouldBe` Just (ScriptPathSpend expected)+      viewTaprootWitness [opaque, opaqueControl] `shouldBe` Just (ScriptPathSpend expected)       scriptPathScriptBytes expected `shouldBe` opaque-      encodeTaprootWitness ctx (ScriptPathSpend expected) `shouldBe` Right [opaque, opaqueControl]+      encodeTaprootWitness (ScriptPathSpend expected) `shouldBe` Right [opaque, opaqueControl]       -- A leaf of another version, whose bytes are a push cut short-      fmap (\case ScriptPathSpend d -> (d.leafVersion, d.opaqueScript); _ -> (0, Nothing)) (viewTaprootWitness ctx ["\x02\xaa", encodeControlBlock ctx 0xc2 internalKey []])+      fmap (\case ScriptPathSpend d -> (d.leafVersion, d.opaqueScript); _ -> (0, Nothing)) (viewTaprootWitness ["\x02\xaa", encodeControlBlock 0xc2 internalKey []])         `shouldBe` Just (0xc2, Just "\x02\xaa")      it "a script path spend of bytes that are not opcodes verifies against the output key that commits to those bytes" $ do       let opaque = "\x50\x4c"-          key = taprootOutputKey ctx (TaprootOutput internalKey (Just (MASTCommitment (leafHashBytes 0xc0 opaque))))-          opaqueSpend = ScriptPathData {annex = Nothing, stack = [], script = Script [], extIsOdd = odd (keyParity ctx key), leafVersion = 0xc0, internalKey, control = [], opaqueScript = Just opaque}-      verifyScriptPathData ctx key opaqueSpend `shouldBe` True-      verifyScriptPathData ctx key opaqueSpend {opaqueScript = Just "\x50\x4d"} `shouldBe` False+          key = taprootOutputKey (TaprootOutput internalKey (Just (MASTCommitment (leafHashBytes 0xc0 opaque))))+          opaqueSpend = ScriptPathData {annex = Nothing, stack = [], script = Script [], extIsOdd = odd (keyParity key), leafVersion = 0xc0, internalKey, control = [], opaqueScript = Just opaque}+      verifyScriptPathData key opaqueSpend `shouldBe` True+      verifyScriptPathData key opaqueSpend {opaqueScript = Just "\x50\x4d"} `shouldBe` False      it "a witness is not written with an annex that is empty or does not start with 0x50" $ do-      encodeTaprootWitness ctx (KeyPathSpend "sig" (Just "hello")) `shouldBe` Left "encodeTaprootWitness: an annex starts with 0x50"-      encodeTaprootWitness ctx (KeyPathSpend "sig" (Just "")) `shouldBe` Left "encodeTaprootWitness: an annex starts with 0x50"-      encodeTaprootWitness ctx (ScriptPathSpend spend {annex = Just "hello"}) `shouldBe` Left "encodeTaprootWitness: an annex starts with 0x50"+      encodeTaprootWitness (KeyPathSpend "sig" (Just "hello")) `shouldBe` Left "encodeTaprootWitness: an annex starts with 0x50"+      encodeTaprootWitness (KeyPathSpend "sig" (Just "")) `shouldBe` Left "encodeTaprootWitness: an annex starts with 0x50"+      encodeTaprootWitness (ScriptPathSpend spend {annex = Just "hello"}) `shouldBe` Left "encodeTaprootWitness: an annex starts with 0x50"      it "a witness is written with a proof of 128 hashes, and not with one of 129" $ do       let node = fromJust (digestFromByteString @SHA256 (BS.replicate 32 1))       -- two stack items, the script and the control block-      fmap length (encodeTaprootWitness ctx (ScriptPathSpend spend {control = replicate 128 node})) `shouldBe` Right 4-      encodeTaprootWitness ctx (ScriptPathSpend spend {control = replicate 129 node}) `shouldBe` Left "encodeTaprootWitness: a control block holds at most 128 nodes"+      fmap length (encodeTaprootWitness (ScriptPathSpend spend {control = replicate 128 node})) `shouldBe` Right 4+      encodeTaprootWitness (ScriptPathSpend spend {control = replicate 129 node}) `shouldBe` Left "encodeTaprootWitness: a control block holds at most 128 nodes"      it "a witness is not written with a leaf version that a control block cannot carry" $ do-      encodeTaprootWitness ctx (ScriptPathSpend spend {leafVersion = 0xc1}) `shouldBe` Left "encodeTaprootWitness: a control block cannot carry the leaf version 193"-      encodeTaprootWitness ctx (ScriptPathSpend spend {leafVersion = 0x50}) `shouldBe` Left "encodeTaprootWitness: a control block cannot carry the leaf version 80"+      encodeTaprootWitness (ScriptPathSpend spend {leafVersion = 0xc1}) `shouldBe` Left "encodeTaprootWitness: a control block cannot carry the leaf version 193"+      encodeTaprootWitness (ScriptPathSpend spend {leafVersion = 0x50}) `shouldBe` Left "encodeTaprootWitness: a control block cannot carry the leaf version 80"      it "a script path spend verifies against its output key, and not with the other parity or another proof" $ do-      verifyScriptPathData ctx outputKey spend `shouldBe` True-      verifyScriptPathData ctx outputKey spend {extIsOdd = not spend.extIsOdd} `shouldBe` False-      verifyScriptPathData ctx outputKey spend {control = []} `shouldBe` False-      verifyScriptPathData ctx outputKey spend {script = Script [OP_1]} `shouldBe` False-      verifyScriptPathData ctx (taprootOutputKey ctx (TaprootOutput internalKey Nothing)) spend `shouldBe` False+      verifyScriptPathData outputKey spend `shouldBe` True+      verifyScriptPathData outputKey spend {extIsOdd = not spend.extIsOdd} `shouldBe` False+      verifyScriptPathData outputKey spend {control = []} `shouldBe` False+      verifyScriptPathData outputKey spend {script = Script [OP_1]} `shouldBe` False+      verifyScriptPathData (taprootOutputKey (TaprootOutput internalKey Nothing)) spend `shouldBe` False      it "a control block is 33 bytes plus 32 per node, with at most 128 nodes" $ do       let node = BS.replicate 32 1@@ -267,24 +267,24 @@           deepest = base <> BS.concat (replicate 128 node)           tooDeep = base <> BS.concat (replicate 129 node)       maxControlBlockNodes `shouldBe` 128-      fmap (\(v, k, nodes) -> (v, exportXOnlyPubKey ctx k == exportXOnlyPubKey ctx internalKey, length nodes)) (decodeControlBlock ctx deepest) `shouldBe` Right (tapscriptLeafVersion + keyParity ctx outputKey, True, 128)-      decodeControlBlock ctx short `shouldBe` Left "decodeControlBlock: a control block is 33 bytes plus 32 per node, not 20"-      decodeControlBlock ctx tooLong `shouldBe` Left "decodeControlBlock: a control block is 33 bytes plus 32 per node, not 69"-      decodeControlBlock ctx tooDeep `shouldBe` Left "decodeControlBlock: more than 128 nodes"-      viewTaprootWitness ctx [scriptBytes, short] `shouldBe` Nothing-      viewTaprootWitness ctx [scriptBytes, tooLong] `shouldBe` Nothing-      viewTaprootWitness ctx [scriptBytes, tooDeep] `shouldBe` Nothing-      fmap (\case ScriptPathSpend d -> length d.control; _ -> 0) (viewTaprootWitness ctx [scriptBytes, deepest]) `shouldBe` Just 128+      fmap (\(v, k, nodes) -> (v, exportXOnlyPubKey k == exportXOnlyPubKey internalKey, length nodes)) (decodeControlBlock deepest) `shouldBe` Right (tapscriptLeafVersion + keyParity outputKey, True, 128)+      decodeControlBlock short `shouldBe` Left "decodeControlBlock: a control block is 33 bytes plus 32 per node, not 20"+      decodeControlBlock tooLong `shouldBe` Left "decodeControlBlock: a control block is 33 bytes plus 32 per node, not 69"+      decodeControlBlock tooDeep `shouldBe` Left "decodeControlBlock: more than 128 nodes"+      viewTaprootWitness [scriptBytes, short] `shouldBe` Nothing+      viewTaprootWitness [scriptBytes, tooLong] `shouldBe` Nothing+      viewTaprootWitness [scriptBytes, tooDeep] `shouldBe` Nothing+      fmap (\case ScriptPathSpend d -> length d.control; _ -> 0) (viewTaprootWitness [scriptBytes, deepest]) `shouldBe` Just 128      it "a control block starts with the leaf version and the parity bit, then the x-only internal key" $-      encodeHex (encodeControlBlock ctx 0xc1 p.point [])+      encodeHex (encodeControlBlock 0xc1 p.point [])         `shouldBe` "c1cc8a4bc64d897bddc5fbc2f670f7a8ba0b386779106cf1223c6fc5d7cd6fc115"      prop "encoding a witness and viewing it gives the witness back" $       forAll ((,) <$> arbitraryBS1 <*> arbitraryMaybe arbitraryBS) $ \(sig, annexData) ->         let annex = ("\x50" <>) <$> annexData             spendWith a = ScriptPathSpend spend {annex = a}-            viewed witness = viewTaprootWitness ctx =<< eitherToMaybe (encodeTaprootWitness ctx witness)+            viewed witness = viewTaprootWitness =<< eitherToMaybe (encodeTaprootWitness witness)          in (viewed (KeyPathSpend sig annex), viewed (spendWith annex))               === (Just (KeyPathSpend sig annex), Just (spendWith annex)) @@ -310,16 +310,16 @@    describe "X-only keys" $ do     it "serialize to the x coordinate, and read back as the point of even y" $ do-      let (_, p) = bip86Key ctx-          x = exportXOnlyPubKey ctx p.point-      marshal ctx (XOnlyPubKey p.point) `shouldBe` x-      fmap (keyParity ctx . (.point)) (unmarshal ctx x :: Either String XOnlyPubKey) `shouldBe` Right 0-      fmap (XOnlyPubKey p.point ==) (unmarshal ctx x) `shouldBe` Right True-      unmarshalJSON ctx (marshalJSON ctx (XOnlyPubKey p.point)) `shouldBe` Just (XOnlyPubKey p.point)-      (unmarshal ctx (BS.replicate 32 0xff) :: Either String XOnlyPubKey) `shouldSatisfy` isLeft+      let (_, p) = bip86Key+          x = exportXOnlyPubKey p.point+      encodeSerial (XOnlyPubKey p.point) `shouldBe` x+      fmap (keyParity . (.point)) (decodeSerial x :: Either String XOnlyPubKey) `shouldBe` Right 0+      fmap (XOnlyPubKey p.point ==) (decodeSerial x) `shouldBe` Right True+      decode (encode (XOnlyPubKey p.point)) `shouldBe` Just (XOnlyPubKey p.point)+      (decodeSerial (BS.replicate 32 0xff) :: Either String XOnlyPubKey) `shouldSatisfy` isLeft     it "the parity of a key is that of its y coordinate" $ do-      keyParity ctx (fromJust (importPubKey ctx (hexBytes "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))) `shouldBe` 0-      keyParity ctx (fromJust (importPubKey ctx (hexBytes "0379be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))) `shouldBe` 1+      keyParity (fromJust (importPubKey (hexBytes "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))) `shouldBe` 0+      keyParity (fromJust (importPubKey (hexBytes "0379be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))) `shouldBe` 1     it "the Tapscript leaf version is 0xc0" $       tapscriptLeafVersion `shouldBe` 0xc0 @@ -343,10 +343,10 @@     -- 4 keys × 34 bytes + OP_2 + OP_NUMEQUAL.     it "of the 138-byte multi_a leaf is the one Bitcoin Core derives, and so is the output script" $ do       let leaf = scriptOf multiALeaf-          internal = fromJust (importXOnlyPubKey ctx (hexBytes "cba52b4389f798ec8ba66d9520ce532af2fe642b970010e2fbd0ec36bce36970"))+          internal = fromJust (importXOnlyPubKey (hexBytes "cba52b4389f798ec8ba66d9520ce532af2fe642b970010e2fbd0ec36bce36970"))       BS.length (hexBytes multiALeaf) `shouldBe` 138       digestHex (leafHash 0xc0 leaf) `shouldBe` "c6831caa9b274f379336d6bcc789aa6e82760d573e3750b97df37e624d8e6c90"-      encodeHex (marshal ctx (taprootScriptOutput ctx (TaprootOutput internal (Just (MASTLeaf 0xc0 leaf)))))+      encodeHex (encodeSerial (taprootScriptOutput (TaprootOutput internal (Just (MASTLeaf 0xc0 leaf)))))         `shouldBe` "51207fd815afed80f6bc581ac94aa52d85c50d2bddff7347e1094936eb71e2f18936"      it "of script bytes that are not a list of opcodes is taken on the bytes" $@@ -362,34 +362,34 @@   -- Python with the base-128 length.   describe "An output made by versions up to 1.5.1 with a leaf of 128 bytes or more" $ do     let internalSecret = fromJust (secKey (hexBytes "01c58048b9108d028cdde54d8ea8fa545cd4145157fad6e5a908809c7e35388d"))-        internal = derivePubKey ctx internalSecret+        internal = derivePubKey internalSecret         oldLeafHash = leafHashBefore152 0xc0 (scriptOf multiALeaf)-        xOnly = encodeHex . exportXOnlyPubKey ctx+        xOnly = encodeHex . exportXOnlyPubKey     it "has a leaf hash that is rebuilt with the base-128 length" $ do       xOnly internal `shouldBe` "cba52b4389f798ec8ba66d9520ce532af2fe642b970010e2fbd0ec36bce36970"       digestHex oldLeafHash `shouldBe` "4a0b2a93f8430729d9467c0bc91d26d54b63802e627783bf808694c8e8dbc372"     it "has the output key of the tree that holds the old leaf hash as a commitment" $-      xOnly (taprootOutputKey ctx (TaprootOutput internal (Just (MASTCommitment oldLeafHash))))+      xOnly (taprootOutputKey (TaprootOutput internal (Just (MASTCommitment oldLeafHash))))         `shouldBe` "15e87fb4cb019af07cf16fa2b9a8451536bd86321dcc11053c70d9038ec97c80"     it "is spent by its key path with the secret key tweaked with that commitment" $-      fmap (xOnly . derivePubKey ctx) (taprootOutputSecKey ctx internalSecret (Just (MASTCommitment oldLeafHash)))+      fmap (xOnly . derivePubKey) (taprootOutputSecKey internalSecret (Just (MASTCommitment oldLeafHash)))         `shouldBe` Just "15e87fb4cb019af07cf16fa2b9a8451536bd86321dcc11053c70d9038ec97c80"     it "keeps the script path of a short leaf next to the long one" $ do       -- The tree {pk(1cf7198d…2500), multi_a leaf}       let short = Script [opPushData (hexBytes "1cf7198d10d0552c8df4d0380372a5fa224a1226fc3a49546a416086442d2500"), OP_CHECKSIG]           oldTree = MASTBranch (MASTLeaf 0xc0 short) (MASTCommitment oldLeafHash)-          oldKey = taprootOutputKey ctx (TaprootOutput internal (Just oldTree))+          oldKey = taprootOutputKey (TaprootOutput internal (Just oldTree))           proofs = [proof | (_, _, proof) <- getMerkleProofs oldTree]-          spendOf proof = ScriptPathData {annex = Nothing, stack = [], script = short, extIsOdd = odd (keyParity ctx oldKey), leafVersion = 0xc0, internalKey = internal, control = proof, opaqueScript = Nothing}+          spendOf proof = ScriptPathData {annex = Nothing, stack = [], script = short, extIsOdd = odd (keyParity oldKey), leafVersion = 0xc0, internalKey = internal, control = proof, opaqueScript = Nothing}       xOnly oldKey `shouldBe` "120ed04aacce013f8ed3b63a53143aec81a4c05fa0a263a693d14aa8bebd7efd"       map (map digestHex) proofs `shouldBe` [["4a0b2a93f8430729d9467c0bc91d26d54b63802e627783bf808694c8e8dbc372"]]-      map (verifyScriptPathData ctx oldKey . spendOf) proofs `shouldBe` [True]+      map (verifyScriptPathData oldKey . spendOf) proofs `shouldBe` [True]     it "is not the output of the same tree today" $ do       let short = Script [opPushData (hexBytes "1cf7198d10d0552c8df4d0380372a5fa224a1226fc3a49546a416086442d2500"), OP_CHECKSIG]           tree = MASTBranch (MASTLeaf 0xc0 short) (MASTLeaf 0xc0 (scriptOf multiALeaf))       -- Root and key computed in Python from the text of BIP 341       digestHex (mastCommitment tree) `shouldBe` "4bff8cf0bd46ff4d4470c11a7f407dfee7078c7675b877691310c0ee0058c620"-      xOnly (taprootOutputKey ctx (TaprootOutput internal (Just tree))) `shouldBe` "b672ffdc20bf79cf4bda88ec7a0ad9c53c91e032f2bc169af425eae9dac8afe0"+      xOnly (taprootOutputKey (TaprootOutput internal (Just tree))) `shouldBe` "b672ffdc20bf79cf4bda88ec7a0ad9c53c91e032f2bc169af425eae9dac8afe0"    describe "Merkle proofs" $ do     -- tr(ecd5eddb…7670,{pk(A),{pk(B),{pk(C),pk(D)}}}). The Merkle root and@@ -403,9 +403,9 @@           c = pkLeaf "5807c60bab1f93b36747e3d120c29fa898ab37e616b3b7635b21e5a71888e6da"           d = pkLeaf "33045c7755fc6aef51859ad00d7393f1d23ff8b0bd6acf0d6c6d7a72502d905a"           tree = MASTBranch a (MASTBranch b (MASTBranch c d))-          internal = fromJust (importXOnlyPubKey ctx (hexBytes "ecd5eddb647ff233131e292cef048228bce3a3b045319d563b57d59e294c7670"))-          outputKey = taprootOutputKey ctx (TaprootOutput internal (Just tree))-          controlBlocks = [encodeHex (encodeControlBlock ctx (0xc0 + keyParity ctx outputKey) internal proof) | (_, _, proof) <- getMerkleProofs tree]+          internal = fromJust (importXOnlyPubKey (hexBytes "ecd5eddb647ff233131e292cef048228bce3a3b045319d563b57d59e294c7670"))+          outputKey = taprootOutputKey (TaprootOutput internal (Just tree))+          controlBlocks = [encodeHex (encodeControlBlock (0xc0 + keyParity outputKey) internal proof) | (_, _, proof) <- getMerkleProofs tree]       digestHex (mastCommitment tree) `shouldBe` "e0f4dd44e6affb70c64661b32d78666ce2296fcdf9abdcbbe9482e91398f4ac5"       controlBlocks         `shouldBe` [ "c1ecd5eddb647ff233131e292cef048228bce3a3b045319d563b57d59e294c7670cd8b2619baff8006c3b4f8d86a79d76d2a636b226a43602aa7b17908152a2db6",@@ -424,12 +424,12 @@               === (root, paths)     prop "gives each leaf a proof of as many hashes as the leaf is deep, which verifies against the output key" $       forAll (arbitraryMAST True) $ \tree ->-        let (_, p) = bip86Key ctx-            internal = fromJust (importXOnlyPubKey ctx (exportXOnlyPubKey ctx p.point))-            outputKey = taprootOutputKey ctx (TaprootOutput internal (Just tree))-            spendOf (version, script, proof) = ScriptPathData {annex = Nothing, stack = [], script, extIsOdd = odd (keyParity ctx outputKey), leafVersion = version, internalKey = internal, control = proof, opaqueScript = Nothing}+        let (_, p) = bip86Key+            internal = fromJust (importXOnlyPubKey (exportXOnlyPubKey p.point))+            outputKey = taprootOutputKey (TaprootOutput internal (Just tree))+            spendOf (version, script, proof) = ScriptPathData {annex = Nothing, stack = [], script, extIsOdd = odd (keyParity outputKey), leafVersion = version, internalKey = internal, control = proof, opaqueScript = Nothing}             proofs = getMerkleProofs tree-         in (map (\(_, _, proof) -> length proof) proofs, map (verifyScriptPathData ctx outputKey . spendOf) proofs)+         in (map (\(_, _, proof) -> length proof) proofs, map (verifyScriptPathData outputKey . spendOf) proofs)               === (leafDepths tree, map (const True) proofs)     prop "without a commitment is built back from the list of its leaves" $       forAll (arbitraryMAST False) $ \tree ->@@ -446,8 +446,8 @@       length spends `shouldBe` 24       let verdict (txid, spentScript, witness) =             ( txid,-              case (viewTaprootWitness ctx witness, importXOnlyPubKey ctx (BS.drop 2 spentScript)) of-                (Just (ScriptPathSpend spd), Just outputKey) -> verifyScriptPathData ctx outputKey spd+              case (viewTaprootWitness witness, importXOnlyPubKey (BS.drop 2 spentScript)) of+                (Just (ScriptPathSpend spd), Just outputKey) -> verifyScriptPathData outputKey spd                 _ -> False             )       filter (not . snd) (map verdict spends) `shouldBe` []@@ -482,61 +482,61 @@         `shouldBe` Left "taprootSigHash: SIGHASH_SINGLE without an output at the input index"    describe "verifyStdTx on Taproot inputs" $ do-    let coinOfTx = oneCoin ctx+    let coinOfTx = oneCoin     it "accepts the key path spend with an annex that Bitcoin Core 32.1 mined on regtest" $ do       let tx = txOf keyPathAnnexTx-      verifyStdTx btc ctx tx (coinOfTx tx "512028066f61c28af1ecb48c7948f8b5770838eec15223c8697a8e40510c2c29ea04") `shouldBe` True+      verifyStdTx btc tx (coinOfTx tx "512028066f61c28af1ecb48c7948f8b5770838eec15223c8697a8e40510c2c29ea04") `shouldBe` True     it "accepts the script path spend of a single key leaf with an annex that Bitcoin Core 32.1 mined on regtest" $ do       let tx = txOf scriptPathAnnexTx-      verifyStdTx btc ctx tx (coinOfTx tx "5120a354b6c111a5f8339fd8ea5bc6147f8ca829029188e4d3f7622751417328be18") `shouldBe` True+      verifyStdTx btc tx (coinOfTx tx "5120a354b6c111a5f8339fd8ea5bc6147f8ca829029188e4d3f7622751417328be18") `shouldBe` True     -- The witness holds a valid signature of the leaf key over the leaf     -- "<key> OP_CHECKSIG", and a control block that names the same key as     -- internal key. The coin's output key does not commit to that leaf.     it "refuses a script path spend whose leaf the output key of the coin does not commit to" $ do       let tx = txOf uncommittedLeafTx-      verifyStdTx btc ctx tx (coinOfTx tx "5120da4710964f7852695de2da025290e24af6d8c281de5a0b902b7135fd9fd74d21") `shouldBe` False+      verifyStdTx btc tx (coinOfTx tx "5120da4710964f7852695de2da025290e24af6d8c281de5a0b902b7135fd9fd74d21") `shouldBe` False     it "refuses a Taproot input that has an input script" $ do       let tx = txOf keyPathAnnexTx           withScript = tx {inputs = [i {script = "\x51"} | i <- tx.inputs]} :: Tx-      verifyStdTx btc ctx withScript (coinOfTx tx "512028066f61c28af1ecb48c7948f8b5770838eec15223c8697a8e40510c2c29ea04") `shouldBe` False+      verifyStdTx btc withScript (coinOfTx tx "512028066f61c28af1ecb48c7948f8b5770838eec15223c8697a8e40510c2c29ea04") `shouldBe` False      -- BIP 342 defines the rules of leaf version 0xc0 only. A leaf of another     -- version is not a Tapscript, so its key check is not something this     -- function can vouch for.     it "verifies the script path spend of a single key leaf of version 0xc0, and not of version 0xc2" $ do-      let (leafSecret, leafPublic) = bip86Key ctx-          internal = fromJust (importXOnlyPubKey ctx (hexBytes "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))-          leafScript = Script [opPushData (exportXOnlyPubKey ctx leafPublic.point), OP_CHECKSIG]+      let (leafSecret, leafPublic) = bip86Key+          internal = fromJust (importXOnlyPubKey (hexBytes "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))+          leafScript = Script [opPushData (exportXOnlyPubKey leafPublic.point), OP_CHECKSIG]           outpoint = OutPoint "1111111111111111111111111111111111111111111111111111111111111111" 0           spendWith version = do             let output = TaprootOutput internal (Just (MASTLeaf version leafScript))-                coinScript = taprootScriptOutput ctx output-                unsigned = buildTx ctx [outpoint] [(coinScript, 99000)]-            digest <- taprootSigHash unsigned [TxOut 100000 (marshal ctx coinScript)] 0 sigHashDefault Nothing (Just (leafHash version leafScript, 0xffffffff))-            signature <- taprootSignature (signSchnorr ctx leafSecret.key (hashToMsg digest)) sigHashDefault+                coinScript = taprootScriptOutput output+                unsigned = buildTx [outpoint] [(coinScript, 99000)]+            digest <- taprootSigHash unsigned [TxOut 100000 (encodeSerial coinScript)] 0 sigHashDefault Nothing (Just (leafHash version leafScript, 0xffffffff))+            signature <- taprootSignature (signSchnorr leafSecret.key (hashToMsg digest)) sigHashDefault             witness <--              encodeTaprootWitness ctx . ScriptPathSpend $-                ScriptPathData {annex = Nothing, stack = [encodeTaprootSig signature], script = leafScript, extIsOdd = odd (keyParity ctx (taprootOutputKey ctx output)), leafVersion = version, internalKey = internal, control = [], opaqueScript = Nothing}-            return (verifyStdTx btc ctx (Tx unsigned.version unsigned.inputs unsigned.outputs [witness] unsigned.locktime) [(coinScript, 100000, outpoint)])+              encodeTaprootWitness . ScriptPathSpend $+                ScriptPathData {annex = Nothing, stack = [encodeTaprootSig signature], script = leafScript, extIsOdd = odd (keyParity (taprootOutputKey output)), leafVersion = version, internalKey = internal, control = [], opaqueScript = Nothing}+            return (verifyStdTx btc (Tx unsigned.version unsigned.inputs unsigned.outputs [witness] unsigned.locktime) [(coinScript, 100000, outpoint)])       spendWith 0xc0 `shouldBe` Right True       spendWith 0xc2 `shouldBe` Right False    describe "Control blocks" $     it "are refused when the internal key is not the x coordinate of a point" $       -- ff…ff is above the field size, so it is no x coordinate-      decodeControlBlock ctx ("\xc0" <> BS.replicate 32 0xff) `shouldBe` Left "decodeControlBlock: the internal key is not an x-only public key"+      decodeControlBlock ("\xc0" <> BS.replicate 32 0xff) `shouldBe` Left "decodeControlBlock: the internal key is not an x-only public key"    describe "X-only keys as text and bytes" $ do     let x = "7a338b2a113a14b5a008560cbf5d3c46a6c282967c05f739f30668d32fc538b5"-        json t = unmarshalJSON ctx (encode (String t)) :: Maybe XOnlyPubKey+        json t = decode (encode (String t)) :: Maybe XOnlyPubKey     it "are read from the hex of 32 bytes" $-      fmap (encodeHex . marshal ctx) (json x) `shouldBe` Just x+      fmap (encodeHex . encodeSerial) (json x) `shouldBe` Just x     it "are refused from the hex of 33 bytes, of 64 bytes and of 31 bytes" $ do       json (x <> "ff") `shouldBe` Nothing       json (x <> x) `shouldBe` Nothing       json (Data.Text.dropEnd 2 x) `shouldBe` Nothing     it "are refused from 33 bytes" $-      (unmarshal ctx (hexBytes x <> "\xff") :: Either String XOnlyPubKey) `shouldSatisfy` isLeft+      (decodeSerial (hexBytes x <> "\xff") :: Either String XOnlyPubKey) `shouldSatisfy` isLeft    describe "The depth limit of a script tree" $ do     -- BIP 341: a control block holds at most 128 nodes, so a leaf deeper@@ -569,22 +569,22 @@       checkTapTree (MASTLeaf 0xc1 (Script [OP_1])) `shouldBe` Left "checkTapTree: the leaf version 193 is odd"       checkTapTree (MASTLeaf 0x50 (Script [OP_1])) `shouldBe` Left "checkTapTree: the leaf version 0x50 would read as an annex"     it "the proof of a leaf at depth 128 verifies, and the proof of a leaf at depth 129 does not" $ do-      let (_, p) = bip86Key ctx-          internal = fromJust (importXOnlyPubKey ctx (exportXOnlyPubKey ctx p.point))+      let (_, p) = bip86Key+          internal = fromJust (importXOnlyPubKey (exportXOnlyPubKey p.point))           deepest tree =-            let outputKey = taprootOutputKey ctx (TaprootOutput internal (Just tree))+            let outputKey = taprootOutputKey (TaprootOutput internal (Just tree))                 (version, script, proof) = last (getMerkleProofs tree)-                spend = ScriptPathData {annex = Nothing, stack = [], script, extIsOdd = odd (keyParity ctx outputKey), leafVersion = version, internalKey = internal, control = proof, opaqueScript = Nothing}-             in (length proof, verifyScriptPathData ctx outputKey spend)+                spend = ScriptPathData {annex = Nothing, stack = [], script, extIsOdd = odd (keyParity outputKey), leafVersion = version, internalKey = internal, control = proof, opaqueScript = Nothing}+             in (length proof, verifyScriptPathData outputKey spend)       deepest (chain 128) `shouldBe` (128, True)       deepest (chain 129) `shouldBe` (129, False)  -- | The first key of the BIP 86 vectors, m/86'/0'/0'/0/0-bip86Key :: Ctx -> (PrivateKey, PublicKey)-bip86Key ctx = (PrivateKey secret True, PublicKey (derivePubKey ctx secret) True)+bip86Key :: (PrivateKey, PublicKey)+bip86Key = (PrivateKey secret True, PublicKey (derivePubKey secret) True)   where     root = fromJust (xPrvImport btc "xprv9s21ZrQH143K3GJpoapnV8SFfukcVBSfeCficPSGfubmSFDxo1kuHnLisriDvSnRRuL2Qrg5ggqHKNVpxR86QEC8w35uxmGoggxtQTPvfUu")-    secret = (derivePath ctx ("m/86'/0'/0'/0/0" :: DerivPath) root).key+    secret = (derivePath ("m/86'/0'/0'/0/0" :: DerivPath) root).key  -- | The test vectors of BIP 86: path, internal key, output key, address bip86Vectors :: [(DerivPath, Text, Text, Text)]@@ -665,8 +665,8 @@  -- | The coin of 100,000 satoshi that the first input of a transaction -- spends, with the output script given in hex-oneCoin :: Ctx -> Tx -> Text -> [(ScriptOutput, Word64, OutPoint)]-oneCoin ctx tx script = [(either error id (unmarshal ctx (hexBytes script)), 100000, (head tx.inputs).outpoint)]+oneCoin :: Tx -> Text -> [(ScriptOutput, Word64, OutPoint)]+oneCoin tx script = [(either error id (decodeSerial (hexBytes script)), 100000, (head tx.inputs).outpoint)]  txOf :: Text -> Tx txOf = either error id . S.decode . hexBytes@@ -706,9 +706,9 @@ expectRight :: Either String a -> IO a expectRight = either fail return -coinsOf :: Ctx -> KeyPathVector -> [(ScriptOutput, Word64, OutPoint)]-coinsOf ctx v =-  [ (either error id (unmarshal ctx coin.script), coin.value, input.outpoint)+coinsOf :: KeyPathVector -> [(ScriptOutput, Word64, OutPoint)]+coinsOf v =+  [ (either error id (decodeSerial coin.script), coin.value, input.outpoint)   | (input, coin) <- zip v.unsignedTx.inputs v.spent   ] @@ -727,29 +727,29 @@       leaf@MASTLeaf {} -> [BA.convert $ mastCommitment leaf]       MASTCommitment {} -> mempty -- The test vectors have complete trees -testOutputKey :: Ctx -> TestScriptPubKey -> IO ()-testOutputKey ctx testData = do-  XOnlyPubKey (taprootOutputKey ctx theOutput) @?= theOutputKey+testOutputKey :: TestScriptPubKey -> IO ()+testOutputKey testData = do+  XOnlyPubKey (taprootOutputKey theOutput) @?= theOutputKey   where     theOutput = tspkGiven testData     theOutputKey = XOnlyPubKey . spkiTweakedPubKey $ tspkIntermediary testData -testScriptOutput :: Ctx -> TestScriptPubKey -> IO ()-testScriptOutput ctx testData =-  taprootScriptOutput ctx (tspkGiven testData) @?= (spkeScriptPubKey . tspkExpected) testData+testScriptOutput :: TestScriptPubKey -> IO ()+testScriptOutput testData =+  taprootScriptOutput (tspkGiven testData) @?= (spkeScriptPubKey . tspkExpected) testData -testControlBlocks :: Ctx -> TestScriptPubKey -> IO ()-testControlBlocks ctx testData = do+testControlBlocks :: TestScriptPubKey -> IO ()+testControlBlocks testData = do   mapM_ onExamples exampleControlBlocks   mapM_ checkVerification scriptPathSpends   where     theOutput = tspkGiven testData-    theOutputKey = taprootOutputKey ctx theOutput+    theOutputKey = taprootOutputKey theOutput     exampleControlBlocks = spkeControlBlocks $ tspkExpected testData     -- The control block is the last item of the witness: the stack is     -- empty, so it comes after the script     calculatedControlBlocks =-      either error last . encodeTaprootWitness ctx . ScriptPathSpend <$> scriptPathSpends+      either error last . encodeTaprootWitness . ScriptPathSpend <$> scriptPathSpends     scriptPathSpends =       mkScriptPathSpend <$> maybe mempty getMerkleProofs theOutput.mast     mkScriptPathSpend (leafVersion, script, proof) =@@ -757,22 +757,22 @@         { annex = Nothing,           stack = mempty,           script,-          extIsOdd = odd $ keyParity ctx theOutputKey,+          extIsOdd = odd $ keyParity theOutputKey,           leafVersion,           internalKey = theOutput.internalKey,           control = proof,           opaqueScript = Nothing         }     onExamples expected = map encodeHex calculatedControlBlocks @?= map encodeHex expected-    checkVerification = assertBool "Script verifies" . verifyScriptPathData ctx theOutputKey+    checkVerification = assertBool "Script verifies" . verifyScriptPathData theOutputKey -testAddress :: Ctx -> TestScriptPubKey -> IO ()-testAddress ctx testData =+testAddress :: TestScriptPubKey -> IO ()+testAddress testData =   computedAddress @?= (Just . spkeAddress . tspkExpected) testData   where     computedAddress =-      (addrToText btc <=< outputAddress btc ctx)-        . taprootScriptOutput ctx+      (addrToText btc <=< outputAddress btc)+        . taprootScriptOutput         $ tspkGiven testData  testTreeLeaves :: TestScriptPubKey -> IO ()@@ -784,9 +784,9 @@  newtype SpkGiven = SpkGiven {unSpkGiven :: TaprootOutput} -spkGivenParseJSON :: Ctx -> Value -> Parser SpkGiven-spkGivenParseJSON ctx = withObject "SpkGiven" $ \obj -> do-  pxopk@XOnlyPubKey {} <- unmarshalValue ctx =<< obj .: "internalPubkey"+spkGivenParseJSON :: Value -> Parser SpkGiven+spkGivenParseJSON = withObject "SpkGiven" $ \obj -> do+  pxopk@XOnlyPubKey {} <- parseJSON =<< obj .: "internalPubkey"   tree <- traverse parseScriptTree =<< obj .:? "scriptTree"   return $ SpkGiven $ TaprootOutput pxopk.point tree   where@@ -810,14 +810,14 @@     spkiTweakedPubKey :: PubKey   } -spkIntermediaryParseJSON :: Ctx -> Value -> Parser SpkIntermediary-spkIntermediaryParseJSON ctx = withObject "SpkIntermediary" $ \obj ->+spkIntermediaryParseJSON :: Value -> Parser SpkIntermediary+spkIntermediaryParseJSON = withObject "SpkIntermediary" $ \obj ->   SpkIntermediary     <$> (obj .:? "leafHashes" >>= (traverse . traverse) jsonHex)     <*> (obj .: "merkleRoot" >>= traverse jsonHex)     <*> fmap       (\(XOnlyPubKey k) -> k)-      (unmarshalValue ctx =<< obj .: "tweakedPubkey")+      (parseJSON =<< obj .: "tweakedPubkey")  data SpkExpected = SpkExpected   { spkeScriptPubKey :: ScriptOutput,@@ -825,10 +825,10 @@     spkeAddress :: Text   } -spkExpectedParseJSON :: Ctx -> Value -> Parser SpkExpected-spkExpectedParseJSON ctx = withObject "SpkExpected" $ \obj ->+spkExpectedParseJSON :: Value -> Parser SpkExpected+spkExpectedParseJSON = withObject "SpkExpected" $ \obj ->   SpkExpected-    <$> (unmarshalValue ctx =<< obj .: "scriptPubKey")+    <$> (parseJSON =<< obj .: "scriptPubKey")     <*> ((traverse . traverse) jsonHex =<< obj .:? "scriptPathControlBlocks")     <*> obj .: "bip350Address" @@ -838,11 +838,11 @@     tspkExpected :: SpkExpected   } -testScriptPubKeyParseJSON :: Ctx -> Value -> Parser TestScriptPubKey-testScriptPubKeyParseJSON ctx = withObject "TestScriptPubKey" $ \obj -> do-  given <- unSpkGiven <$> (spkGivenParseJSON ctx =<< obj .: "given")-  inter <- spkIntermediaryParseJSON ctx =<< obj .: "intermediary"-  expect <- spkExpectedParseJSON ctx =<< obj .: "expected"+testScriptPubKeyParseJSON :: Value -> Parser TestScriptPubKey+testScriptPubKeyParseJSON = withObject "TestScriptPubKey" $ \obj -> do+  given <- unSpkGiven <$> (spkGivenParseJSON =<< obj .: "given")+  inter <- spkIntermediaryParseJSON =<< obj .: "intermediary"+  expect <- spkExpectedParseJSON =<< obj .: "expected"   return $ TestScriptPubKey given inter expect  -- | The keyPathSpending vector: the unsigned transaction, the outputs it@@ -898,10 +898,10 @@     testKeyPath :: KeyPathVector   } -testVectorParseJSON :: Ctx -> Value -> Parser TestVector-testVectorParseJSON ctx = withObject "TestVector" $ \obj ->+testVectorParseJSON :: Value -> Parser TestVector+testVectorParseJSON = withObject "TestVector" $ \obj ->   TestVector-    <$> (mapM (testScriptPubKeyParseJSON ctx) =<< obj .: "scriptPubKey")+    <$> (mapM testScriptPubKeyParseJSON =<< obj .: "scriptPubKey")     <*> (obj .: "keyPathSpending" >>= \case [v] -> keyPathParseJSON v; _ -> fail "one keyPathSpending vector")  jsonHex :: Text -> Parser ByteString
test/Haskoin/Transaction/VerdictSpec.hs view
@@ -1,5 +1,5 @@-{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ImportQualifiedPost #-} {-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-}@@ -31,8 +31,8 @@ secret n = fromJust (secKey (B.replicate 31 0 <> B.singleton n))  -- | The compressed bytes of the public key of a secret.-pubBytes :: Ctx -> SecKey -> ByteString-pubBytes ctx = exportPubKey ctx True . derivePubKey ctx+pubBytes :: SecKey -> ByteString+pubBytes = exportPubKey True . derivePubKey  coin :: OutPoint coin = OutPoint "0101010101010101010101010101010101010101010101010101010101010101" 0@@ -56,23 +56,23 @@ tampered :: Tx -> Tx tampered tx = tx {outputs = [o {value = o.value - 1} | o <- tx.outputs]} -ecdsa :: Ctx -> SecKey -> Word8 -> Either String Hash256 -> ByteString-ecdsa ctx k hashType = either error (\h -> exportSig ctx (signHash ctx k h) <> B.singleton hashType)+ecdsa :: SecKey -> Word8 -> Either String Hash256 -> ByteString+ecdsa k hashType = either error (\h -> exportSig (signHash k h) <> B.singleton hashType)  -- | A Schnorr signature of Bitcoin Cash, made the plain way: this is a -- test, and the nonce is not a secret worth keeping.-cashSchnorr :: Ctx -> SecKey -> Hash256 -> ByteString-cashSchnorr ctx k h = head (mapMaybe attempt [1 ..])+cashSchnorr :: SecKey -> Hash256 -> ByteString+cashSchnorr k h = head (mapMaybe attempt [1 ..])   where     n = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 :: Integer     p = 2 ^ (256 :: Int) - 2 ^ (32 :: Int) - 977 :: Integer     word256 i = let b = integerToBS i in B.replicate (32 - B.length b) 0 <> b     d = bsToInteger k.get     attempt nonce = do-      r <- derivePubKey ctx <$> secKey (word256 nonce)-      let (x, y) = B.splitAt 32 (B.drop 1 (exportPubKey ctx False r))+      r <- derivePubKey <$> secKey (word256 nonce)+      let (x, y) = B.splitAt 32 (B.drop 1 (exportPubKey False r))           square = powMod (bsToInteger y) ((p - 1) `div` 2) == 1-          e = bsToInteger (runPutS (serialize (sha256 (x <> pubBytes ctx k <> runPutS (serialize h))))) `mod` n+          e = bsToInteger (runPutS (serialize (sha256 (x <> pubBytes k <> runPutS (serialize h))))) `mod` n       if square then Just (x <> word256 ((nonce + e * d) `mod` n)) else Nothing     powMod _ 0 = 1 :: Integer     powMod b i@@ -80,48 +80,48 @@       | otherwise = b * powMod b (i - 1) `mod` p  spec :: Spec-spec = prepareContext $ \ctx -> do+spec = do   let k = secret 7-      pub = pubBytes ctx k+      pub = pubBytes k       h160 = addressHash pub       value = 100000 :: Word64-      prev so = Just (TxOut value (marshal ctx so))-      pkhScript = either error id (encodeOutput ctx (PayPKHash h160))+      prev so = Just (TxOut value (encodeSerial so))+      pkhScript = either error id (encodeOutput (PayPKHash h160))       three net tx prevOut = do-        judgeInputs net ctx tx [prevOut] `shouldBe` [InputVerified]-        judgeInputs net ctx (tampered tx) [prevOut] `shouldBe` [InputForged]-        judgeInputs net ctx tx [Nothing] `shouldBe` [InputUndecided]+        judgeInputs net tx [prevOut] `shouldBe` [InputVerified]+        judgeInputs net (tampered tx) [prevOut] `shouldBe` [InputForged]+        judgeInputs net tx [Nothing] `shouldBe` [InputUndecided]    describe "judgeInputs on coins of one key" $ do     it "tells a key hash input that verifies from a forged one, and from one it cannot see" $ do       let unsigned = spending "" []-          sig = ecdsa ctx k 0x01 (txSigHash btc unsigned pkhScript value 0 sigHashAll)+          sig = ecdsa k 0x01 (txSigHash btc unsigned pkhScript value 0 sigHashAll)       three btc (spending (pushing [sig, pub]) []) (prev (PayPKHash h160))     it "says forged of another key than the one the coin names" $ do       let other = secret 8           unsigned = spending "" []-          sig = ecdsa ctx other 0x01 (txSigHash btc unsigned pkhScript value 0 sigHashAll)-      judgeInputs btc ctx (spending (pushing [sig, pubBytes ctx other]) []) [prev (PayPKHash h160)]+          sig = ecdsa other 0x01 (txSigHash btc unsigned pkhScript value 0 sigHashAll)+      judgeInputs btc (spending (pushing [sig, pubBytes other]) []) [prev (PayPKHash h160)]         `shouldBe` [InputForged]     it "does the same for a witness key hash, plain and nested" $ do       let unsigned = spending "" []-          sig = ecdsa ctx k 0x01 (txSigHashForkId btc unsigned pkhScript value 0 sigHashAll)-          program = marshal ctx (PayWitnessPKHash h160)+          sig = ecdsa k 0x01 (txSigHashForkId btc unsigned pkhScript value 0 sigHashAll)+          program = encodeSerial (PayWitnessPKHash h160)       three btc (spending "" [sig, pub]) (prev (PayWitnessPKHash h160))       three btc (spending (pushing [program]) [sig, pub]) (prev (PayScriptHash (addressHash program)))     it "does the same for a Taproot key" $ do       let outKey = B.drop 1 pub-          out = TxOut value (marshal ctx (PayWitness 1 outKey))+          out = TxOut value (encodeSerial (PayWitness 1 outKey))           -- the secret of the key with an even y, whichever of the two it is-          signed = head (rights [signTaprootInput ctx (spending "" []) [out] 0 sigHashDefault s | s <- [k, negated]])-          negated = fromJust (secKey . (.get) =<< tweakNegate ctx =<< tweak k.get)+          signed = head (rights [signTaprootInput (spending "" []) [out] 0 sigHashDefault s | s <- [k, negated]])+          negated = fromJust (secKey . (.get) =<< tweakNegate =<< tweak k.get)       three btc signed (Just out)     it "leaves a hash type other than all, and a script, to a node" $ do       let unsigned = spending "" []-          none = ecdsa ctx k 0x02 (txSigHash btc unsigned pkhScript value 0 sigHashNone)-      judgeInputs btc ctx (tampered (spending (pushing [none, pub]) [])) [prev (PayPKHash h160)]+          none = ecdsa k 0x02 (txSigHash btc unsigned pkhScript value 0 sigHashNone)+      judgeInputs btc (tampered (spending (pushing [none, pub]) [])) [prev (PayPKHash h160)]         `shouldBe` [InputVerified]-      judgeInputs btc ctx (spending (pushing ["anything"]) []) [prev (PayScriptHash h160)]+      judgeInputs btc (spending (pushing ["anything"]) []) [prev (PayScriptHash h160)]         `shouldBe` [InputUndecided]    describe "judgeInputs on Bitcoin Cash" $ do@@ -129,17 +129,17 @@         digest prefix = txSigHashCashToken bch unsigned prefix pkhScript value 0 (setForkIdFlag sigHashAll)         tokens = B.singleton 0xef <> B.replicate 32 0xaa <> B.pack [0x10, 0xfd, 0xe8, 0x03]     it "reads a Schnorr signature" $ do-      let sig = cashSchnorr ctx k (either error id (digest "")) <> B.singleton 0x41+      let sig = cashSchnorr k (either error id (digest "")) <> B.singleton 0x41       B.length sig `shouldBe` 65       three bch (spending (pushing [sig, pub]) []) (prev (PayPKHash h160))     it "reads an ECDSA signature" $-      three bch (spending (pushing [ecdsa ctx k 0x41 (digest ""), pub]) []) (prev (PayPKHash h160))+      three bch (spending (pushing [ecdsa k 0x41 (digest ""), pub]) []) (prev (PayPKHash h160))     it "reads a coin that holds tokens, whose digest covers them" $ do-      let withTokens = Just (TxOut value (tokens <> marshal ctx (PayPKHash h160)))-      three bch (spending (pushing [ecdsa ctx k 0x41 (digest tokens), pub]) []) withTokens-      three bch (spending (pushing [cashSchnorr ctx k (either error id (digest tokens)) <> "\x41", pub]) []) withTokens+      let withTokens = Just (TxOut value (tokens <> encodeSerial (PayPKHash h160)))+      three bch (spending (pushing [ecdsa k 0x41 (digest tokens), pub]) []) withTokens+      three bch (spending (pushing [cashSchnorr k (either error id (digest tokens)) <> "\x41", pub]) []) withTokens       -- signed as if the coin held none: not a signature of this coin-      judgeInputs bch ctx (spending (pushing [ecdsa ctx k 0x41 (digest ""), pub]) []) [withTokens]+      judgeInputs bch (spending (pushing [ecdsa k 0x41 (digest ""), pub]) []) [withTokens]         `shouldBe` [InputForged]    describe "judgeInputs on what Bitcoin Cash Node signed" $ do@@ -151,47 +151,47 @@         genesis =           parse             "0200000001f28fd1cdb4293ae6bb76e580c5a3469fb926690471f3ffb798ef0a\-          \cda9886525000000006441e31c237fe3a1a45f6c32c779c78025f29bd735fa44\-          \d18c182bc1c08fbbcab25f08cbd8c1937dccd38acf37ef2bf8907e75029d622c\-          \5a9f6f5161ffe534fa2775412103bcacac8993931b1f0867991841a140425906\-          \839d26c4c906a737a4f2f29dd79effffffff01c0aff629010000003eeff28fd1\-          \cdb4293ae6bb76e580c5a3469fb926690471f3ffb798ef0acda988652510fde8\-          \0376a9145dd6bc82b5a42053b8f7802e68d296ac3578537a88ac00000000"+            \cda9886525000000006441e31c237fe3a1a45f6c32c779c78025f29bd735fa44\+            \d18c182bc1c08fbbcab25f08cbd8c1937dccd38acf37ef2bf8907e75029d622c\+            \5a9f6f5161ffe534fa2775412103bcacac8993931b1f0867991841a140425906\+            \839d26c4c906a737a4f2f29dd79effffffff01c0aff629010000003eeff28fd1\+            \cdb4293ae6bb76e580c5a3469fb926690471f3ffb798ef0acda988652510fde8\+            \0376a9145dd6bc82b5a42053b8f7802e68d296ac3578537a88ac00000000"         spend =           parse             "0200000001db5f2a09c11a2aaceb0d9bfa755006380257d48dab94a73cfd4d69\-          \c2e2d122a6000000006441f52f838cf46e41b8c630334d2b6edefdb49f67fd19\-          \45ee864321da50b1fa652b6b2db4b517110ee5598cbf5193eac763a56d59bfe2\-          \e20d8f3fb9af4b08bfe340412103bcacac8993931b1f0867991841a140425906\-          \839d26c4c906a737a4f2f29dd79effffffff01806de729010000003eeff28fd1\-          \cdb4293ae6bb76e580c5a3469fb926690471f3ffb798ef0acda988652510fde8\-          \0376a9145dd6bc82b5a42053b8f7802e68d296ac3578537a88ac00000000"+            \c2e2d122a6000000006441f52f838cf46e41b8c630334d2b6edefdb49f67fd19\+            \45ee864321da50b1fa652b6b2db4b517110ee5598cbf5193eac763a56d59bfe2\+            \e20d8f3fb9af4b08bfe340412103bcacac8993931b1f0867991841a140425906\+            \839d26c4c906a737a4f2f29dd79effffffff01806de729010000003eeff28fd1\+            \cdb4293ae6bb76e580c5a3469fb926690471f3ffb798ef0acda988652510fde8\+            \0376a9145dd6bc82b5a42053b8f7802e68d296ac3578537a88ac00000000"         coinbase = TxOut 5000000000 (fromJust (decodeHex "76a9145dd6bc82b5a42053b8f7802e68d296ac3578537a88ac"))     it "verifies its Schnorr signature of a coin without tokens" $ do-      judgeInputs bchRegTest ctx genesis [Just coinbase] `shouldBe` [InputVerified]-      judgeInputs bchRegTest ctx (tampered genesis) [Just coinbase] `shouldBe` [InputForged]+      judgeInputs bchRegTest genesis [Just coinbase] `shouldBe` [InputVerified]+      judgeInputs bchRegTest (tampered genesis) [Just coinbase] `shouldBe` [InputForged]     it "verifies its Schnorr signature of a coin that holds tokens" $ do       let held = head genesis.outputs       fmap fst (splitTokenPrefix held.script) `shouldSatisfy` maybe False (not . B.null)-      judgeInputs bchRegTest ctx spend [Just held] `shouldBe` [InputVerified]-      judgeInputs bchRegTest ctx (tampered spend) [Just held] `shouldBe` [InputForged]+      judgeInputs bchRegTest spend [Just held] `shouldBe` [InputVerified]+      judgeInputs bchRegTest (tampered spend) [Just held] `shouldBe` [InputForged]       -- the same coin without its tokens is another coin       let bare = held {script = maybe held.script snd (splitTokenPrefix held.script)} :: TxOut-      judgeInputs bchRegTest ctx spend [Just bare] `shouldBe` [InputForged]+      judgeInputs bchRegTest spend [Just bare] `shouldBe` [InputForged]    describe "judgeInputs on a multisig of Bitcoin Cash signed with Schnorr signatures" $ do     let secrets = map secret [11, 12, 13]-        keys = map (wrapPubKey True . derivePubKey ctx) secrets+        keys = map (wrapPubKey True . derivePubKey) secrets         twoOfThree = PayMulSig keys 2-        redeem = marshal ctx twoOfThree+        redeem = encodeSerial twoOfThree         locked = prev (PayScriptHash (addressHash redeem))-        code = either error id (encodeOutput ctx twoOfThree)+        code = either error id (encodeOutput twoOfThree)         digest = either error id (txSigHashForkId bch (spending "" []) code value 0 (setForkIdFlag sigHashAll))-        sign s = cashSchnorr ctx s digest <> B.singleton 0x41+        sign s = cashSchnorr s digest <> B.singleton 0x41         -- the field of bits is a small number, pushed by its own opcode         spendWith bits sigs =           spending (runPutS (serialize (Script ([bits] <> map opPushData (sigs <> [redeem]))))) []-        verdict tx = judgeInputs bch ctx tx [locked]+        verdict tx = judgeInputs bch tx [locked]     it "verifies the signatures of the keys that the bits name, in the order of the keys" $ do       verdict (spendWith OP_5 [sign (head secrets), sign (secrets !! 2)]) `shouldBe` [InputVerified]       verdict (spendWith OP_3 [sign (head secrets), sign (secrets !! 1)]) `shouldBe` [InputVerified]@@ -206,24 +206,24 @@       verdict (spendWith OP_5 (reverse sigs)) `shouldBe` [InputUndecided]     it "does not verify what was not signed, nor an ECDSA signature among them" $ do       verdict (tampered (spendWith OP_5 [sign (head secrets), sign (secrets !! 2)])) `shouldBe` [InputUndecided]-      let ecdsaSig = ecdsa ctx (head secrets) 0x41 (Right digest)+      let ecdsaSig = ecdsa (head secrets) 0x41 (Right digest)       verdict (spendWith OP_5 [ecdsaSig, sign (secrets !! 2)]) `shouldBe` [InputUndecided]    describe "verifyStdInput on a multisig of Taproot" $ do     let secrets = map secret [11, 12, 13]-        xOnly = B.drop 1 . pubBytes ctx+        xOnly = B.drop 1 . pubBytes         leaf =           Script $             [opPushData (xOnly (head secrets)), OP_CHECKSIG]               <> concat [[opPushData (xOnly s), OP_CHECKSIGADD] | s <- drop 1 secrets]               <> [OP_2, OP_NUMEQUAL]-        internal = derivePubKey ctx (secret 14)+        internal = derivePubKey (secret 14)         tree = TaprootOutput {internalKey = internal, mast = Just (MASTLeaf tapscriptLeafVersion leaf)}-        out = TxOut value (marshal ctx (taprootScriptOutput ctx tree))+        out = TxOut value (encodeSerial (taprootScriptOutput tree))         unsigned = spending "" []         leafOf = Just (leafHash tapscriptLeafVersion leaf, 0xffffffff)         digest = either error id (taprootSigHash unsigned [out] 0 sigHashDefault Nothing leafOf)-        sign s = (signSchnorr ctx s (hashToMsg digest)).get+        sign s = (signSchnorr s (hashToMsg digest)).get         spendWith items =           let path =                 ScriptPathSpend@@ -231,19 +231,19 @@                     { annex = Nothing,                       stack = items,                       script = leaf,-                      extIsOdd = odd (keyParity ctx (taprootOutputKey ctx tree)),+                      extIsOdd = odd (keyParity (taprootOutputKey tree)),                       leafVersion = tapscriptLeafVersion,                       internalKey = internal,                       control = [],                       opaqueScript = Nothing                     }-           in unsigned {witness = [either error id (encodeTaprootWitness ctx path)]} :: Tx-        verdict tx = judgeInputs btc ctx tx [Just out]+           in unsigned {witness = [either error id (encodeTaprootWitness path)]} :: Tx+        verdict tx = judgeInputs btc tx [Just out]     it "verifies two signatures of three keys, with an item for each key, the last first" $ do       verdict (spendWith [sign (secrets !! 2), "", sign (head secrets)]) `shouldBe` [InputVerified]       verdict (spendWith ["", sign (secrets !! 1), sign (head secrets)]) `shouldBe` [InputVerified]       let lastTwo = spendWith [sign (secrets !! 2), sign (secrets !! 1), ""]-      verifyStdInput btc ctx lastTwo [(taprootScriptOutput ctx tree, value, coin)] 0 `shouldBe` True+      verifyStdInput btc lastTwo [(taprootScriptOutput tree, value, coin)] 0 `shouldBe` True     it "does not verify one signature, three, a signature of another key, or one of other outputs" $ do       verdict (spendWith ["", "", sign (head secrets)]) `shouldBe` [InputUndecided]       verdict (spendWith [sign (secrets !! 2), sign (secrets !! 1), sign (head secrets)]) `shouldBe` [InputUndecided]@@ -276,13 +276,13 @@    describe "judgeInputs on signed transactions" $     prop "never says forged of an input that verifies" $-      forAll (elements [btc, bch] >>= \net -> (,) net <$> arbitrarySigningData net ctx) $ \(net, (tx, sigis, keys)) ->-        case signTx net ctx tx sigis (map (.key) keys) of+      forAll (elements [btc, bch] >>= \net -> (,) net <$> arbitrarySigningData net) $ \(net, (tx, sigis, keys)) ->+        case signTx net tx sigis (map (.key) keys) of           Left _ -> property True           Right signed ->-            let prevOf i = lookup i.outpoint [(s.outpoint, TxOut s.value (marshal ctx s.script)) | s <- sigis]-                verdicts = judgeInputs net ctx signed (map prevOf signed.inputs)+            let prevOf i = lookup i.outpoint [(s.outpoint, TxOut s.value (encodeSerial s.script)) | s <- sigis]+                verdicts = judgeInputs net signed (map prevOf signed.inputs)                 coins = [(s.script, s.value, s.outpoint) | s <- sigis]              in counterexample (show verdicts) $                   InputForged `notElem` verdicts-                    && (not (verifyStdTx net ctx signed coins) || all (== InputVerified) verdicts)+                    && (not (verifyStdTx net signed coins) || all (== InputVerified) verdicts)
test/Haskoin/TransactionSpec.hs view
@@ -41,38 +41,38 @@ import Test.QuickCheck import Text.Read (readMaybe) -identityTests :: Ctx -> IdentityTests-identityTests ctx =+identityTests :: IdentityTests+identityTests =   def     { readTests =         [ ReadBox arbitraryTxHash,-          ReadBox $ flip arbitraryTx ctx =<< arbitraryNetwork,-          ReadBox $ flip arbitraryTxIn ctx =<< arbitraryNetwork,-          ReadBox $ flip arbitraryTxOut ctx =<< arbitraryNetwork,+          ReadBox $ arbitraryTx =<< arbitraryNetwork,+          ReadBox $ arbitraryTxIn =<< arbitraryNetwork,+          ReadBox $ arbitraryTxOut =<< arbitraryNetwork,           ReadBox arbitraryOutPoint         ],       jsonTests =         [ JsonBox arbitraryTxHash,-          JsonBox $ flip arbitraryTx ctx =<< arbitraryNetwork,-          JsonBox $ flip arbitraryWitnessTx ctx =<< arbitraryNetwork,-          JsonBox $ flip arbitraryLegacyTx ctx =<< arbitraryNetwork,-          JsonBox $ flip arbitraryTxIn ctx =<< arbitraryNetwork,-          JsonBox $ flip arbitraryTxOut ctx =<< arbitraryNetwork,+          JsonBox $ arbitraryTx =<< arbitraryNetwork,+          JsonBox $ arbitraryWitnessTx =<< arbitraryNetwork,+          JsonBox $ arbitraryLegacyTx =<< arbitraryNetwork,+          JsonBox $ arbitraryTxIn =<< arbitraryNetwork,+          JsonBox $ arbitraryTxOut =<< arbitraryNetwork,           JsonBox arbitraryOutPoint         ],       serialTests =-        [ SerialBox $ flip arbitraryTx ctx =<< arbitraryNetwork,-          SerialBox $ flip arbitraryWitnessTx ctx =<< arbitraryNetwork,-          SerialBox $ flip arbitraryLegacyTx ctx =<< arbitraryNetwork,-          SerialBox $ flip arbitraryTxIn ctx =<< arbitraryNetwork,-          SerialBox $ flip arbitraryTxOut ctx =<< arbitraryNetwork,+        [ SerialBox $ arbitraryTx =<< arbitraryNetwork,+          SerialBox $ arbitraryWitnessTx =<< arbitraryNetwork,+          SerialBox $ arbitraryLegacyTx =<< arbitraryNetwork,+          SerialBox $ arbitraryTxIn =<< arbitraryNetwork,+          SerialBox $ arbitraryTxOut =<< arbitraryNetwork,           SerialBox arbitraryOutPoint         ]     }  spec :: Spec-spec = prepareContext $ \ctx -> do-  testIdentity $ identityTests ctx+spec = do+  testIdentity $ identityTests   describe "Transaction properties" $ do     prop "decode and encode txid" $       forAll arbitraryTxHash $@@ -82,48 +82,50 @@         \h -> fromString (cs $ txHashToHex h) == h     prop "building address tx" $       forAll arbitraryNetAddress $ \(net, addr) ->-        forAll (arbitrarySatoshi net) $ testBuildAddrTx net ctx addr+        forAll (arbitrarySatoshi net) $ testBuildAddrTx net addr     prop "the size guess is at least the virtual size of a signed legacy transaction, with little slack" $       forAll arbitraryNetwork $ \net ->-        forAll (arbitraryAddrOnlyTxFull net ctx) (testGuessSize net ctx)+        forAll (arbitraryAddrOnlyTxFull net) (testGuessSize net)     prop "the weight guess is at least the weight of a signed transaction whose inputs have a kind" $-      forAll arbitraryNetwork $ \net -> testGuessWeight net ctx False+      forAll arbitraryNetwork $+        \net -> testGuessWeight net False     prop "the weight guess is at least the weight of a signed transaction with its SegWit inputs nested" $-      forAll arbitraryNetwork $ \net -> testGuessWeight net ctx True+      forAll arbitraryNetwork $+        \net -> testGuessWeight net True     prop "choose coins" $       forAll arbitraryNetwork $ \net ->         forAll (listOf (arbitrarySatoshi net)) $ \coins ->           forAll (listOf arbitraryOutputKind) (testChooseCoins coins)     prop "sign and validate transaction" $       forAll arbitraryNetwork $ \net ->-        forAll (arbitrarySigningData net ctx) (testDetSignTx net ctx)+        forAll (arbitrarySigningData net) (testDetSignTx net)     prop "sign and validate (nested) transaction" $       forAll arbitraryNetwork $ \net ->-        forAll (arbitrarySigningData net ctx) (testDetSignNestedTx net ctx)+        forAll (arbitrarySigningData net) (testDetSignNestedTx net)     prop "merge partially signed transactions" $       forAll arbitraryNetwork $ \net ->-        property $ forAll (arbitraryPartialTxs net ctx) (testMergeTx net ctx)+        property $ forAll (arbitraryPartialTxs net) (testMergeTx net)     prop "nosigTxHash does not change when a transaction is signed, whether in the input scripts or in the witness" $       forAll arbitraryNetwork $ \net ->-        forAll (arbitrarySigningData net ctx) $ \(tx, sigis, prv) ->-          nosigTxHash (either error id (signTx net ctx tx sigis (map (.key) prv))) === nosigTxHash tx+        forAll (arbitrarySigningData net) $ \(tx, sigis, prv) ->+          nosigTxHash (either error id (signTx net tx sigis (map (.key) prv))) === nosigTxHash tx   describe "Transaction vectors" $ do     it "compute txid from tx" $ mapM_ testTxidVector txidVectors     it "build pkhash transaction (generated from bitcoind)" $-      mapM_ (testPKHashVector ctx) pkHashVectors+      mapM_ testPKHashVector pkHashVectors   idsSpec-  bytesSpec ctx-  sizeSpec ctx+  bytesSpec+  sizeSpec   coinSelectionSpec-  buildSpec ctx-  verificationSpec ctx-  coreSignedSpec ctx-  consensusSpec ctx-  thiefSpec ctx-  signerSpec ctx-  mergeSpec ctx-  taprootSigningSpec ctx-  segwitSpec ctx+  buildSpec+  verificationSpec+  coreSignedSpec+  consensusSpec+  thiefSpec+  signerSpec+  mergeSpec+  taprootSigningSpec+  segwitSpec   genesisSpec  -- Txid Vectors@@ -192,14 +194,14 @@  -- Build address transactions vectors generated from bitcoin-core raw tx API -testPKHashVector :: Ctx -> ([(Text, Word32)], [(Text, Word64)], Text) -> Assertion-testPKHashVector ctx (is, os, res) =+testPKHashVector :: ([(Text, Word32)], [(Text, Word64)], Text) -> Assertion+testPKHashVector (is, os, res) =   assertEqual     "Build PKHash Tx"     (Right res)     (encodeHex . runPutS . serialize <$> txE)   where-    txE = buildAddrTx btc ctx (map f is) os+    txE = buildAddrTx btc (map f is) os     f (tid, ix) = OutPoint (fromJust $ hexToTxHash tid) ix  pkHashVectors :: [([(Text, Word32)], [(Text, Word64)], Text)]@@ -253,26 +255,26 @@  -- Transaction Properties -- -testBuildAddrTx :: Network -> Ctx -> Address -> TestCoin -> IO ()-testBuildAddrTx net ctx a coin+testBuildAddrTx :: Network -> Address -> TestCoin -> IO ()+testBuildAddrTx net a coin   | isPubKeyAddress a = (PayPKHash <$> addressHash160 a) `shouldBe` Just out   | isScriptAddress a = (PayScriptHash <$> addressHash160 a) `shouldBe` Just out   | otherwise = discard   where     out = either error id $ do-      tx <- buildAddrTx net ctx [] [(fromJust (addrToText net a), coin.getTestCoin)]-      unmarshal ctx (head tx.outputs).script+      tx <- buildAddrTx net [] [(fromJust (addrToText net a), coin.getTestCoin)]+      decodeSerial (head tx.outputs).script  -- The guess is an upper bound on the virtual size that counts 72 bytes -- per signature. A signature with a short r or s is 1 or 2 bytes less.-testGuessSize :: Network -> Ctx -> Tx -> Bool-testGuessSize net ctx tx =+testGuessSize :: Network -> Tx -> Bool+testGuessSize net tx =   guess >= size && guess <= size + 2 * signatures   where     guess = guessTxSize (map inputKind ins) (map outputKind outs)     size = txVirtualSize tx-    ins = map (either error id . unmarshal (net, ctx) . (.script)) tx.inputs-    outs = map (either error id . unmarshal ctx . (.script)) tx.outputs+    ins = map (either error id . unmarshal net . (.script)) tx.inputs+    outs = map (either error id . decodeSerial . (.script)) tx.outputs     inputKind (ScriptHashInput _ (PayMulSig keys r)) = InputMulSig r (length keys)     inputKind _ = InputPKHash     outputKind o@@ -285,17 +287,17 @@ -- The guess is an upper bound on the weight of the transaction once signed: -- by signTx, or by signNestedWitnessTx with its SegWit inputs nested. Only -- signing data whose inputs all have a kind is generated.-testGuessWeight :: Network -> Ctx -> Bool -> Property-testGuessWeight net ctx nested =-  forAll (arbitrarySigningData net ctx `suchThat` allKnown) $ \(tx, sigis, keys) ->-    let signed = either error id (sign net ctx tx sigis (map (.key) keys))-        kinds = mapMaybe (sigInputKind ctx nested keys) sigis-        guess = guessTxWeight kinds (map (txOutKind ctx) tx.outputs)+testGuessWeight :: Network -> Bool -> Property+testGuessWeight net nested =+  forAll (arbitrarySigningData net `suchThat` allKnown) $ \(tx, sigis, keys) ->+    let signed = either error id (sign net tx sigis (map (.key) keys))+        kinds = mapMaybe (sigInputKind nested keys) sigis+        guess = guessTxWeight kinds (map txOutKind tx.outputs)      in counterexample ("weight " <> show (txWeight signed) <> ", guess " <> show guess) $           txWeight signed <= guess   where     sign = if nested then signNestedWitnessTx else signTx-    allKnown (_, sigis, keys) = all (isJust . sigInputKind ctx nested keys) sigis+    allKnown (_, sigis, keys) = all (isJust . sigInputKind nested keys) sigis  -- The kind of input a SigInput is signed as, when the estimator has one. -- The key of a public key hash is found among the signing keys, to tell@@ -304,8 +306,8 @@ -- pay-to-witness-script-hash of a single key, multisig with an uncompressed -- key, and pay-to-witness-public-key-hash with an uncompressed key, which -- the estimator counts as compressed.-sigInputKind :: Ctx -> Bool -> [PrivateKey] -> SigInput -> Maybe InputKind-sigInputKind ctx nested keys si = case (si.script, si.redeem) of+sigInputKind :: Bool -> [PrivateKey] -> SigInput -> Maybe InputKind+sigInputKind nested keys si = case (si.script, si.redeem) of   (PayPK _, Nothing) -> Just InputPK   (PayPKHash h, Nothing) -> do     k <- keyOfHash h@@ -320,15 +322,15 @@   (PayWitness 1 program, Nothing) | B.length program == 32 -> Just InputTaproot   _ -> Nothing   where-    keyOfHash h = find (\k -> addressHash160 (pubKeyAddr ctx (derivePublicKey ctx k)) == Just h) keys+    keyOfHash h = find (\k -> addressHash160 (pubKeyAddr (derivePublicKey k)) == Just h) keys     compressedMultisig kind ps m = do       guard (all (.compress) ps)       Just (kind m (length ps))  -- The kind of an output, from its script. A script of no named kind is -- 'OutputScript' with its size.-txOutKind :: Ctx -> TxOut -> OutputKind-txOutKind ctx out = case unmarshal ctx out.script of+txOutKind :: TxOut -> OutputKind+txOutKind out = case decodeSerial out.script of   Right (PayPKHash _) -> OutputPKHash   Right (PayScriptHash _) -> OutputScriptHash   Right (PayScript32Hash _) -> OutputScript32Hash@@ -359,38 +361,38 @@  {- Signing Transactions -} -testDetSignTx :: Network -> Ctx -> (Tx, [SigInput], [PrivateKey]) -> Bool-testDetSignTx net ctx (tx, sigis, prv) =+testDetSignTx :: Network -> (Tx, [SigInput], [PrivateKey]) -> Bool+testDetSignTx net (tx, sigis, prv) =   not verify1 && not verify2 && verify3   where-    verify1 = verifyStdTx net ctx tx verData-    verify2 = verifyStdTx net ctx txSigP verData-    verify3 = verifyStdTx net ctx txSigC verData-    txSigP = either error id $ signTx net ctx tx sigis (map (.key) (tail prv))-    txSigC = either error id $ signTx net ctx txSigP sigis [(head prv).key]+    verify1 = verifyStdTx net tx verData+    verify2 = verifyStdTx net txSigP verData+    verify3 = verifyStdTx net txSigC verData+    txSigP = either error id $ signTx net tx sigis (map (.key) (tail prv))+    txSigC = either error id $ signTx net txSigP sigis [(head prv).key]     sigData SigInput {..} = (script, value, outpoint)     verData = map sigData sigis -testDetSignNestedTx :: Network -> Ctx -> (Tx, [SigInput], [PrivateKey]) -> Bool-testDetSignNestedTx net ctx (tx, sigis, prv) =+testDetSignNestedTx :: Network -> (Tx, [SigInput], [PrivateKey]) -> Bool+testDetSignNestedTx net (tx, sigis, prv) =   not verify1 && not verify2 && verify3   where-    verify1 = verifyStdTx net ctx tx verData-    verify2 = verifyStdTx net ctx txSigP verData-    verify3 = verifyStdTx net ctx txSigC verData+    verify1 = verifyStdTx net tx verData+    verify2 = verifyStdTx net txSigP verData+    verify3 = verifyStdTx net txSigC verData     txSigP =       either error id $-        signNestedWitnessTx net ctx tx sigis ((.key) <$> tail prv)+        signNestedWitnessTx net tx sigis ((.key) <$> tail prv)     txSigC =       either error id $-        signNestedWitnessTx net ctx txSigP sigis [(head prv).key]+        signNestedWitnessTx net txSigP sigis [(head prv).key]     verData = handleSegwit <$> sigis     handleSegwit (SigInput s v o _ _)-      | isSegwit s = (either error id (toP2SH =<< encodeOutput ctx s), v, o)+      | isSegwit s = (either error id (toP2SH =<< encodeOutput s), v, o)       | otherwise = (s, v, o) -testMergeTx :: Network -> Ctx -> ([Tx], [(ScriptOutput, Word64, OutPoint, Int, Int)]) -> Bool-testMergeTx net ctx (txs, os) =+testMergeTx :: Network -> ([Tx], [(ScriptOutput, Word64, OutPoint, Int, Int)]) -> Bool+testMergeTx net (txs, os) =   and     [ isRight mergeRes,       length mergedTx.inputs == length os,@@ -402,14 +404,14 @@     ]   where     outs = map (\(so, val, op, _, _) -> (so, val, op)) os-    mergeRes = mergeTxs net ctx txs outs+    mergeRes = mergeTxs net txs outs     mergedTx = fromRight (error "Could not merge") mergeRes-    isValid = verifyStdTx net ctx mergedTx outs+    isValid = verifyStdTx net mergedTx outs     enoughSigs = all (\(m, c) -> c >= m) sigMap     sigFun (_, _, _, m, _) inp = (m, sigCnt inp)     sigMap = zipWith sigFun os mergedTx.inputs     sigCnt inp =-      case unmarshal (net, ctx) inp.script of+      case unmarshal net inp.script of         Right (RegularInput (SpendMulSig sigs)) -> length sigs         Right (ScriptHashInput (SpendMulSig sigs) _) -> length sigs         _ -> error "Invalid input script type"@@ -434,20 +436,20 @@  -- | The key pair whose secret key is the number given, in compressed form. -- Tests use these fixed keys, so that a failure can be run again.-fixedKey :: Ctx -> Word8 -> (PrivateKey, PublicKey)-fixedKey ctx n = (k, derivePublicKey ctx k)+fixedKey :: Word8 -> (PrivateKey, PublicKey)+fixedKey n = (k, derivePublicKey k)   where     k = wrapSecKey True (fromJust (secKey (B.replicate 31 0 <> B.singleton n)))  -- | The same key pair with the public key in uncompressed form-fixedKeyU :: Ctx -> Word8 -> (PrivateKey, PublicKey)-fixedKeyU ctx n = (k, derivePublicKey ctx k)+fixedKeyU :: Word8 -> (PrivateKey, PublicKey)+fixedKeyU n = (k, derivePublicKey k)   where-    k = wrapSecKey False (fst (fixedKey ctx n)).key+    k = wrapSecKey False (fst (fixedKey n)).key  -- | HASH160 of a public key as it is serialized-keyHash :: Ctx -> PublicKey -> Hash160-keyHash ctx = addressHash . marshal ctx+keyHash :: PublicKey -> Hash160+keyHash = addressHash . encodeSerial  -- | A coin to spend: an output of the genesis coinbase transaction id coinAt :: Word32 -> OutPoint@@ -506,8 +508,8 @@  {- Bytes -} -bytesSpec :: Ctx -> Spec-bytesSpec ctx =+bytesSpec :: Spec+bytesSpec =   describe "Transaction bytes" $ do     -- The bytes of the first pkhash vector, with the input count written     -- as 0xffffffffffffffff, which wraps around to -1 as an Int@@ -617,8 +619,8 @@  {- Sizes and fees -} -sizeSpec :: Ctx -> Spec-sizeSpec ctx =+sizeSpec :: Spec+sizeSpec =   describe "Size and fee estimation" $ do     it "counts the bytes of each kind of input, without and with witness" $ do       -- outpoint 36, sequence 4, script length 1, signature push 73@@ -739,14 +741,14 @@       dustThreshold (OutputScript 37) `shouldBe` 582      it "is at least the virtual size of a signed P2WPKH spend, and of a Taproot key path spend" $ do-      let (k, p) = fixedKey ctx 1-          h = fromJust (addressHash160 (pubKeyAddr ctx p))+      let (k, p) = fixedKey 1+          h = fromJust (addressHash160 (pubKeyAddr p))           op = OutPoint (fromJust (hexToTxHash genesisTxId)) 0-          witnessTx = buildTx ctx [op] [(PayWitnessPKHash h, 90000)]-          taprootOutput = taprootScriptOutput ctx (TaprootOutput p.point Nothing)-          taprootTx = buildTx ctx [op] [(taprootOutput, 90000)]-      signedWitness <- either fail return (signTx btc ctx witnessTx [SigInput (PayWitnessPKHash h) 100000 op sigHashAll Nothing] [k.key])-      signedTaproot <- either fail return (signTx btc ctx taprootTx [SigInput taprootOutput 100000 op sigHashDefault Nothing] [k.key])+          witnessTx = buildTx [op] [(PayWitnessPKHash h, 90000)]+          taprootOutput = taprootScriptOutput (TaprootOutput p.point Nothing)+          taprootTx = buildTx [op] [(taprootOutput, 90000)]+      signedWitness <- either fail return (signTx btc witnessTx [SigInput (PayWitnessPKHash h) 100000 op sigHashAll Nothing] [k.key])+      signedTaproot <- either fail return (signTx btc taprootTx [SigInput taprootOutput 100000 op sigHashDefault Nothing] [k.key])       -- 82 bytes without witness. The witness: marker and flag 2, count 1,       -- the signature with its hash type after its length, 72 or 73, and       -- the key after its length 34: 437 or 438 units, 110 virtual bytes@@ -823,261 +825,261 @@  {- Building -} -buildSpec :: Ctx -> Spec-buildSpec ctx =+buildSpec :: Spec+buildSpec =   describe "Building a transaction to addresses" $ do     let address = "14LsRquZfURNFrzpcLVGdaHTfAPjjwiSPb"     -- AmountFromValue of Bitcoin Core refuses an amount out of range when     -- createrawtransaction builds a transaction     it "refuses an amount above the 21 million coins that can exist" $ do-      buildAddrTx btc ctx [coinAt 0] [(address, 2100000000000000)] `shouldSatisfy` isRight-      buildAddrTx btc ctx [coinAt 0] [(address, 2100000000000001)] `shouldBe` Left "buildAddrTx: An amount is above the maximum of 2100000000000000 satoshi"-      buildAddrTx btc ctx [coinAt 0] [(address, 18446744073709551615)] `shouldBe` Left "buildAddrTx: An amount is above the maximum of 2100000000000000 satoshi"+      buildAddrTx btc [coinAt 0] [(address, 2100000000000000)] `shouldSatisfy` isRight+      buildAddrTx btc [coinAt 0] [(address, 2100000000000001)] `shouldBe` Left "buildAddrTx: An amount is above the maximum of 2100000000000000 satoshi"+      buildAddrTx btc [coinAt 0] [(address, 18446744073709551615)] `shouldBe` Left "buildAddrTx: An amount is above the maximum of 2100000000000000 satoshi"      it "refuses an address of another network" $-      buildAddrTx bch ctx [coinAt 0] [("bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu", 1000)] `shouldBe` Left "buildAddrTx: Invalid address bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu"+      buildAddrTx bch [coinAt 0] [("bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu", 1000)] `shouldBe` Left "buildAddrTx: Invalid address bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu"  {- Verification -} -verificationSpec :: Ctx -> Spec-verificationSpec ctx =+verificationSpec :: Spec+verificationSpec =   describe "Verification" $ do     let coinOf = OutPoint (fromJust (hexToTxHash genesisTxId))     it "accepts a correct P2PKH spend, and refuses a witness on its input, a wrong key, a wrong amount and a missing coin" $ do-      let (k, p) = fixedKey ctx 1-          (_, other) = fixedKey ctx 2-      let h = fromJust (addressHash160 (pubKeyAddr ctx p))-          otherHash = fromJust (addressHash160 (pubKeyAddr ctx other))+      let (k, p) = fixedKey 1+          (_, other) = fixedKey 2+      let h = fromJust (addressHash160 (pubKeyAddr p))+          otherHash = fromJust (addressHash160 (pubKeyAddr other))           op = coinOf 0-          tx = buildTx ctx [op] [(PayPKHash h, 90000)]-      signed <- either fail return (signTx btc ctx tx [SigInput (PayPKHash h) 100000 op sigHashAll Nothing] [k.key])-      verifyStdTx btc ctx signed [(PayPKHash h, 100000, op)] `shouldBe` True-      verifyStdTx btc ctx signed {witness = [["junk"]]} [(PayPKHash h, 100000, op)] `shouldBe` False-      verifyStdTx btc ctx signed [(PayPKHash otherHash, 100000, op)] `shouldBe` False+          tx = buildTx [op] [(PayPKHash h, 90000)]+      signed <- either fail return (signTx btc tx [SigInput (PayPKHash h) 100000 op sigHashAll Nothing] [k.key])+      verifyStdTx btc signed [(PayPKHash h, 100000, op)] `shouldBe` True+      verifyStdTx btc signed {witness = [["junk"]]} [(PayPKHash h, 100000, op)] `shouldBe` False+      verifyStdTx btc signed [(PayPKHash otherHash, 100000, op)] `shouldBe` False       -- The legacy digest does not commit to the amount, but the outputs may not spend more than the coin-      verifyStdTx btc ctx signed [(PayPKHash h, 89999, op)] `shouldBe` False-      verifyStdTx btc ctx signed [(PayPKHash h, 100000, coinOf 1)] `shouldBe` False-      verifyStdTx btc ctx signed [] `shouldBe` False-      verifyStdInput btc ctx signed [(PayPKHash h, 100000, op)] 0 `shouldBe` True-      verifyStdInput btc ctx signed [(PayPKHash h, 100000, op)] 1 `shouldBe` False-      verifyStdInput btc ctx signed [(PayPKHash h, 100000, op)] (-1) `shouldBe` False+      verifyStdTx btc signed [(PayPKHash h, 89999, op)] `shouldBe` False+      verifyStdTx btc signed [(PayPKHash h, 100000, coinOf 1)] `shouldBe` False+      verifyStdTx btc signed [] `shouldBe` False+      verifyStdInput btc signed [(PayPKHash h, 100000, op)] 0 `shouldBe` True+      verifyStdInput btc signed [(PayPKHash h, 100000, op)] 1 `shouldBe` False+      verifyStdInput btc signed [(PayPKHash h, 100000, op)] (-1) `shouldBe` False      it "refuses a transaction without inputs, and the outputs of a transaction spending more than its coins" $ do-      let (k, p) = fixedKey ctx 1-      let h = fromJust (addressHash160 (pubKeyAddr ctx p))+      let (k, p) = fixedKey 1+      let h = fromJust (addressHash160 (pubKeyAddr p))           ops = [coinOf 0, coinOf 1]-          tx = buildTx ctx ops [(PayPKHash h, 150000)]+          tx = buildTx ops [(PayPKHash h, 150000)]           sigis = [SigInput (PayPKHash h) 100000 op sigHashAll Nothing | op <- ops]           coins = [(PayPKHash h, 100000, op) | op <- ops]-      signed <- either fail return (signTx btc ctx tx sigis [k.key])-      verifyStdTx btc ctx signed coins `shouldBe` True-      verifyStdTx btc ctx signed (take 1 coins) `shouldBe` False-      verifyStdTx btc ctx (buildTx ctx [] [(PayPKHash h, 1)]) [] `shouldBe` False+      signed <- either fail return (signTx btc tx sigis [k.key])+      verifyStdTx btc signed coins `shouldBe` True+      verifyStdTx btc signed (take 1 coins) `shouldBe` False+      verifyStdTx btc (buildTx [] [(PayPKHash h, 1)]) [] `shouldBe` False       -- The same coins hold less than the outputs spend-      verifyStdTx btc ctx signed [(PayPKHash h, 70000, op) | op <- ops] `shouldBe` False+      verifyStdTx btc signed [(PayPKHash h, 70000, op) | op <- ops] `shouldBe` False      it "signs SIGHASH_SINGLE on a legacy input with an output at its index and on a SegWit input, but refuses it on a legacy input without one" $ do-      let (k, p) = fixedKey ctx 1-      let h = fromJust (addressHash160 (pubKeyAddr ctx p))+      let (k, p) = fixedKey 1+      let h = fromJust (addressHash160 (pubKeyAddr p))           ops = [coinOf 0, coinOf 1]           -- one output, so input 1 has none at its index-          tx = buildTx ctx ops [(PayPKHash h, 150000)]+          tx = buildTx ops [(PayPKHash h, 150000)]           legacy op = SigInput (PayPKHash h) 100000 op sigHashSingle Nothing           segwit op = SigInput (PayWitnessPKHash h) 100000 op sigHashSingle Nothing-      signedFirst <- either fail return (signTx btc ctx tx [legacy (coinOf 0)] [k.key])-      verifyStdInput btc ctx signedFirst [(PayPKHash h, 100000, coinOf 0)] 0 `shouldBe` True-      signTx btc ctx tx [legacy (coinOf 1)] [k.key] `shouldBe` Left "makeSignature: SIGHASH_SINGLE without an output at the input index"+      signedFirst <- either fail return (signTx btc tx [legacy (coinOf 0)] [k.key])+      verifyStdInput btc signedFirst [(PayPKHash h, 100000, coinOf 0)] 0 `shouldBe` True+      signTx btc tx [legacy (coinOf 1)] [k.key] `shouldBe` Left "makeSignature: SIGHASH_SINGLE without an output at the input index"       -- The BIP 143 digest commits to the coin even without an output-      signedWitness <- either fail return (signTx btc ctx tx [segwit (coinOf 1)] [k.key])-      verifyStdInput btc ctx signedWitness [(PayWitnessPKHash h, 100000, coinOf 1)] 1 `shouldBe` True+      signedWitness <- either fail return (signTx btc tx [segwit (coinOf 1)] [k.key])+      verifyStdInput btc signedWitness [(PayWitnessPKHash h, 100000, coinOf 1)] 1 `shouldBe` True      -- A node accepts the signature over the constant digest 1 that a     -- legacy SIGHASH_SINGLE input without an output has, so the verifier     -- must too, although the signer refuses to make one     it "accepts a legacy SIGHASH_SINGLE signature over the constant digest 1, as a node does" $ do-      let (k, p) = fixedKey ctx 1-      let h = fromJust (addressHash160 (pubKeyAddr ctx p))+      let (k, p) = fixedKey 1+      let h = fromJust (addressHash160 (pubKeyAddr p))           ops = [coinOf 0, coinOf 1]-          tx = buildTx ctx ops [(PayPKHash h, 150000)]+          tx = buildTx ops [(PayPKHash h, 150000)]           one = "0100000000000000000000000000000000000000000000000000000000000000" :: Hash256-          overOne = marshal (btc, ctx) (RegularInput (SpendPKHash (TxSignature (signHash ctx k.key one) sigHashSingle) p))+          overOne = marshal btc (RegularInput (SpendPKHash (TxSignature (signHash k.key one) sigHashSingle) p))           spent = Tx tx.version [TxIn (coinOf 0) "" 0xffffffff, TxIn (coinOf 1) overOne 0xffffffff] tx.outputs [] tx.locktime           spentFirst = Tx tx.version [TxIn (coinOf 0) overOne 0xffffffff, TxIn (coinOf 1) "" 0xffffffff] tx.outputs [] tx.locktime-      verifyStdInput btc ctx spent [(PayPKHash h, 100000, coinOf 1)] 1 `shouldBe` True+      verifyStdInput btc spent [(PayPKHash h, 100000, coinOf 1)] 1 `shouldBe` True       -- The same signature on input 0, which has an output, does not verify-      verifyStdInput btc ctx spentFirst [(PayPKHash h, 100000, coinOf 0)] 0 `shouldBe` False+      verifyStdInput btc spentFirst [(PayPKHash h, 100000, coinOf 0)] 0 `shouldBe` False      it "refuses a SegWit input with a non-empty input script and a wrong amount" $ do-      let (k, p) = fixedKey ctx 1-      let h = fromJust (addressHash160 (pubKeyAddr ctx p))+      let (k, p) = fixedKey 1+      let h = fromJust (addressHash160 (pubKeyAddr p))           op = coinOf 0-          tx = buildTx ctx [op] [(PayWitnessPKHash h, 90000)]-      signed <- either fail return (signTx btc ctx tx [SigInput (PayWitnessPKHash h) 100000 op sigHashAll Nothing] [k.key])-      verifyStdTx btc ctx signed [(PayWitnessPKHash h, 100000, op)] `shouldBe` True+          tx = buildTx [op] [(PayWitnessPKHash h, 90000)]+      signed <- either fail return (signTx btc tx [SigInput (PayWitnessPKHash h) 100000 op sigHashAll Nothing] [k.key])+      verifyStdTx btc signed [(PayWitnessPKHash h, 100000, op)] `shouldBe` True       -- The BIP 143 digest commits to the amount-      verifyStdTx btc ctx signed [(PayWitnessPKHash h, 100001, op)] `shouldBe` False+      verifyStdTx btc signed [(PayWitnessPKHash h, 100001, op)] `shouldBe` False       let pushed = Tx signed.version [TxIn op "\x51" i.sequence | i <- signed.inputs] signed.outputs signed.witness signed.locktime-      verifyStdTx btc ctx pushed [(PayWitnessPKHash h, 100000, op)] `shouldBe` False+      verifyStdTx btc pushed [(PayWitnessPKHash h, 100000, op)] `shouldBe` False  {- Merging -} -mergeSpec :: Ctx -> Spec-mergeSpec ctx =+mergeSpec :: Spec+mergeSpec =   describe "Merging partially signed transactions" $ do     it "leaves an input that no transaction signed unsigned, and merges the others" $ do-      let (k1, p1) = fixedKey ctx 1-          (k2, p2) = fixedKey ctx 2+      let (k1, p1) = fixedKey 1+          (k2, p2) = fixedKey 2       let ms = PayMulSig [p1, p2] 2-          so = PayScriptHash (fromJust (either (const Nothing) addressHash160 (payToScriptAddress ctx ms)))+          so = PayScriptHash (fromJust (either (const Nothing) addressHash160 (payToScriptAddress ms)))           ops = [OutPoint (fromJust (hexToTxHash genesisTxId)) 0, OutPoint (fromJust (hexToTxHash genesisTxId)) 1]-          tx = buildTx ctx ops [(PayPKHash (fromJust (addressHash160 (pubKeyAddr ctx p1))), 90000)]+          tx = buildTx ops [(PayPKHash (fromJust (addressHash160 (pubKeyAddr p1))), 90000)]           coins = [(so, 100000, op) | op <- ops]           sigi = SigInput so 100000 (head ops) sigHashAll (Just ms)-      a <- either fail return (signTx btc ctx tx [sigi] [k1.key])-      b <- either fail return (signTx btc ctx tx [sigi] [k2.key])-      merged <- either fail return (mergeTxs btc ctx [a, b] coins)+      a <- either fail return (signTx btc tx [sigi] [k1.key])+      b <- either fail return (signTx btc tx [sigi] [k2.key])+      merged <- either fail return (mergeTxs btc [a, b] coins)       (merged.inputs !! 1).script `shouldBe` ""-      verifyStdInput btc ctx merged coins 0 `shouldBe` True-      verifyStdTx btc ctx merged coins `shouldBe` False+      verifyStdInput btc merged coins 0 `shouldBe` True+      verifyStdTx btc merged coins `shouldBe` False       -- The second input signed by both completes the transaction       let sigi2 = SigInput so 100000 (ops !! 1) sigHashAll (Just ms)-      c <- either fail return (signTx btc ctx tx [sigi2] [k1.key])-      d <- either fail return (signTx btc ctx tx [sigi2] [k2.key])-      complete <- either fail return (mergeTxs btc ctx [a, b, c, d] coins)-      verifyStdTx btc ctx complete coins `shouldBe` True+      c <- either fail return (signTx btc tx [sigi2] [k1.key])+      d <- either fail return (signTx btc tx [sigi2] [k2.key])+      complete <- either fail return (mergeTxs btc [a, b, c, d] coins)+      verifyStdTx btc complete coins `shouldBe` True      it "keeps the witness of an input that is not merged" $ do-      let (k1, p1) = fixedKey ctx 1-          (k2, p2) = fixedKey ctx 2-          (k3, p3) = fixedKey ctx 3+      let (k1, p1) = fixedKey 1+          (k2, p2) = fixedKey 2+          (k3, p3) = fixedKey 3           ms = PayMulSig [p1, p2] 2-          so = either error id (toP2SH =<< encodeOutput ctx ms)-          wpkh = PayWitnessPKHash (keyHash ctx p3)-          tx = buildTx ctx [coinAt 0, coinAt 1] [(PayPKHash (keyHash ctx p1), 150000)]+          so = either error id (toP2SH =<< encodeOutput ms)+          wpkh = PayWitnessPKHash (keyHash p3)+          tx = buildTx [coinAt 0, coinAt 1] [(PayPKHash (keyHash p1), 150000)]           msSigi = SigInput so 100000 (coinAt 0) sigHashAll (Just ms)           coins = [(so, 100000, coinAt 0), (wpkh, 100000, coinAt 1)]-      withSegwit <- either fail return (signTx btc ctx tx [SigInput wpkh 100000 (coinAt 1) sigHashAll Nothing] [k3.key])-      a <- either fail return (signTx btc ctx withSegwit [msSigi] [k1.key])-      b <- either fail return (signTx btc ctx withSegwit [msSigi] [k2.key])-      merged <- either fail return (mergeTxs btc ctx [a, b] [(so, 100000, coinAt 0)])+      withSegwit <- either fail return (signTx btc tx [SigInput wpkh 100000 (coinAt 1) sigHashAll Nothing] [k3.key])+      a <- either fail return (signTx btc withSegwit [msSigi] [k1.key])+      b <- either fail return (signTx btc withSegwit [msSigi] [k2.key])+      merged <- either fail return (mergeTxs btc [a, b] [(so, 100000, coinAt 0)])       merged.witness `shouldBe` withSegwit.witness-      verifyStdTx btc ctx merged coins `shouldBe` True+      verifyStdTx btc merged coins `shouldBe` True      it "mergeTxInput refuses an index that a transaction does not have" $ do-      let (_, p1) = fixedKey ctx 1+      let (_, p1) = fixedKey 1           ms = PayMulSig [p1] 1-          tx = buildTx ctx [coinAt 0] []-          short = buildTx ctx [] []-      mergeTxInput btc ctx [tx] tx ((ms, 100000), 3) `shouldBe` Left "mergeTxInput: input index out of range"-      mergeTxInput btc ctx [tx, short] tx ((ms, 100000), 0) `shouldBe` Left "mergeTxInput: input index out of range"+          tx = buildTx [coinAt 0] []+          short = buildTx [] []+      mergeTxInput btc [tx] tx ((ms, 100000), 3) `shouldBe` Left "mergeTxInput: input index out of range"+      mergeTxInput btc [tx, short] tx ((ms, 100000), 0) `shouldBe` Left "mergeTxInput: input index out of range"      it "refuses to merge inputs that carry different redeem scripts" $ do-      let (k1, p1) = fixedKey ctx 1-          (k2, p2) = fixedKey ctx 2-          (_, p3) = fixedKey ctx 3+      let (k1, p1) = fixedKey 1+          (k2, p2) = fixedKey 2+          (_, p3) = fixedKey 3           msA = PayMulSig [p1, p2] 2           msB = PayMulSig [p1, p2, p3] 2-          hashOf ms = either error id (toP2SH =<< encodeOutput ctx ms)-          tx = buildTx ctx [coinAt 0] [(PayPKHash (keyHash ctx p1), 90000)]-      a <- either fail return (signTx btc ctx tx [SigInput (hashOf msA) 100000 (coinAt 0) sigHashAll (Just msA)] [k1.key])-      b <- either fail return (signTx btc ctx tx [SigInput (hashOf msB) 100000 (coinAt 0) sigHashAll (Just msB)] [k2.key])-      mergeTxs btc ctx [a, b] [(hashOf msA, 100000, coinAt 0)] `shouldBe` Left "Redeem scripts do not match"+          hashOf ms = either error id (toP2SH =<< encodeOutput ms)+          tx = buildTx [coinAt 0] [(PayPKHash (keyHash p1), 90000)]+      a <- either fail return (signTx btc tx [SigInput (hashOf msA) 100000 (coinAt 0) sigHashAll (Just msA)] [k1.key])+      b <- either fail return (signTx btc tx [SigInput (hashOf msB) 100000 (coinAt 0) sigHashAll (Just msB)] [k2.key])+      mergeTxs btc [a, b] [(hashOf msA, 100000, coinAt 0)] `shouldBe` Left "Redeem scripts do not match"      it "countMulSig counts the signatures that verify, in key order" $ do-      let (k1, p1) = fixedKey ctx 1-          (k2, p2) = fixedKey ctx 2-          (k3, p3) = fixedKey ctx 3+      let (k1, p1) = fixedKey 1+          (k2, p2) = fixedKey 2+          (k3, p3) = fixedKey 3       let ms = PayMulSig [p1, p2, p3] 2-          msScript = either error id (encodeOutput ctx ms)+          msScript = either error id (encodeOutput ms)           op = OutPoint (fromJust (hexToTxHash genesisTxId)) 0-          tx = buildTx ctx [op] [(PayPKHash (fromJust (addressHash160 (pubKeyAddr ctx p1))), 90000)]-          sigOf k = TxSignature (signHash ctx k.key (either error id (txSigHash btc tx msScript 100000 0 sigHashAll))) sigHashAll-          count = countMulSig btc ctx tx msScript 100000 0 (map (.point) [p1, p2, p3])+          tx = buildTx [op] [(PayPKHash (fromJust (addressHash160 (pubKeyAddr p1))), 90000)]+          sigOf k = TxSignature (signHash k.key (either error id (txSigHash btc tx msScript 100000 0 sigHashAll))) sigHashAll+          count = countMulSig btc tx msScript 100000 0 (map (.point) [p1, p2, p3])       count [sigOf k1, sigOf k3] `shouldBe` 2       count [sigOf k1, sigOf k2, sigOf k3] `shouldBe` 3       -- The count is not a verdict: verifyStdInput refuses this input       count [sigOf k1, TxSignatureEmpty, sigOf k3] `shouldBe` 2       -- A signature out of key order is not counted, nor a signature of another digest       count [sigOf k3, sigOf k1] `shouldBe` 1-      count [TxSignature (signHash ctx k1.key (sha256 ("other" :: ByteString))) sigHashAll] `shouldBe` 0+      count [TxSignature (signHash k1.key (sha256 ("other" :: ByteString))) sigHashAll] `shouldBe` 0       count [] `shouldBe` 0      it "findSigInput pairs the signing parameters with the index of their input" $ do       let ops = [OutPoint (fromJust (hexToTxHash genesisTxId)) i | i <- [0 .. 2]]-          tx = buildTx ctx ops []+          tx = buildTx ops []           sigi op = SigInput (PayPKHash "0000000000000000000000000000000000000000") 1 op sigHashAll Nothing       map snd (findSigInput [sigi (ops !! 2), sigi (ops !! 0)] tx.inputs) `shouldBe` [0, 2]       findSigInput [sigi (OutPoint (fromJust (hexToTxHash genesisTxId)) 9)] tx.inputs `shouldBe` []      it "buildInput refuses an index out of range, a Taproot output and a mismatched redeem script" $ do-      let (k, p) = fixedKey ctx 1+      let (k, p) = fixedKey 1       let op = OutPoint (fromJust (hexToTxHash genesisTxId)) 0-          tx = buildTx ctx [op] []-          sig = TxSignature (signHash ctx k.key (sha256 ("digest" :: ByteString))) sigHashAll-          h = fromJust (addressHash160 (pubKeyAddr ctx p))-      buildInput btc ctx tx 1 (PayPKHash h) 1 Nothing sig p `shouldBe` Left "buildInput: Invalid input index"-      buildInput btc ctx tx 0 (taprootScriptOutput ctx (TaprootOutput p.point Nothing)) 1 Nothing sig p `shouldBe` Left "buildInput: a Taproot input has no input script"-      buildInput btc ctx tx 0 (PayPKHash h) 1 (Just (PayPK p)) sig p `shouldBe` Left "buildInput: Invalid output/redeem script combination"-      buildInput btc ctx tx 0 (PayPKHash h) 1 Nothing sig p `shouldBe` Right (RegularInput (SpendPKHash sig p))+          tx = buildTx [op] []+          sig = TxSignature (signHash k.key (sha256 ("digest" :: ByteString))) sigHashAll+          h = fromJust (addressHash160 (pubKeyAddr p))+      buildInput btc tx 1 (PayPKHash h) 1 Nothing sig p `shouldBe` Left "buildInput: Invalid input index"+      buildInput btc tx 0 (taprootScriptOutput (TaprootOutput p.point Nothing)) 1 Nothing sig p `shouldBe` Left "buildInput: a Taproot input has no input script"+      buildInput btc tx 0 (PayPKHash h) 1 (Just (PayPK p)) sig p `shouldBe` Left "buildInput: Invalid output/redeem script combination"+      buildInput btc tx 0 (PayPKHash h) 1 Nothing sig p `shouldBe` Right (RegularInput (SpendPKHash sig p))      it "refuses an empty list and transactions that differ" $ do-      mergeTxs btc ctx [] [] `shouldBe` Left "Transaction list is empty"+      mergeTxs btc [] [] `shouldBe` Left "Transaction list is empty"       let op = OutPoint (fromJust (hexToTxHash genesisTxId)) 0-          one = buildTx ctx [op] []-          other = buildTx ctx [op] [(PayPK (PublicKey (derivePubKey ctx (fromJust (secKey (B.replicate 32 1)))) True), 1)]-      mergeTxs btc ctx [one] [] `shouldBe` Right one-      mergeTxs btc ctx [one, other] [] `shouldBe` Left "Transactions do not match"+          one = buildTx [op] []+          other = buildTx [op] [(PayPK (PublicKey (derivePubKey (fromJust (secKey (B.replicate 32 1)))) True), 1)]+      mergeTxs btc [one] [] `shouldBe` Right one+      mergeTxs btc [one, other] [] `shouldBe` Left "Transactions do not match"  {- Taproot -} -taprootSigningSpec :: Ctx -> Spec-taprootSigningSpec ctx =+taprootSigningSpec :: Spec+taprootSigningSpec =   describe "Taproot key path signing" $ do     let op = OutPoint (fromJust (hexToTxHash genesisTxId)) 0     it "signs with the internal key of an output without script tree, as BIP 86 spends, and with the output key itself" $ do-      let (k, p) = fixedKey ctx 1-      let so = taprootScriptOutput ctx (TaprootOutput p.point Nothing)-          tx = buildTx ctx [op] [(so, 90000)]+      let (k, p) = fixedKey 1+      let so = taprootScriptOutput (TaprootOutput p.point Nothing)+          tx = buildTx [op] [(so, 90000)]           sigi = SigInput so 100000 op sigHashDefault Nothing-          tweaked = fromJust (taprootOutputSecKey ctx k.key Nothing)-      byInternal <- either fail return (signTx btc ctx tx [sigi] [k.key])-      byOutput <- either fail return (signTx btc ctx tx [sigi] [tweaked])+          tweaked = fromJust (taprootOutputSecKey k.key Nothing)+      byInternal <- either fail return (signTx btc tx [sigi] [k.key])+      byOutput <- either fail return (signTx btc tx [sigi] [tweaked])       byInternal `shouldBe` byOutput       map length byInternal.witness `shouldBe` [1]       map (B.length . head) byInternal.witness `shouldBe` [64]-      verifyStdTx btc ctx byInternal [(so, 100000, op)] `shouldBe` True+      verifyStdTx btc byInternal [(so, 100000, op)] `shouldBe` True       -- A signature with a hash type is 65 bytes and verifies as well-      withType <- either fail return (signTx btc ctx tx [sigi {sighash = setAnyoneCanPay sigHashAll}] [k.key])+      withType <- either fail return (signTx btc tx [sigi {sighash = setAnyoneCanPay sigHashAll}] [k.key])       map (B.length . head) withType.witness `shouldBe` [65]-      verifyStdTx btc ctx withType [(so, 100000, op)] `shouldBe` True+      verifyStdTx btc withType [(so, 100000, op)] `shouldBe` True       -- Another key does not sign-      let (other, _) = fixedKey ctx 2-      fmap (.witness) (signTx btc ctx tx [sigi] [other.key]) `shouldBe` Right []+      let (other, _) = fixedKey 2+      fmap (.witness) (signTx btc tx [sigi] [other.key]) `shouldBe` Right []      it "needs the output every input spends, and refuses signInput" $ do-      let (k, p) = fixedKey ctx 1-      let so = taprootScriptOutput ctx (TaprootOutput p.point Nothing)+      let (k, p) = fixedKey 1+      let so = taprootScriptOutput (TaprootOutput p.point Nothing)           other = OutPoint (fromJust (hexToTxHash genesisTxId)) 1-          tx = buildTx ctx [op, other] [(so, 90000)]+          tx = buildTx [op, other] [(so, 90000)]           sigi = SigInput so 100000 op sigHashDefault Nothing-      signTx btc ctx tx [sigi] [k.key] `shouldBe` Left "signTx: a Taproot signature needs the output every input spends"-      signInput btc ctx tx 0 sigi k `shouldBe` Left "signInput: a Taproot input is signed with signTaprootInput"-      signTaprootInput ctx tx [TxOut 100000 (marshal ctx so)] 0 sigHashDefault k.key `shouldBe` Left "taprootSigHash: one spent output per input is required"-      signTaprootInput ctx tx [TxOut 100000 (marshal ctx so), TxOut 1 ""] 0 (setForkIdFlag sigHashAll) k.key `shouldBe` Left "taprootSigHash: invalid hash type 65"+      signTx btc tx [sigi] [k.key] `shouldBe` Left "signTx: a Taproot signature needs the output every input spends"+      signInput btc tx 0 sigi k `shouldBe` Left "signInput: a Taproot input is signed with signTaprootInput"+      signTaprootInput tx [TxOut 100000 (encodeSerial so)] 0 sigHashDefault k.key `shouldBe` Left "taprootSigHash: one spent output per input is required"+      signTaprootInput tx [TxOut 100000 (encodeSerial so), TxOut 1 ""] 0 (setForkIdFlag sigHashAll) k.key `shouldBe` Left "taprootSigHash: invalid hash type 65"  {- SegWit helpers -} -segwitSpec :: Ctx -> Spec-segwitSpec ctx =+segwitSpec :: Spec+segwitSpec =   describe "SegWit witness helpers" $ do-    let (k, p) = fixedKey ctx 1+    let (k, p) = fixedKey 1         digest = sha256 ("message" :: ByteString)-        sig = TxSignature (signHash ctx k.key digest) sigHashAll-        sigBytes = encodeTxSig btc ctx sig-        keyBytes = marshal ctx p-        h = fromJust (addressHash160 (pubKeyAddr ctx p))+        sig = TxSignature (signHash k.key digest) sigHashAll+        sigBytes = encodeTxSig btc sig+        keyBytes = encodeSerial p+        h = fromJust (addressHash160 (pubKeyAddr p))         multisig = PayMulSig [p] 1-        multisigScript = either error id (encodeOutput ctx multisig)+        multisigScript = either error id (encodeOutput multisig)         wsh = either error id (toP2WSH multisigScript)     it "isSegwit is true for the version 0 programs only" $ do       isSegwit (PayWitnessPKHash h) `shouldBe` True@@ -1086,33 +1088,33 @@       isSegwit (PayWitness 1 (B.replicate 32 0)) `shouldBe` False      it "a simple input stacks its signatures, keys and the empty item of multisig" $ do-      simpleInputStack btc ctx (SpendPK sig) `shouldBe` [sigBytes]-      simpleInputStack btc ctx (SpendPKHash sig p) `shouldBe` [sigBytes, keyBytes]-      simpleInputStack btc ctx (SpendMulSig [sig, TxSignatureEmpty]) `shouldBe` ["", sigBytes, ""]+      simpleInputStack btc (SpendPK sig) `shouldBe` [sigBytes]+      simpleInputStack btc (SpendPKHash sig p) `shouldBe` [sigBytes, keyBytes]+      simpleInputStack btc (SpendMulSig [sig, TxSignatureEmpty]) `shouldBe` ["", sigBytes, ""]      it "a witness program encodes to its stack, with the script last for P2WSH" $ do-      toWitnessStack btc ctx (P2WPKH (WitnessProgramPKH sig p)) `shouldBe` [sigBytes, keyBytes]-      toWitnessStack btc ctx (P2WSH (WitnessProgramSH ["", sigBytes] multisigScript)) `shouldBe` ["", sigBytes, runPutS (serialize multisigScript)]-      toWitnessStack btc ctx EmptyWitnessProgram `shouldBe` []+      toWitnessStack btc (P2WPKH (WitnessProgramPKH sig p)) `shouldBe` [sigBytes, keyBytes]+      toWitnessStack btc (P2WSH (WitnessProgramSH ["", sigBytes] multisigScript)) `shouldBe` ["", sigBytes, runPutS (serialize multisigScript)]+      toWitnessStack btc EmptyWitnessProgram `shouldBe` []      it "a witness is read against the output it spends" $ do-      viewWitnessProgram btc ctx (PayWitnessPKHash h) [sigBytes, keyBytes] `shouldBe` Right (P2WPKH (WitnessProgramPKH sig p))-      viewWitnessProgram btc ctx (PayWitnessPKHash h) [sigBytes] `shouldBe` Left "viewWitnessProgram: Invalid witness program"-      viewWitnessProgram btc ctx wsh ["", sigBytes, runPutS (serialize multisigScript)] `shouldBe` Right (P2WSH (WitnessProgramSH ["", sigBytes] multisigScript))-      viewWitnessProgram btc ctx (PayPKHash h) [] `shouldBe` Right EmptyWitnessProgram-      viewWitnessProgram btc ctx (PayPKHash h) [sigBytes] `shouldBe` Left "viewWitnessProgram: Invalid witness program"+      viewWitnessProgram btc (PayWitnessPKHash h) [sigBytes, keyBytes] `shouldBe` Right (P2WPKH (WitnessProgramPKH sig p))+      viewWitnessProgram btc (PayWitnessPKHash h) [sigBytes] `shouldBe` Left "viewWitnessProgram: Invalid witness program"+      viewWitnessProgram btc wsh ["", sigBytes, runPutS (serialize multisigScript)] `shouldBe` Right (P2WSH (WitnessProgramSH ["", sigBytes] multisigScript))+      viewWitnessProgram btc (PayPKHash h) [] `shouldBe` Right EmptyWitnessProgram+      viewWitnessProgram btc (PayPKHash h) [sigBytes] `shouldBe` Left "viewWitnessProgram: Invalid witness program"      it "a witness program decodes to the input it stands for" $ do-      decodeWitnessInput btc ctx (P2WPKH (WitnessProgramPKH sig p)) `shouldBe` Right (Nothing, SpendPKHash sig p)-      decodeWitnessInput btc ctx (P2WSH (WitnessProgramSH ["", sigBytes] multisigScript)) `shouldBe` Right (Just multisig, SpendMulSig [sig])-      decodeWitnessInput btc ctx (P2WSH (WitnessProgramSH [sigBytes] multisigScript)) `shouldBe` Left "decodeWitnessInput: Non-standard script output"-      decodeWitnessInput btc ctx EmptyWitnessProgram `shouldBe` Left "decodeWitnessInput: Empty witness program"+      decodeWitnessInput btc (P2WPKH (WitnessProgramPKH sig p)) `shouldBe` Right (Nothing, SpendPKHash sig p)+      decodeWitnessInput btc (P2WSH (WitnessProgramSH ["", sigBytes] multisigScript)) `shouldBe` Right (Just multisig, SpendMulSig [sig])+      decodeWitnessInput btc (P2WSH (WitnessProgramSH [sigBytes] multisigScript)) `shouldBe` Left "decodeWitnessInput: Non-standard script output"+      decodeWitnessInput btc EmptyWitnessProgram `shouldBe` Left "decodeWitnessInput: Empty witness program"      it "a witness program is computed from a standard input, native or nested" $ do-      calcWitnessProgram btc ctx (PayWitnessPKHash h) (RegularInput (SpendPKHash sig p)) `shouldBe` Right (P2WPKH (WitnessProgramPKH sig p))-      calcWitnessProgram btc ctx (either error id (toP2SH =<< encodeOutput ctx (PayWitnessPKHash h))) (RegularInput (SpendPKHash sig p)) `shouldBe` Right (P2WPKH (WitnessProgramPKH sig p))-      calcWitnessProgram btc ctx wsh (ScriptHashInput (SpendMulSig [sig]) multisig) `shouldBe` Right (P2WSH (WitnessProgramSH ["", sigBytes] multisigScript))-      calcWitnessProgram btc ctx (PayPKHash h) (RegularInput (SpendPKHash sig p)) `shouldBe` Left "calcWitnessProgram: Invalid segwit SigInput"+      calcWitnessProgram btc (PayWitnessPKHash h) (RegularInput (SpendPKHash sig p)) `shouldBe` Right (P2WPKH (WitnessProgramPKH sig p))+      calcWitnessProgram btc (either error id (toP2SH =<< encodeOutput (PayWitnessPKHash h))) (RegularInput (SpendPKHash sig p)) `shouldBe` Right (P2WPKH (WitnessProgramPKH sig p))+      calcWitnessProgram btc wsh (ScriptHashInput (SpendMulSig [sig]) multisig) `shouldBe` Right (P2WSH (WitnessProgramSH ["", sigBytes] multisigScript))+      calcWitnessProgram btc (PayPKHash h) (RegularInput (SpendPKHash sig p)) `shouldBe` Left "calcWitnessProgram: Invalid segwit SigInput"  {- Genesis -} @@ -1141,13 +1143,13 @@  -- These signatures were made by Bitcoin Core 32.1 on regtest, not by the -- library, so they check the verifier against an independent signer.-coreSignedSpec :: Ctx -> Spec-coreSignedSpec ctx =+coreSignedSpec :: Spec+coreSignedSpec =   describe "Transactions signed by Bitcoin Core" $ do     let verdict coinAmount (_, txHex, scriptHex, amount) = do           tx <- decodeTx (hexBytes txHex)-          coin <- unmarshal ctx (hexBytes scriptHex)-          return (verifyStdTx btcRegTest ctx tx [(coin, coinAmount amount, i.outpoint) | i <- tx.inputs])+          coin <- decodeSerial (hexBytes scriptHex)+          return (verifyStdTx btcRegTest tx [(coin, coinAmount amount, i.outpoint) | i <- tx.inputs])         kindOf (kind, _, _, _) = kind         -- The kinds whose digest commits to the amount of the coin         commitsToAmount v = any (`isPrefixOf` kindOf v) ["p2w", "p2sh-p2w", "p2tr"]@@ -1170,31 +1172,31 @@ -- A 2-of-3 multisig coin of the fixed keys 1, 2 and 3, in its three forms: -- bare, pay-to-script-hash and pay-to-witness-script-hash. Each test gives -- the signature items of the input, and gets the verdict for each form.-consensusSpec :: Ctx -> Spec-consensusSpec ctx =+consensusSpec :: Spec+consensusSpec =   describe "Verification of inputs that no block can contain" $ do-    let (k1, p1) = fixedKey ctx 1-        (k2, p2) = fixedKey ctx 2-        (k3, p3) = fixedKey ctx 3-        (k4, _) = fixedKey ctx 4+    let (k1, p1) = fixedKey 1+        (k2, p2) = fixedKey 2+        (k3, p3) = fixedKey 3+        (k4, _) = fixedKey 4         op = coinAt 0-        tx = buildTx ctx [op] [(PayPKHash (keyHash ctx p1), 90000)]+        tx = buildTx [op] [(PayPKHash (keyHash p1), 90000)]         ms = PayMulSig [p1, p2, p3] 2-        msScript = either error id (encodeOutput ctx ms)+        msScript = either error id (encodeOutput ms)         -- The digest that a signature of the bare and the pay-to-script-hash         -- form signs, and the BIP 143 digest of the witness form         legacyDigest = either error id (txSigHash btc tx msScript 100000 0 sigHashAll)         witnessDigest = either error id (txSigHashForkId btc tx msScript 100000 0 sigHashAll)-        sig digest k = TxSignature (signHash ctx k.key digest) sigHashAll+        sig digest k = TxSignature (signHash k.key digest) sigHashAll         p2sh = either error id (toP2SH msScript)         p2wsh = either error id (toP2WSH msScript)-        bare items = withInputScript tx 0 (marshal (btc, ctx) (RegularInput (SpendMulSig items)))-        hashed items = withInputScript tx 0 (marshal (btc, ctx) (ScriptHashInput (SpendMulSig items) ms))-        inWitness items = withWitness tx [simpleInputStack btc ctx (SpendMulSig items) <> [runPutS (serialize msScript)]]+        bare items = withInputScript tx 0 (marshal btc (RegularInput (SpendMulSig items)))+        hashed items = withInputScript tx 0 (marshal btc (ScriptHashInput (SpendMulSig items) ms))+        inWitness items = withWitness tx [simpleInputStack btc (SpendMulSig items) <> [runPutS (serialize msScript)]]         verdicts itemsOf =-          ( verifyStdInput btc ctx (bare (itemsOf legacyDigest)) [(ms, 100000, op)] 0,-            verifyStdInput btc ctx (hashed (itemsOf legacyDigest)) [(p2sh, 100000, op)] 0,-            verifyStdInput btc ctx (inWitness (itemsOf witnessDigest)) [(p2wsh, 100000, op)] 0+          ( verifyStdInput btc (bare (itemsOf legacyDigest)) [(ms, 100000, op)] 0,+            verifyStdInput btc (hashed (itemsOf legacyDigest)) [(p2sh, 100000, op)] 0,+            verifyStdInput btc (inWitness (itemsOf witnessDigest)) [(p2wsh, 100000, op)] 0           )      it "accepts a 2-of-3 multisig input with the signatures of two of its keys, in key order" $ do@@ -1227,121 +1229,121 @@     -- BIP 141: the input script of a nested witness program "must be     -- exactly a push of the BIP16 redeemScript"     it "refuses a P2SH-P2WPKH input whose script pushes the program with OP_PUSHDATA1" $ do-      let h = keyHash ctx p1-          coin = either error id (toP2SH =<< encodeOutput ctx (PayWitnessPKHash h))+      let h = keyHash p1+          coin = either error id (toP2SH =<< encodeOutput (PayWitnessPKHash h))           sigi = SigInput (PayWitnessPKHash h) 100000 op sigHashAll Nothing           program = B.pack [0x00, 0x14] <> runPutS (serialize h)-      signed <- either fail return (signNestedWitnessTx btc ctx tx [sigi] [k1.key])+      signed <- either fail return (signNestedWitnessTx btc tx [sigi] [k1.key])       (head signed.inputs).script `shouldBe` B.singleton 0x16 <> program-      verifyStdInput btc ctx signed [(coin, 100000, op)] 0 `shouldBe` True-      verifyStdInput btc ctx (withInputScript signed 0 (B.pack [0x4c, 0x16] <> program)) [(coin, 100000, op)] 0 `shouldBe` False+      verifyStdInput btc signed [(coin, 100000, op)] 0 `shouldBe` True+      verifyStdInput btc (withInputScript signed 0 (B.pack [0x4c, 0x16] <> program)) [(coin, 100000, op)] 0 `shouldBe` False      it "refuses a Taproot input that has an input script" $ do-      let so = taprootScriptOutput ctx (TaprootOutput p1.point Nothing)-      signed <- either fail return (signTx btc ctx tx [SigInput so 100000 op sigHashDefault Nothing] [k1.key])-      verifyStdInput btc ctx signed [(so, 100000, op)] 0 `shouldBe` True-      verifyStdInput btc ctx (withInputScript signed 0 "\x51") [(so, 100000, op)] 0 `shouldBe` False+      let so = taprootScriptOutput (TaprootOutput p1.point Nothing)+      signed <- either fail return (signTx btc tx [SigInput so 100000 op sigHashDefault Nothing] [k1.key])+      verifyStdInput btc signed [(so, 100000, op)] 0 `shouldBe` True+      verifyStdInput btc (withInputScript signed 0 "\x51") [(so, 100000, op)] 0 `shouldBe` False      -- CheckTransaction of Bitcoin Core: bad-txns-inputs-duplicate     it "refuses a transaction that lists the same outpoint twice" $ do-      let h = keyHash ctx p1-          twice = buildTx ctx [op, op] [(PayPKHash h, 90000)]+      let h = keyHash p1+          twice = buildTx [op, op] [(PayPKHash h, 90000)]           sigi = SigInput (PayPKHash h) 100000 op sigHashAll Nothing-      signed <- either fail return (signTx btc ctx twice [sigi, sigi] [k1.key])+      signed <- either fail return (signTx btc twice [sigi, sigi] [k1.key])       map (B.null . (.script)) signed.inputs `shouldBe` [False, False]-      verifyStdTx btc ctx signed [(PayPKHash h, 100000, op)] `shouldBe` False-      verifyStdTx btc ctx signed [(PayPKHash h, 100000, op), (PayPKHash h, 100000, op)] `shouldBe` False+      verifyStdTx btc signed [(PayPKHash h, 100000, op)] `shouldBe` False+      verifyStdTx btc signed [(PayPKHash h, 100000, op), (PayPKHash h, 100000, op)] `shouldBe` False      it "refuses a transaction with no inputs and no outputs" $-      verifyStdTx btc ctx (Tx 1 [] [] [] 0) [] `shouldBe` False+      verifyStdTx btc (Tx 1 [] [] [] 0) [] `shouldBe` False      it "accepts outputs that spend exactly what the coins hold, and refuses one satoshi more" $ do-      let h = keyHash ctx p1+      let h = keyHash p1           sigi = SigInput (PayPKHash h) 100000 op sigHashAll Nothing-          exact = buildTx ctx [op] [(PayPKHash h, 100000)]-          over = buildTx ctx [op] [(PayPKHash h, 100001)]-      signedExact <- either fail return (signTx btc ctx exact [sigi] [k1.key])-      signedOver <- either fail return (signTx btc ctx over [sigi] [k1.key])-      verifyStdTx btc ctx signedExact [(PayPKHash h, 100000, op)] `shouldBe` True-      verifyStdTx btc ctx signedOver [(PayPKHash h, 100000, op)] `shouldBe` False+          exact = buildTx [op] [(PayPKHash h, 100000)]+          over = buildTx [op] [(PayPKHash h, 100001)]+      signedExact <- either fail return (signTx btc exact [sigi] [k1.key])+      signedOver <- either fail return (signTx btc over [sigi] [k1.key])+      verifyStdTx btc signedExact [(PayPKHash h, 100000, op)] `shouldBe` True+      verifyStdTx btc signedOver [(PayPKHash h, 100000, op)] `shouldBe` False      -- Bitcoin Cash has no SegWit, so a witness program is no template there     it "refuses a witness spend on a network without SegWit" $ do-      let h = keyHash ctx p1+      let h = keyHash p1           forkId = setForkIdFlag sigHashAll-          code = either error id (encodeOutput ctx (PayPKHash h))+          code = either error id (encodeOutput (PayPKHash h))           digest = either error id (txSigHashForkId bch tx code 100000 0 forkId)-          stack = [encodeTxSig bch ctx (TxSignature (signHash ctx k1.key digest) forkId), marshal ctx p1]-      verifyStdInput bch ctx (withWitness tx [stack]) [(PayWitnessPKHash h, 100000, op)] 0 `shouldBe` False+          stack = [encodeTxSig bch (TxSignature (signHash k1.key digest) forkId), encodeSerial p1]+      verifyStdInput bch (withWitness tx [stack]) [(PayWitnessPKHash h, 100000, op)] 0 `shouldBe` False  {- A coin spent with a key or a script that is not its own -}  -- In each test the thief signs the right digest of the coin with key 2, and -- puts key 2, or a script of key 2, where the coin commits to key 1.-thiefSpec :: Ctx -> Spec-thiefSpec ctx =+thiefSpec :: Spec+thiefSpec =   describe "Verification of a coin spent with a key or a script that is not its own" $ do-    let (k1, p1) = fixedKey ctx 1-        (k2, p2) = fixedKey ctx 2-        h1 = keyHash ctx p1-        h2 = keyHash ctx p2+    let (k1, p1) = fixedKey 1+        (k2, p2) = fixedKey 2+        h1 = keyHash p1+        h2 = keyHash p2         op = coinAt 0-        tx = buildTx ctx [op] [(PayPKHash h1, 90000)]-        script = either error id . encodeOutput ctx+        tx = buildTx [op] [(PayPKHash h1, 90000)]+        script = either error id . encodeOutput         legacy code = either error id (txSigHash btc tx (script code) 100000 0 sigHashAll)         bip143 code = either error id (txSigHashForkId btc tx (script code) 100000 0 sigHashAll)-        sig digest k = TxSignature (signHash ctx k.key digest) sigHashAll-        owner sigi = either error id (signTx btc ctx tx [sigi] [k1.key])-        ownerNested sigi = either error id (signNestedWitnessTx btc ctx tx [sigi] [k1.key])+        sig digest k = TxSignature (signHash k.key digest) sigHashAll+        owner sigi = either error id (signTx btc tx [sigi] [k1.key])+        ownerNested sigi = either error id (signNestedWitnessTx btc tx [sigi] [k1.key])      it "refuses a P2PKH coin spent with another key" $ do       let coin = PayPKHash h1-          thief = withInputScript tx 0 (marshal (btc, ctx) (RegularInput (SpendPKHash (sig (legacy coin) k2) p2)))-      verifyStdInput btc ctx (owner (SigInput coin 100000 op sigHashAll Nothing)) [(coin, 100000, op)] 0 `shouldBe` True-      verifyStdInput btc ctx thief [(coin, 100000, op)] 0 `shouldBe` False+          thief = withInputScript tx 0 (marshal btc (RegularInput (SpendPKHash (sig (legacy coin) k2) p2)))+      verifyStdInput btc (owner (SigInput coin 100000 op sigHashAll Nothing)) [(coin, 100000, op)] 0 `shouldBe` True+      verifyStdInput btc thief [(coin, 100000, op)] 0 `shouldBe` False      it "refuses a P2SH coin spent with another redeem script" $ do       let coin = either error id (toP2SH (script (PayPK p1)))-          thief = withInputScript tx 0 (marshal (btc, ctx) (ScriptHashInput (SpendPK (sig (legacy (PayPK p2)) k2)) (PayPK p2)))-      verifyStdInput btc ctx (owner (SigInput coin 100000 op sigHashAll (Just (PayPK p1)))) [(coin, 100000, op)] 0 `shouldBe` True-      verifyStdInput btc ctx thief [(coin, 100000, op)] 0 `shouldBe` False+          thief = withInputScript tx 0 (marshal btc (ScriptHashInput (SpendPK (sig (legacy (PayPK p2)) k2)) (PayPK p2)))+      verifyStdInput btc (owner (SigInput coin 100000 op sigHashAll (Just (PayPK p1)))) [(coin, 100000, op)] 0 `shouldBe` True+      verifyStdInput btc thief [(coin, 100000, op)] 0 `shouldBe` False      it "refuses a P2WPKH coin spent with another key" $ do       let coin = PayWitnessPKHash h1-          thief = withWitness tx [[encodeTxSig btc ctx (sig (bip143 (PayPKHash h1)) k2), marshal ctx p2]]-      verifyStdInput btc ctx (owner (SigInput coin 100000 op sigHashAll Nothing)) [(coin, 100000, op)] 0 `shouldBe` True-      verifyStdInput btc ctx thief [(coin, 100000, op)] 0 `shouldBe` False+          thief = withWitness tx [[encodeTxSig btc (sig (bip143 (PayPKHash h1)) k2), encodeSerial p2]]+      verifyStdInput btc (owner (SigInput coin 100000 op sigHashAll Nothing)) [(coin, 100000, op)] 0 `shouldBe` True+      verifyStdInput btc thief [(coin, 100000, op)] 0 `shouldBe` False      it "refuses a P2WSH coin spent with another witness script" $ do       let own = PayMulSig [p1] 1           other = PayMulSig [p2] 1           coin = either error id (toP2WSH (script own))-          thief = withWitness tx [["", encodeTxSig btc ctx (sig (bip143 other) k2), runPutS (serialize (script other))]]-      verifyStdInput btc ctx (owner (SigInput coin 100000 op sigHashAll (Just own))) [(coin, 100000, op)] 0 `shouldBe` True-      verifyStdInput btc ctx thief [(coin, 100000, op)] 0 `shouldBe` False+          thief = withWitness tx [["", encodeTxSig btc (sig (bip143 other) k2), runPutS (serialize (script other))]]+      verifyStdInput btc (owner (SigInput coin 100000 op sigHashAll (Just own))) [(coin, 100000, op)] 0 `shouldBe` True+      verifyStdInput btc thief [(coin, 100000, op)] 0 `shouldBe` False      it "refuses a P2SH-P2WPKH coin spent with the program of another key" $ do       let coin = either error id (toP2SH (script (PayWitnessPKHash h1)))           thief =             withWitness-              (withInputScript tx 0 (marshal (btc, ctx) (NestedWitnessInput (PayWitnessPKHash h2))))-              [[encodeTxSig btc ctx (sig (bip143 (PayPKHash h2)) k2), marshal ctx p2]]-      verifyStdInput btc ctx (ownerNested (SigInput (PayWitnessPKHash h1) 100000 op sigHashAll Nothing)) [(coin, 100000, op)] 0 `shouldBe` True-      verifyStdInput btc ctx thief [(coin, 100000, op)] 0 `shouldBe` False+              (withInputScript tx 0 (marshal btc (NestedWitnessInput (PayWitnessPKHash h2))))+              [[encodeTxSig btc (sig (bip143 (PayPKHash h2)) k2), encodeSerial p2]]+      verifyStdInput btc (ownerNested (SigInput (PayWitnessPKHash h1) 100000 op sigHashAll Nothing)) [(coin, 100000, op)] 0 `shouldBe` True+      verifyStdInput btc thief [(coin, 100000, op)] 0 `shouldBe` False  {- What the signer refuses -} -signerSpec :: Ctx -> Spec-signerSpec ctx =+signerSpec :: Spec+signerSpec =   describe "What the signer refuses" $ do-    let (k1, p1) = fixedKey ctx 1-        (k2, _) = fixedKey ctx 2-        (k1u, p1u) = fixedKeyU ctx 1-        h1 = keyHash ctx p1+    let (k1, p1) = fixedKey 1+        (k2, _) = fixedKey 2+        (k1u, p1u) = fixedKeyU 1+        h1 = keyHash p1         op = coinAt 0         -- Two outputs, so that SIGHASH_SINGLE has one at the index of the input-        tx = buildTx ctx [op] [(PayPKHash h1, 50000), (PayPKHash h1, 40000)]-        signWith net coin sh = signTx net ctx tx [SigInput coin 100000 op sh Nothing] [k1.key]+        tx = buildTx [op] [(PayPKHash h1, 50000), (PayPKHash h1, 40000)]+        signWith net coin sh = signTx net tx [SigInput coin 100000 op sh Nothing] [k1.key]      it "signs the six hash types that a node accepts" $       forM_ [0x01, 0x02, 0x03, 0x81, 0x82, 0x83] $ \sh -> do@@ -1372,84 +1374,84 @@       signWith bch (PayPKHash h1) 0x21 `shouldBe` Left "makeSignature: the hash type 33 is not one a node accepts"       signed <- either fail return (signWith bch (PayPKHash h1) 0x01)       -- The signature is the first push of the input script, and its last byte the hash type-      fmap (\si -> case si of RegularInput (SpendPKHash (TxSignature _ sh) _) -> Just sh; _ -> Nothing) (unmarshal (bch, ctx) (head signed.inputs).script)+      fmap (\si -> case si of RegularInput (SpendPKHash (TxSignature _ sh) _) -> Just sh; _ -> Nothing) (unmarshal bch (head signed.inputs).script)         `shouldBe` Right (Just 0x41)      it "refuses a pay-to-script-hash coin whose redeem script is over 520 bytes" $ do-      let rdm = PayMulSig [snd (fixedKey ctx n) | n <- [1 .. 16]] 1+      let rdm = PayMulSig [snd (fixedKey n) | n <- [1 .. 16]] 1           -- OP_1, 16 keys of 34 bytes with their push, OP_16, OP_CHECKMULTISIG: 547 bytes-          h = addressHash (runPutS (serialize (either error id (encodeOutput ctx rdm))))-      signTx btc ctx tx [SigInput (PayScriptHash h) 100000 op sigHashAll (Just rdm)] [k1.key]+          h = addressHash (runPutS (serialize (either error id (encodeOutput rdm))))+      signTx btc tx [SigInput (PayScriptHash h) 100000 op sigHashAll (Just rdm)] [k1.key]         `shouldBe` Left "The redeem script is 547 bytes long, and a pay-to-script-hash redeem script can have at most 520"      it "refuses a pay-to-witness-script-hash coin whose witness script is over 10000 bytes" $ do       let rdm = DataCarrier [B.replicate 10000 0]           -- OP_RETURN, OP_PUSHDATA2 with its two length bytes, 10000 bytes: 10004-          h = sha256 (runPutS (serialize (either error id (encodeOutput ctx rdm))))-      makeSignature btc ctx tx 0 (SigInput (PayWitnessScriptHash h) 100000 op sigHashAll (Just rdm)) k1+          h = sha256 (runPutS (serialize (either error id (encodeOutput rdm))))+      makeSignature btc tx 0 (SigInput (PayWitnessScriptHash h) 100000 op sigHashAll (Just rdm)) k1         `shouldBe` Left "The witness script is 10004 bytes long, and a pay-to-witness-script-hash witness script can have at most 10000"      it "refuses a redeem script or a witness script that does not hash to the coin, and a coin without its script" $ do       let other = "0000000000000000000000000000000000000000" :: Hash160           other32 = "0000000000000000000000000000000000000000000000000000000000000000" :: Hash256           rdm = PayPK p1-      makeSignature btc ctx tx 0 (SigInput (PayScriptHash other) 100000 op sigHashAll (Just rdm)) k1+      makeSignature btc tx 0 (SigInput (PayScriptHash other) 100000 op sigHashAll (Just rdm)) k1         `shouldBe` Left "makeSignature: the redeem script does not hash to the coin"-      makeSignature btc ctx tx 0 (SigInput (PayWitnessScriptHash other32) 100000 op sigHashAll (Just rdm)) k1+      makeSignature btc tx 0 (SigInput (PayWitnessScriptHash other32) 100000 op sigHashAll (Just rdm)) k1         `shouldBe` Left "makeSignature: the witness script does not hash to the coin"-      makeSignature btc ctx tx 0 (SigInput (PayScriptHash other) 100000 op sigHashAll Nothing) k1+      makeSignature btc tx 0 (SigInput (PayScriptHash other) 100000 op sigHashAll Nothing) k1         `shouldBe` Left "makeSignature: a pay-to-script-hash coin needs its redeem script"-      makeSignature btc ctx tx 0 (SigInput (PayWitnessScriptHash other32) 100000 op sigHashAll Nothing) k1+      makeSignature btc tx 0 (SigInput (PayWitnessScriptHash other32) 100000 op sigHashAll Nothing) k1         `shouldBe` Left "makeSignature: a pay-to-witness-script-hash coin needs its witness script"      -- SCRIPT_VERIFY_WITNESS_PUBKEYTYPE of Bitcoin Core: no node relays a     -- SegWit version 0 spend with an uncompressed key     it "signTx refuses a SegWit coin of an uncompressed key, native, in a witness script or nested" $ do-      let hu = keyHash ctx p1u+      let hu = keyHash p1u           refusal = Left "sigKeys: a SegWit input is signed with a compressed key only, and this coin pays to an uncompressed key"-          wsh rdm = PayWitnessScriptHash (sha256 (runPutS (serialize (either error id (encodeOutput ctx rdm)))))-      signTx btc ctx tx [SigInput (PayWitnessPKHash hu) 100000 op sigHashAll Nothing] [k1.key] `shouldBe` refusal-      signNestedWitnessTx btc ctx tx [SigInput (PayWitnessPKHash hu) 100000 op sigHashAll Nothing] [k1.key] `shouldBe` refusal-      signTx btc ctx tx [SigInput (wsh (PayPK p1u)) 100000 op sigHashAll (Just (PayPK p1u))] [k1.key] `shouldBe` refusal-      signTx btc ctx tx [SigInput (wsh (PayMulSig [p1u] 1)) 100000 op sigHashAll (Just (PayMulSig [p1u] 1))] [k1.key] `shouldBe` refusal+          wsh rdm = PayWitnessScriptHash (sha256 (runPutS (serialize (either error id (encodeOutput rdm)))))+      signTx btc tx [SigInput (PayWitnessPKHash hu) 100000 op sigHashAll Nothing] [k1.key] `shouldBe` refusal+      signNestedWitnessTx btc tx [SigInput (PayWitnessPKHash hu) 100000 op sigHashAll Nothing] [k1.key] `shouldBe` refusal+      signTx btc tx [SigInput (wsh (PayPK p1u)) 100000 op sigHashAll (Just (PayPK p1u))] [k1.key] `shouldBe` refusal+      signTx btc tx [SigInput (wsh (PayMulSig [p1u] 1)) 100000 op sigHashAll (Just (PayMulSig [p1u] 1))] [k1.key] `shouldBe` refusal       -- The same key signs a legacy coin in its uncompressed form-      signTx btc ctx tx [SigInput (PayPKHash hu) 100000 op sigHashAll Nothing] [k1.key] `shouldSatisfy` isRight+      signTx btc tx [SigInput (PayPKHash hu) 100000 op sigHashAll Nothing] [k1.key] `shouldSatisfy` isRight      -- A block accepts such a spend, so one who knows what it does can still     -- make it, with the key in the form to use     it "signInput signs a SegWit coin with the uncompressed key it is given" $ do-      let hu = keyHash ctx p1u+      let hu = keyHash p1u           sigi = SigInput (PayWitnessPKHash hu) 100000 op sigHashAll Nothing-      signed <- either fail return (signInput btc ctx tx 0 sigi k1u)+      signed <- either fail return (signInput btc tx 0 sigi k1u)       map (map B.length) signed.witness `shouldSatisfy` (\w -> map (drop 1) w == [[65]])-      verifyStdInput btc ctx signed [(PayWitnessPKHash hu, 100000, op)] 0 `shouldBe` True+      verifyStdInput btc signed [(PayWitnessPKHash hu, 100000, op)] 0 `shouldBe` True      it "refuses to sign a SegWit or a Taproot coin on a network without SegWit" $ do-      let so = taprootScriptOutput ctx (TaprootOutput p1.point Nothing)+      let so = taprootScriptOutput (TaprootOutput p1.point Nothing)       signWith bch (PayWitnessPKHash h1) sigHashAll `shouldBe` Left "makeSignature: this network has no SegWit"-      signTx bch ctx tx [SigInput so 100000 op sigHashDefault Nothing] [k1.key] `shouldBe` Left "signTx: this network has no Taproot"+      signTx bch tx [SigInput so 100000 op sigHashDefault Nothing] [k1.key] `shouldBe` Left "signTx: this network has no Taproot"      it "signInput refuses a key that is not a key of the coin" $ do-      signInput btc ctx tx 0 (SigInput (PayPKHash h1) 100000 op sigHashAll Nothing) k2 `shouldBe` Left "signInput: the key is not a key of the coin"-      signInput btc ctx tx 0 (SigInput (PayWitnessPKHash h1) 100000 op sigHashAll Nothing) k2 `shouldBe` Left "signInput: the key is not a key of the coin"-      signInput btc ctx tx 0 (SigInput (PayMulSig [p1] 1) 100000 op sigHashAll Nothing) k2 `shouldBe` Left "signInput: the key is not a key of the coin"-      signInput btc ctx tx 0 (SigInput (PayPKHash h1) 100000 op sigHashAll Nothing) k1 `shouldSatisfy` isRight+      signInput btc tx 0 (SigInput (PayPKHash h1) 100000 op sigHashAll Nothing) k2 `shouldBe` Left "signInput: the key is not a key of the coin"+      signInput btc tx 0 (SigInput (PayWitnessPKHash h1) 100000 op sigHashAll Nothing) k2 `shouldBe` Left "signInput: the key is not a key of the coin"+      signInput btc tx 0 (SigInput (PayMulSig [p1] 1) 100000 op sigHashAll Nothing) k2 `shouldBe` Left "signInput: the key is not a key of the coin"+      signInput btc tx 0 (SigInput (PayPKHash h1) 100000 op sigHashAll Nothing) k1 `shouldSatisfy` isRight      it "signTaprootInput refuses a key that is not the key of the output, and an output that is not Taproot" $ do-      let so = taprootScriptOutput ctx (TaprootOutput p1.point Nothing)-          spent = [TxOut 100000 (marshal ctx so)]-          tweaked = fromJust (taprootOutputSecKey ctx k1.key Nothing)+      let so = taprootScriptOutput (TaprootOutput p1.point Nothing)+          spent = [TxOut 100000 (encodeSerial so)]+          tweaked = fromJust (taprootOutputSecKey k1.key Nothing)       -- The internal key is not the key of the output: its tweak is-      signTaprootInput ctx tx spent 0 sigHashDefault k1.key `shouldBe` Left "signTaprootInput: the key is not the key of the output"-      signTaprootInput ctx tx spent 0 sigHashDefault tweaked `shouldSatisfy` isRight-      signTaprootInput ctx tx [TxOut 100000 (marshal ctx (PayWitnessPKHash h1))] 0 sigHashDefault tweaked+      signTaprootInput tx spent 0 sigHashDefault k1.key `shouldBe` Left "signTaprootInput: the key is not the key of the output"+      signTaprootInput tx spent 0 sigHashDefault tweaked `shouldSatisfy` isRight+      signTaprootInput tx [TxOut 100000 (encodeSerial (PayWitnessPKHash h1))] 0 sigHashDefault tweaked         `shouldBe` Left "signTaprootInput: the output spent is not a Taproot output"      it "refuses to sign a SegWit input of a transaction whose witness list does not match its inputs" $ do-      let two = buildTx ctx [op, coinAt 1] [(PayPKHash h1, 90000)]+      let two = buildTx [op, coinAt 1] [(PayPKHash h1, 90000)]           sigi = SigInput (PayWitnessPKHash h1) 100000 (coinAt 1) sigHashAll Nothing           ms = PayMulSig [p1] 1-          wsh = either error id (toP2WSH =<< encodeOutput ctx ms)-      signTx btc ctx (withWitness two [[]]) [sigi] [k1.key] `shouldBe` Left "Invalid number of witness stacks"-      signTx btc ctx (withWitness two [[]]) [SigInput wsh 100000 (coinAt 1) sigHashAll (Just ms)] [k1.key] `shouldBe` Left "Invalid number of witness stacks"-      signTx btc ctx two [sigi] [k1.key] `shouldSatisfy` isRight+          wsh = either error id (toP2WSH =<< encodeOutput ms)+      signTx btc (withWitness two [[]]) [sigi] [k1.key] `shouldBe` Left "Invalid number of witness stacks"+      signTx btc (withWitness two [[]]) [SigInput wsh 100000 (coinAt 1) sigHashAll (Just ms)] [k1.key] `shouldBe` Left "Invalid number of witness stacks"+      signTx btc two [sigi] [k1.key] `shouldSatisfy` isRight
+ test/Haskoin/Util/DirectSpec.hs view
@@ -0,0 +1,379 @@+{-# LANGUAGE ExistentialQuantification #-}+{-# LANGUAGE ImportQualifiedPost #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | "Haskoin.Util.Direct" promises that its functions give what cereal+-- gives, only faster. The serializers of transactions, blocks, hashes and+-- addresses go through them, so these tests are what shows that no byte+-- and no error changed when they did.+--+-- The reference is always the same serializer run in the monad of cereal+-- with 'runPutS' or 'runGetS', which is the code that the library ran+-- before and that nothing here replaced. The first half checks the three+-- monads operation by operation, on programs made of every method of+-- 'MonadPut' and 'MonadGet'. The second half checks the types: that+-- cereal, binary, 'Serial', 'encodeSerial' and 'decodeSerial' agree on the+-- bytes, read them back, and report the same error for bytes that are cut+-- short, changed or followed by others.+module Haskoin.Util.DirectSpec (spec) where++import Control.Monad (replicateM, unless)+import Crypto.Hash (SHA256 (..), hashWith)+import Data.Binary qualified as Binary+import Data.ByteArray qualified as BA+import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.ByteString.Lazy qualified as L+import Data.ByteString.Short (ShortByteString, fromShort, toShort)+import Data.Bytes.Get+import Data.Bytes.Put+import Data.Bytes.Serial (Serial (..))+import Data.Serialize qualified as Cereal+import Data.Typeable (Proxy (..), Typeable, typeRep)+import Data.Word (Word16, Word32, Word64, Word8)+import Haskoin.Block+import Haskoin.Crypto+import Haskoin.Transaction+import Haskoin.Util+import Haskoin.Util.Arbitrary+import Haskoin.Util.Direct+import Test.Hspec+import Test.Hspec.QuickCheck+import Test.QuickCheck++spec :: Spec+spec = do+  describe "Haskoin.Util.Direct" $ do+    describe "writing" $ do+      prop "encodeDirect gives the bytes of runPutS" $+        forAll (listOf arbitraryOp) $ \ops ->+          encodeDirect (mapM_ write ops) === runPutS (mapM_ write ops)+      prop "sizeDirect gives their length" $+        forAll (listOf arbitraryOp) $ \ops ->+          sizeDirect (mapM_ write ops) === B.length (runPutS (mapM_ write ops))+      prop "putDirect writes them in the middle of a cereal serializer" $+        forAll (listOf arbitraryOp) $ \ops ->+          Cereal.runPut (Cereal.putWord8 1 >> putDirect (mapM_ write ops) >> Cereal.putWord8 2)+            === Cereal.runPut (Cereal.putWord8 1 >> mapM_ write ops >> Cereal.putWord8 2)+      prop "putShortBytes writes the bytes of a short byte string in every monad" $+        forAll arbitraryBSS $ \s -> do+          runPutS (putShortBytes s) `shouldBe` fromShort s+          L.toStrict (runPutL (putShortBytes s)) `shouldBe` fromShort s+          encodeDirect (putShortBytes s) `shouldBe` fromShort s+          sizeDirect (putShortBytes s) `shouldBe` B.length (fromShort s)+    describe "reading" $ do+      prop "decodeDirect gives the result of runGetS on the bytes that were written" $+        forAll arbitraryProgram $ \(steps, bytes) ->+          decodeDirect (mapM look steps) bytes === runGetS (mapM look steps) bytes+      prop "decodeDirect gives the result of runGetS on any bytes, errors included" $+        forAll arbitraryProgram $ \(steps, _) -> forAll arbitraryBS $ \bytes ->+          decodeDirect (mapM look steps) bytes === runGetS (mapM look steps) bytes+      prop "decodeDirect gives the result of runGetS on bytes cut short" $+        forAll arbitraryProgram $ \(steps, bytes) -> forAll (choose (0, B.length bytes)) $ \n ->+          decodeDirect (mapM look steps) (B.take n bytes) === runGetS (mapM look steps) (B.take n bytes)+      prop "getDirect reads what the parser reads in cereal, and leaves the same input" $+        forAll arbitraryProgram $ \(steps, bytes) -> forAll arbitraryBS $ \more ->+          Cereal.runGetState (getDirect (mapM look steps)) (bytes <> more) 0+            === Cereal.runGetState (mapM look steps) (bytes <> more) 0+      prop "getDirect reads input that arrives in pieces as cereal does" $+        forAll arbitraryProgram $ \(steps, bytes) -> forAll (pieces bytes) $ \chunks ->+          feed (getDirect (mapM look steps)) chunks === feed (mapM look steps) chunks+      prop "getShortBytes reads what getByteString reads" $+        forAll arbitraryBS $ \bytes -> forAll (choose (-1, B.length bytes + 1)) $ \n -> do+          runGetS (getShortBytes n) bytes `shouldBe` toShort <$> runGetS (getByteString n) bytes+          decodeDirect (getShortBytes n) bytes `shouldBe` toShort <$> runGetS (getByteString n) bytes+  describe "Encodings of the types that go through Haskoin.Util.Direct" $+    mapM_+      codec+      [ Box arbitraryTxHash,+        Box arbitraryBlockHash,+        Box arbitraryHash160,+        Box arbitraryHash256,+        Box arbitraryHash512,+        Box arbitraryVarInt,+        Box arbitraryOutPoint,+        Box (arbitraryTxIn =<< arbitraryNetwork),+        Box (arbitraryTxOut =<< arbitraryNetwork),+        Box (arbitraryTx =<< arbitraryNetwork),+        Box arbitraryBlockHeader,+        Box (arbitraryBlock =<< arbitraryNetwork),+        Box (arbitraryAddress =<< arbitraryNetwork)+      ]+  describe "Functions that write a value to hash or to measure it" $ do+    prop "encodeSerial and decodeSerial of a transaction, compiled for it" $+      forAll (arbitraryTx =<< arbitraryNetwork) $ \tx -> do+        encodeSerial tx `shouldBe` runPutS (serialize tx)+        decodeSerial (runPutS (serialize tx)) `shouldBe` Right tx+        decodeTx (runPutS (serialize tx)) `shouldBe` Right tx+        decodeTx (runPutS (serialize tx) <> B.singleton 0) `shouldBe` Left trailing+    prop "encodeSerial and decodeSerial of an outpoint, compiled for it" $+      forAll arbitraryOutPoint $ \o -> do+        encodeSerial o `shouldBe` runPutS (serialize o)+        decodeSerial (runPutS (serialize o)) `shouldBe` Right o+    prop "txHash is the double SHA-256 of the transaction without its witness" $+      forAll (arbitraryTx =<< arbitraryNetwork) $ \tx ->+        txHash tx === TxHash (reference (runPutS (serialize (stripped tx))))+    prop "txWitnessHash is the double SHA-256 of the whole transaction" $+      forAll (arbitraryTx =<< arbitraryNetwork) $ \tx ->+        txWitnessHash tx === TxHash (reference (runPutS (serialize tx)))+    prop "txWeight is three times the size without the witness plus the size with it" $+      forAll (arbitraryTx =<< arbitraryNetwork) $ \tx ->+        txWeight tx+          === 3 * B.length (runPutS (serialize (stripped tx))) + B.length (runPutS (serialize tx))+    prop "headerHash is the double SHA-256 of the header" $+      forAll arbitraryBlockHeader $ \h ->+        headerHash h === BlockHash (reference (runPutS (serialize h)))+    prop "sha256 and doubleSHA256 give the digests of crypton for bytes of any length" $+      forAll (choose (0, 300)) $ \n -> forAll (arbitraryBSn n) $ \bytes -> do+        (sha256 bytes).get `shouldBe` toShort (BA.convert (hashWith SHA256 bytes))+        (doubleSHA256 bytes).get `shouldBe` (reference bytes).get+        -- a kind of bytes other than the one the functions are compiled for+        (sha256 (BA.convert bytes :: BA.Bytes)).get `shouldBe` (sha256 bytes).get+        (doubleSHA256 (BA.convert bytes :: BA.Bytes)).get `shouldBe` (doubleSHA256 bytes).get+  where+    trailing = "Failed reading: Trailing bytes after transaction\nEmpty call stack\n"+    stripped :: Tx -> Tx+    stripped (Tx v i o _ l) = Tx v i o [] l++-- | Two rounds of SHA-256 through the pure interface of crypton, as+-- 'doubleSHA256' was written before it called the C code itself.+reference :: ByteString -> Hash256+reference bytes =+  either error id . runGetS deserialize . BA.convert $ hashWith SHA256 (hashWith SHA256 bytes)++-- Programs++-- | One method of 'MonadPut', with what it writes.+data Op+  = W8 Word8+  | W16le Word16+  | W16be Word16+  | W16host Word16+  | W32le Word32+  | W32be Word32+  | W32host Word32+  | W64le Word64+  | W64be Word64+  | W64host Word64+  | Whost Word+  | Bytes ByteString+  | Lazy [ByteString]+  | Short ShortByteString+  | Flush+  deriving (Eq, Show)++arbitraryOp :: Gen Op+arbitraryOp =+  oneof+    [ W8 <$> arbitrary,+      W16le <$> arbitrary,+      W16be <$> arbitrary,+      W16host <$> arbitrary,+      W32le <$> arbitrary,+      W32be <$> arbitrary,+      W32host <$> arbitrary,+      W64le <$> arbitrary,+      W64be <$> arbitrary,+      W64host <$> arbitrary,+      Whost <$> arbitrary,+      Bytes <$> arbitraryBS,+      Lazy <$> listOf arbitraryBS,+      Short <$> arbitraryBSS,+      pure Flush+    ]++write :: (MonadPut m) => Op -> m ()+write op = case op of+  W8 w -> putWord8 w+  W16le w -> putWord16le w+  W16be w -> putWord16be w+  W16host w -> putWord16host w+  W32le w -> putWord32le w+  W32be w -> putWord32be w+  W32host w -> putWord32host w+  W64le w -> putWord64le w+  W64be w -> putWord64be w+  W64host w -> putWord64host w+  Whost w -> putWordhost w+  Bytes b -> putByteString b+  Lazy bs -> putLazyByteString (L.fromChunks bs)+  Short s -> putShortBytes s+  Flush -> flush++-- | One step of a parser: a method of 'MonadGet', or a few of them inside+-- one of the methods that look ahead.+data Step+  = -- | read back what the operation wrote+    Back Op+  | Slice Int+  | Copy Int+  | Skip Int+  | Ahead [Step]+  | -- | look ahead, and keep the input or not+    AheadM Bool [Step]+  | AheadE Bool [Step]+  | Empty+  | Remaining+  | Ensure Int+  | LazyBytes Int+  | Fail+  deriving (Eq, Show)++-- | What a step saw.+data Seen+  = Number Integer+  | Chunk ByteString+  | Flag Bool+  | Many [Seen]+  deriving (Eq, Show)++look :: (MonadGet m) => Step -> m Seen+look step = case step of+  Back op -> case op of+    W8 _ -> number <$> getWord8+    W16le _ -> number <$> getWord16le+    W16be _ -> number <$> getWord16be+    W16host _ -> number <$> getWord16host+    W32le _ -> number <$> getWord32le+    W32be _ -> number <$> getWord32be+    W32host _ -> number <$> getWord32host+    W64le _ -> number <$> getWord64le+    W64be _ -> number <$> getWord64be+    W64host _ -> number <$> getWord64host+    Whost _ -> number <$> getWordhost+    Bytes b -> Chunk <$> getByteString (B.length b)+    Lazy bs -> Chunk <$> getBytes (sum (map B.length bs))+    Short s -> Chunk . fromShort <$> getShortBytes (B.length (fromShort s))+    Flush -> pure (Many [])+  Slice n -> Chunk <$> getBytes n+  Copy n -> Chunk <$> getByteString n+  Skip n -> Many [] <$ skip n+  Ahead steps -> Many <$> lookAhead (mapM look steps)+  AheadM keep steps ->+    maybe (Flag False) Many <$> lookAheadM ((if keep then Just else const Nothing) <$> mapM look steps)+  AheadE keep steps ->+    either Many Many <$> lookAheadE ((if keep then Right else Left) <$> mapM look steps)+  Empty -> Flag <$> isEmpty+  Remaining -> number <$> remaining+  Ensure n -> number . B.length <$> ensure n+  LazyBytes n -> Chunk . L.toStrict <$> getLazyByteString (fromIntegral n)+  Fail -> fail "a step that fails"+  where+    number :: (Integral a) => a -> Seen+    number = Number . toInteger++-- | A parser and bytes that it reads to the end, unless one of its steps+-- fails: the steps that read back what a list of operations wrote, with+-- steps that read nothing put between them.+arbitraryProgram :: Gen ([Step], ByteString)+arbitraryProgram = do+  ops <- listOf arbitraryOp+  steps <- concat <$> mapM around ops+  return (steps, runPutS (mapM_ write ops))+  where+    around op = do+      extra <- frequency [(3, pure []), (1, pure <$> idle)]+      return (Back op : extra)+    -- steps that leave the position where it is, most of the time+    idle =+      oneof+        [ Slice <$> choose (-1, 2),+          Copy <$> choose (-1, 2),+          Skip <$> choose (-1, 2),+          Ahead <$> some,+          AheadM <$> arbitrary <*> some,+          AheadE <$> arbitrary <*> some,+          pure Empty,+          pure Remaining,+          Ensure <$> choose (0, 3),+          LazyBytes <$> choose (0, 2),+          frequency [(1, pure Fail), (5, pure Empty)]+        ]+    some = do+      n <- choose (0, 3)+      replicateM n (oneof [Back <$> arbitraryOp, Slice <$> choose (0, 3), pure Empty, pure Remaining])++-- | The bytes cut into pieces at random places.+pieces :: ByteString -> Gen [ByteString]+pieces bytes+  | B.null bytes = pure []+  | otherwise = do+      n <- choose (1, B.length bytes)+      (B.take n bytes :) <$> pieces (B.drop n bytes)++-- | Run a cereal parser on input that arrives in pieces and then ends. The+-- result is the value with the input left over, or the error.+feed :: Cereal.Get a -> [ByteString] -> Either String (a, ByteString)+feed parser = go (Cereal.runGetPartial parser)+  where+    go continue chunks = case continue (headOr chunks) of+      Cereal.Done a rest -> Right (a, rest <> mconcat (drop 1 chunks))+      Cereal.Fail message _ -> Left message+      Cereal.Partial more+        | null chunks -> Left "the parser wants input after the end"+        | otherwise -> go more (drop 1 chunks)+    headOr = foldr const B.empty++-- Types++data Box+  = forall a.+    (Show a, Eq a, Typeable a, Serial a, Cereal.Serialize a, Binary.Binary a) =>+    Box (Gen a)++-- | Bytes that are not what was written: cut short, with a byte changed,+-- or with bytes after them.+damaged :: ByteString -> Gen ByteString+damaged bytes =+  oneof+    [ (`B.take` bytes) <$> choose (0, B.length bytes),+      change <$> choose (0, max 0 (B.length bytes - 1)) <*> arbitrary,+      (bytes <>) <$> arbitraryBS1,+      arbitraryBS+    ]+  where+    change i w = B.take i bytes <> B.pack [w | i < B.length bytes] <> B.drop (i + 1) bytes++codec :: Box -> Spec+codec (Box (gen :: Gen a)) = describe (show (typeRep (Proxy :: Proxy a))) $ do+  prop "cereal, binary, Serial and encodeSerial give the same bytes" $+    forAll gen $ \x -> do+      let bytes = runPutS (serialize x)+      Cereal.encode x `shouldBe` bytes+      L.toStrict (Binary.encode x) `shouldBe` bytes+      L.toStrict (runPutL (serialize x)) `shouldBe` bytes+      encodeSerial x `shouldBe` bytes+      encodeDirect (serialize x) `shouldBe` bytes+      sizeDirect (serialize x) `shouldBe` B.length bytes+  prop "cereal, binary, Serial and decodeSerial read them back" $+    forAll gen $ \x -> do+      let bytes = runPutS (serialize x)+      Cereal.decode bytes `shouldBe` Right x+      Binary.decode (L.fromStrict bytes) `shouldBe` x+      runGetS deserialize bytes `shouldBe` Right x+      runGetL deserialize (L.fromStrict bytes) `shouldBe` x+      decodeSerial bytes `shouldBe` Right x+      decodeDirect deserialize bytes `shouldBe` Right x+  prop "cereal and decodeSerial give the result of the Serial parser on damaged bytes" $+    forAll gen $ \x -> forAll (damaged (runPutS (serialize x))) $ \bytes -> do+      Cereal.decode bytes `shouldBe` (runGetS deserialize bytes :: Either String a)+      decodeDirect deserialize bytes `shouldBe` (runGetS deserialize bytes :: Either String a)+      decodeSerial bytes `shouldBe` (runGetS whole bytes :: Either String a)+  prop "cereal reads the value from input that arrives in pieces" $+    forAll gen $ \x -> forAll arbitraryBS $ \more -> forAll (pieces (runPutS (serialize x) <> more)) $+      \chunks -> do+        feed Cereal.get chunks `shouldBe` Right (x, more)+        feed deserialize chunks `shouldBe` Right (x, more)+  prop "cereal reads damaged input that arrives in pieces as the Serial parser does" $+    forAll gen $ \x -> forAll (damaged (runPutS (serialize x)) >>= pieces) $ \chunks ->+      feed Cereal.get chunks `shouldBe` (feed deserialize chunks :: Either String (a, ByteString))+  where+    -- what decodeSerial was before it read the bytes directly+    whole :: (Serial b) => Cereal.Get b+    whole = do+      value <- deserialize+      done <- isEmpty+      unless done $ fail "decodeSerial: bytes left over after the value"+      return value
test/Haskoin/UtilSpec.hs view
@@ -9,19 +9,18 @@ module Haskoin.UtilSpec (spec) where  import Control.Exception (ErrorCall, evaluate)-import System.Timeout (timeout) import Control.Monad.Except (ExceptT, runExceptT) import Data.Aeson import Data.Aeson.Encoding (encodingToLazyByteString) import Data.ByteString (ByteString) import Data.ByteString qualified as B import Data.ByteString.Builder (byteStringHex, lazyByteStringHex, toLazyByteString)+import Data.ByteString.Char8 qualified as C import Data.ByteString.Lazy qualified as BL import Data.ByteString.Short qualified as SBS-import Data.Text.Encoding qualified as TE-import Data.Text.Lazy.Encoding qualified as TLE import Data.Bytes.Get import Data.Bytes.Put+import Data.Bytes.Serial (deserialize, serialize) import Data.Default (def) import Data.Either (isLeft) import Data.Foldable (toList)@@ -31,11 +30,16 @@ import Data.Maybe import Data.Sequence qualified as Seq import Data.Serialize qualified as S+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import Data.Text.Lazy.Encoding qualified as TLE import Data.Word (Word8) import GHC.Generics (Generic) import Haskoin.Crypto+import Haskoin.Network.Constants (btc) import Haskoin.Util import Haskoin.Util.Arbitrary+import System.Timeout (timeout) import Test.Hspec import Test.Hspec.QuickCheck import Test.QuickCheck@@ -68,7 +72,7 @@   parseJSON = genericParseJSON (dropSumLabels 1 2 "type")  spec :: Spec-spec = prepareContext $ \ctx ->+spec =   describe "utility functions" $ do     testIdentity identityTests @@ -104,9 +108,19 @@         encodingToLazyByteString (hexEncoding "\xab\xcd") `shouldBe` "\"abcd\""         toLazyByteString (hexBuilder "\xab\xcd") `shouldBe` "abcd"       prop "decodeHex . encodeHex" $ forAll arbitraryBS fromToHex-      -- the table-based hex against the hex of the builder of bytestring,-      -- byte by byte, on every byte value and on chunks of every size-      -- either side of where the builder's own hex takes over+      -- every byte value against digits worked out here, without a table:+      -- the library takes its digits from the table of bytestring, so the+      -- builder of bytestring alone would not be an independent check+      it "writes every byte value as its two lowercase digits" $ do+        let every = B.pack [0 .. 255]+            digit n = "0123456789abcdef" !! n+            digits = concat [[digit (n `div` 16), digit (n `mod` 16)] | n <- [0 .. 255]]+        encodeHexBytes every `shouldBe` C.pack digits+        encodeHex every `shouldBe` T.pack digits+        toLazyByteString (hexBuilder (BL.fromStrict every)) `shouldBe` BL.fromStrict (C.pack digits)+        encodeHexReversed (SBS.toShort (B.reverse every)) `shouldBe` T.pack digits+      -- and against the hex of the builder of bytestring, on chunks of+      -- every size       it "writes every byte value as the builder of bytestring does" $ do         let every = B.pack [0 .. 255]             reference = BL.toStrict (toLazyByteString (byteStringHex every))@@ -313,22 +327,36 @@      describe "Marshalling" $ do       let key = fromJust (secKey (B.replicate 32 1))-          public = PublicKey (derivePubKey ctx key) True+          public = PublicKey (derivePubKey key) True+          xprv = makeXPrvKey (B.replicate 32 1)       it "marshal and unmarshal round trip, strict and lazy" $ do-        unmarshal ctx (marshal ctx public) `shouldBe` Right public-        unmarshalLazy ctx (marshalLazy ctx public) `shouldBe` Right public-        (unmarshalLazy ctx "junk" :: Either String PublicKey) `shouldSatisfy` isLeft+        unmarshal btc (marshal btc xprv) `shouldBe` Right xprv+        unmarshalLazy btc (marshalLazy btc xprv) `shouldBe` Right xprv+        (unmarshalLazy btc "junk" :: Either String XPrvKey) `shouldSatisfy` isLeft       it "unmarshal refuses bytes after the value, strict and lazy" $ do+        let bytes = marshal btc xprv <> "\xff"+        (unmarshal btc bytes :: Either String XPrvKey)+          `shouldSatisfy` either ("bytes left over" `isInfixOf`) (const False)+        (unmarshalLazy btc (BL.fromStrict bytes) :: Either String XPrvKey)+          `shouldSatisfy` either ("bytes left over" `isInfixOf`) (const False)+      it "encodeSerial and decodeSerial round trip" $ do+        decodeSerial (encodeSerial public) `shouldBe` Right public+        encodeSerial public `shouldBe` runPutS (serialize public)+        (decodeSerial "junk" :: Either String PublicKey) `shouldSatisfy` isLeft+      it "decodeSerial refuses bytes after the value, which deserialize leaves" $ do         -- the compressed public key of secret key 1, then one more byte         let bytes = fromJust (decodeHex "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798ff")-        (unmarshal ctx bytes :: Either String PublicKey)-          `shouldSatisfy` either ("bytes left over" `isInfixOf`) (const False)-        (unmarshalLazy ctx (BL.fromStrict bytes) :: Either String PublicKey)+        (decodeSerial bytes :: Either String PublicKey)           `shouldSatisfy` either ("bytes left over" `isInfixOf`) (const False)+        fmap encodeSerial (runGetS deserialize bytes :: Either String PublicKey) `shouldBe` Right (B.init bytes)       it "marshalJSON and unmarshalJSON round trip, and refuse what is not the value" $ do-        unmarshalJSON ctx (marshalJSON ctx public) `shouldBe` Just public-        (unmarshalJSON ctx "\"junk\"" :: Maybe PublicKey) `shouldBe` Nothing-        (unmarshalJSON ctx "{" :: Maybe PublicKey) `shouldBe` Nothing+        unmarshalJSON btc (marshalJSON btc xprv) `shouldBe` Just xprv+        (unmarshalJSON btc "\"junk\"" :: Maybe XPrvKey) `shouldBe` Nothing+        (unmarshalJSON btc "{" :: Maybe XPrvKey) `shouldBe` Nothing+      it "the JSON of a public key round trips, and refuses what is not the value" $ do+        decode (encode public) `shouldBe` Just public+        (decode "\"junk\"" :: Maybe PublicKey) `shouldBe` Nothing+        (decode "{" :: Maybe PublicKey) `shouldBe` Nothing      describe "Test helpers" $ do       it "customCerealID tells whether a getter reads what a putter writes" $ do