haskoin-core

Bitcoin & Bitcoin Cash library for Haskell

http://github.com/jprupp/haskoin-core#readme

Version on this page:3.0.0
LTS Haskell 24.69:1.2.2
Stackage Nightly 2026-11-30:3.0.0
Latest on Hackage:3.0.1

See all snapshots haskoin-core appears in

MIT licensed by JP Rupp
Maintained by [email protected]
This version can be pinned in stack with:haskoin-core-3.0.0@sha256:23985edfb8c6a32d56dd51318e9b8e9ae6ac252a83669ad2d4525f850ec1e154,8578

Module documentation for 3.0.0

Haskoin Core

CI Hackage License: MIT

Haskoin Core is a Bitcoin and Bitcoin Cash library for Haskell. It covers keys, addresses, scripts, transactions, PSBTs, block headers and the peer-to-peer message format.

It does no I/O of its own. It never opens a socket or writes a file. You can use it in a wallet, a block explorer or a node, and bring your own networking and storage.

Contents

Features

Area What you get
Networks Bitcoin and Bitcoin Cash: mainnet, testnet3, testnet4 and regtest; Bitcoin testnet3 is deprecated
Keys secp256k1 keys, WIF, BIP-32 extended keys and paths, BIP-39 mnemonics, SLIP-39 Shamir shares
Signatures Deterministic ECDSA (RFC 6979) and BIP-340 Schnorr
Addresses Base58, Bech32, Bech32m and CashAddr, including P2SH32 and the token-aware CashAddr types
Scripts Script parsing and serialization, standard templates, BIP-67 sorted multisig, the CashTokens prefix
Transactions Building, signing and verifying P2PK, P2PKH, P2SH, multisig, P2WPKH, P2WSH, nested SegWit and Taproot key path spends
Wallet tools Coin selection, and weight, size and fee estimates
PSBT Versions 0 and 2, with the Taproot fields (BIP-174, BIP-370, BIP-371)
Taproot Script trees, output keys, witnesses, control blocks and signature hashes (BIP-341, BIP-342)
Blocks Header validation, proof of work, the difficulty rules of both chains, Merkle trees and an in-memory header chain
Peer-to-peer Message encoding, including addrv2, compact blocks and compact filter messages, and BIP-37 Bloom filters
Protocol State machines of how Bitcoin Core and Bitcoin Cash Node treat a peer, one per network
Testing QuickCheck generators for the library’s types

What is not included

  • Peer connections and chain sync. Use haskoin-node.
  • Address and transaction indexing. Use haskoin-store.
  • A script interpreter. verifyStdTx recognises the standard templates. It is not a consensus check.
  • Signet, output descriptors, Miniscript and MuSig2.
  • Signing with Schnorr signatures, SIGHASH_UTXOS and token outputs of Bitcoin Cash. judgeInputs verifies a Schnorr signature, of one key or in a multisig, and the spend of a coin that holds tokens. Nothing here signs them, and verifyStdTx does not read them. The tokens of an output and its address are read: see Bitcoin Cash.
  • BIP-324 encrypted transport.
  • BIP-39 word lists other than English.

Installation

System library

Haskoin Core needs libsecp256k1 0.2.0 or later, and pkg-config to find it.

# Debian and Ubuntu
sudo apt-get install libsecp256k1-dev pkg-config

# macOS with Homebrew
brew install secp256k1 pkg-config

# Nix
nix-shell -p secp256k1 pkg-config

Check what you have with pkg-config --modversion libsecp256k1. Debian 11 and other older systems ship a version below 0.2.0. On those, build the library from source and enable its recovery module with ./configure --enable-module-recovery.

Compiler

The library is tested with GHC 9.10 and 9.12. It cannot build below GHC 9.2, because it uses OverloadedRecordDot.

With Cabal

Add the packages to your .cabal file:

build-depends:
    base
  , bytes
  , haskoin-core
  , text

You need bytes to serialize values with runPutS and serialize.

Run cabal update first. Haskoin Core needs a recent secp256k1-haskell, and a stale package index makes the build fail with a dependency error.

With Stack

Haskoin Core is not in Stackage, so add it to stack.yaml as an extra dependency. Use the latest version from Hackage.

resolver: nightly-2026-10-28
extra-deps:
  - haskoin-core-3.0.0
  - base16-2.0
  - secp256k1-haskell-3.0.0

Quick start

This program turns a mnemonic into the first receiving address of a BIP-84 wallet.

{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings #-}

module Main (main) where

import Data.Text (Text)
import Haskoin

-- This is the public BIP-39 test mnemonic. Never send coins to it.
mnemonic :: Text
mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"

main :: IO ()
main = do
  seed <- either fail pure (mnemonicToSeed "" mnemonic)
  let master = makeXPrvKey seed
      -- Hardened steps need the private key.
      account = derivePath ("m/84'/0'/0'" :: HardPath) master
      accountPub = deriveXPubKey account
      -- The remaining steps only need the public key.
      receiving = derivePubPath ("m/0" :: SoftPath) accountPub
      (address, _publicKey) = deriveWitnessAddr receiving 0
  print (addrToText btc address)
  -- => Just "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu"

The address is the one that BIP-84 publishes for this mnemonic.

Concepts

A few conventions apply across the whole library. Reading this section first will save you time.

No context to pass

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 their first argument.

Value Chain Name for netByName
btc Bitcoin mainnet btc
btcTest Bitcoin testnet3 btctest
btcTest4 Bitcoin testnet4 btctest4
btcRegTest Bitcoin regtest btcreg
bch Bitcoin Cash mainnet bch
bchTest3 Bitcoin Cash testnet3 bchtest3
bchTest4 Bitcoin Cash testnet4 bchtest4
bchRegTest Bitcoin Cash regtest bchreg

btcTest, Bitcoin testnet3, is deprecated: using it gives a warning when you compile. Bitcoin Core has deprecated testnet3 in favour of testnet4, whose BIP94 rules stop the storms of minimum-difficulty blocks that made testnet3 hard to use, and will remove it. Use btcTest4 instead. btcTest is still in allNets and netByName still finds it, so that code reading old testnet3 data keeps working; a later major version will remove it. bchTest3 is not deprecated: Bitcoin Cash Node still supports testnet3.

The Bitcoin Cash testnet3 carries its number, bchTest3 and bchtest3, as testnet4 does, so that neither looks like the default test network of Bitcoin Cash. Before 3.0.0 it was bchTest and bchtest. Its CashAddr prefix is still bchtest, which every Bitcoin Cash test network shares.

The constants of each network are those of the reference node: Bitcoin Core 32.1 for Bitcoin and Bitcoin Cash Node 29.2.0 for Bitcoin Cash. Bitcoin Core has no checkpoints, so the Bitcoin networks have none either.

Record fields

The library is built with NoFieldSelectors, so record fields are not functions. Turn on OverloadedRecordDot in your modules and read fields with a dot.

print btc.defaultPort
-- => 8333
print (map (.value) btc.genesisTx.outputs)
-- => [5000000000]

Many records share field names. Tx and Psbt both have inputs, for example. To update such a field, import the module qualified and name the field through it, as the PSBT example does.

Errors

Functions that can fail return Maybe or Either String. The examples below turn those into IO failures with either fail pure.

Hashes, paths and public keys have IsString instances, so you can write them as literals. Those instances call error on bad input. For input you do not control, use hexToTxHash, hexToBlockHash, parsePath and textToAddr.

Amounts

Amounts are satoshi, as Word64.

Serialization

Most types have Serial instances, from the bytes package, and also Binary and 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, 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 network marshalJSON net x unmarshalJSON net json

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).

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.

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 form that Bitcoin Core and block explorers display, so you can paste those values straight in. The serialized bytes keep the internal order.

Usage guide

The examples below are fragments of main in this program. Paste one in place of the comment to run it. If an example starts with import lines, add them to the top of the file. A -- => comment shows what the line above it prints.

{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings #-}

module Main (main) where

import Data.Bytes.Put (runPutS)
import Data.Bytes.Serial (serialize)
import Haskoin

main :: IO ()
main = do
  -- This is the public BIP-39 test mnemonic. Never send coins to it.
  seed <-
    either fail pure $
      mnemonicToSeed "" "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
  let master = makeXPrvKey seed
  -- Paste an example here.
  pure ()

Mnemonics

Generate entropy with a cryptographic source. This example uses the entropy package.

import qualified Data.ByteString as B
import System.Entropy (getEntropy)

-- 16 bytes of entropy give 12 words. 32 bytes give 24 words.
entropy <- getEntropy 16
words12 <- either fail pure (toMnemonic entropy)

-- The passphrase is optional. Use "" for none.
newSeed <- either fail pure (mnemonicToSeed "my passphrase" words12)
print (B.length newSeed)
-- => 64

mnemonicToSeed checks the words and the checksum. fromMnemonic gives the entropy back.

Keys and signatures

-- A secret key is 32 bytes. decodeSecKey refuses zero and values at or above
-- the curve order.
bytes <- maybe (fail "bad hex") pure (decodeHex "0000000000000000000000000000000000000000000000000000000000000001")
secret <- maybe (fail "bad key") pure (decodeSecKey bytes)

-- True asks for the compressed form of the public key.
let private = wrapSecKey True secret
    public = derivePublicKey private

print private
-- => PrivateKey {key = <redacted>, compress = True}
print (toWif btc private)
-- => "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn"
print (encodeHex (encodeSerial public))
-- => "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
print (addrToText btc (pubKeyAddr public))
-- => Just "1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH"

-- Sign and verify a hash.
let digest = doubleSHA256 bytes
    signature = signHash secret digest
print (verifyHashSig digest signature public.point)
-- => True

fromWif btc text reads a WIF key back. Haskoin also re-exports the secp256k1-haskell API, which has the Schnorr functions such as signSchnorr and verifySchnorr.

Extended keys

Paths have three types. A HardPath has only hardened steps. A SoftPath has only normal steps, which a public key can derive. A DerivPath can mix both. Hardened steps can be written ', h or H.

let account = derivePath ("m/84'/0'/0'" :: HardPath) master
    accountPub = deriveXPubKey account

print (xPubExport btc accountPub)
-- => "xpub6CatWdiZiodmUeTDp8LT5or8nmbKNcuyvz7WyksVFkKB4RHwCD3XyuvPEbvqAQY3rAPshWcMLoP2fMFMKHPJ4ZeZXYVUhLv1VMrjPC7PW6V"

-- The account's public key derives all its receiving addresses.
let receiving = derivePubPath ("m/0" :: SoftPath) accountPub
    addresses = [address | (address, _, _) <- deriveWitnessAddrs receiving 0]
print (map (addrToText btc) (take 2 addresses))
-- => [Just "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu",Just "bc1qnjg0jd8228aq7egyzacy8cys3knf9xvrerkf9g"]

Pick the address function that matches the wallet standard:

Standard Address type Path One address Endless list
BIP-44 P2PKH m/44'/0'/0' deriveAddr deriveAddrs
BIP-49 P2WPKH nested in P2SH m/49'/0'/0' deriveCompatWitnessAddr deriveCompatWitnessAddrs
BIP-84 P2WPKH m/84'/0'/0' deriveWitnessAddr deriveWitnessAddrs
BIP-86 Taproot m/86'/0'/0' See Taproot

xPrvExport and xPubExport write the standard xprv and xpub forms. xPrvImport and xPubImport read them back. The ypub and zpub prefixes are not supported.

parsePath reads a path at run time. It returns a ParsedPath, which applyPath applies to a private or a public key.

Addresses

let text = "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu"

print (textToAddr btc text)
-- => Just (WitnessPubKeyAddress {hash160 = "c0cebcd6c3d3ca8c75dc5ec62ebe55330ef910e2"})

-- An address of another network is refused.
print (textToAddr bch text)
-- => Nothing

-- The output script an address pays to.
print (encodeHex <$> (addressToScriptBS =<< textToAddr btc text))
-- => Just "0014c0cebcd6c3d3ca8c75dc5ec62ebe55330ef910e2"

textToAddr and addrToText handle every address format of a network. addrToBase58, addrToBech32 and addrToCash each write one chosen format.

Scripts

ScriptOutput is a standard output script. Its constructors are PayPK, PayPKHash, PayMulSig, PayScriptHash, PayWitnessPKHash, PayWitnessScriptHash, PayWitness, PayScript32Hash and DataCarrier.

let keyA = wrapPubKey True "02ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f8"
    keyB = wrapPubKey True "02fe6f0a5a297eb38c391581c4413e084773ea23954d93f7753db7dc0adc188b2f"
    -- BIP-67 sorts the keys, so that all signers build the same script.
    multisig = sortMulSig (PayMulSig [keyA, keyB] 2)

-- The address can fail, because a P2SH redeem script holds at most 520 bytes.
print (addrToText btc <$> payToScriptAddress multisig)
-- => Right (Just "39bgKC7RFbpoCRbtD5KEdkYKtNyhpsNa3Z")

-- OP_RETURN is 6a, then the push of 5 bytes, then "hello".
print (encodeHex (encodeSerial (DataCarrier ["hello"])))
-- => "6a0568656c6c6f"

-- Read the same bytes back.
script <- maybe (fail "bad hex") pure (decodeHex "6a0568656c6c6f")
print (decodeSerial script :: Either String ScriptOutput)
-- => Right (DataCarrier {pushes = ["hello"]})

Decoding a ScriptOutput fails for a script that matches no template. A Script holds any script, as a list of ScriptOp values, so use that type for the others. encodeOutput and decodeOutput convert between ScriptOutput and Script.

The templates are matched on their exact bytes: every hash and key is a direct push. A multisig script whose keys are pushed with OP_PUSHDATA1 is therefore not a PayMulSig, although Bitcoin Core calls it multisig. A signature covers the bytes of the script of its coin, and a ScriptOutput does not keep them, so a PayMulSig must stand for one script only. The library does not sign or verify the spend of such a coin. Nodes of Bitcoin do not relay that spend, and on Bitcoin Cash no block holds it.

Opcodes on the two chains

Bitcoin and Bitcoin Cash split a script into opcodes in the same way, so one ScriptOp type serves both, with one constructor per byte, and a script parses without a network. The chains name twelve bytes differently. Their constructors carry the Bitcoin name, but 0xba carries the Bitcoin Cash name OP_CHECKDATASIG, and each has a pattern synonym for the other name:

Byte Bitcoin Bitcoin Cash
0x65, 0x66 OP_VERIF, OP_VERNOTIF OP_BEGIN, OP_UNTIL
0x7f–0x81 OP_SUBSTR, OP_LEFT, OP_RIGHT OP_SPLIT, OP_NUM2BIN, OP_BIN2NUM
0x89, 0x8a OP_RESERVED1, OP_RESERVED2 OP_DEFINE, OP_INVOKE
0x8d, 0x8e OP_2MUL, OP_2DIV OP_LSHIFTNUM, OP_RSHIFTNUM
0x98, 0x99 OP_LSHIFT, OP_RSHIFT OP_LSHIFTBIN, OP_RSHIFTBIN
0xba OP_CHECKSIGADD OP_CHECKDATASIG

Both names build and match the same value: OP_SPLIT == OP_SUBSTR. The opcodes that only Bitcoin Cash defines have constructors of their own: OP_CHECKDATASIGVERIFY and OP_REVERSEBYTES, the introspection opcodes from OP_INPUTINDEX (0xc0) to OP_OUTPUTBYTECODE (0xcd), the token opcodes from OP_UTXOTOKENCATEGORY (0xce) to OP_OUTPUTTOKENAMOUNT (0xd3), and the reserved OP_RESERVED3 and OP_RESERVED4.

Show prints the constructor. To show an opcode as a chain names it, use opName, which gives the name that the reference node of the network prints:

print (opName btc OP_SUBSTR, opName bch OP_SUBSTR)
-- => ("OP_SUBSTR","OP_SPLIT")

Which opcodes a chain enables, and from which block, is a matter for a script interpreter, which this library does not have.

payToWitnessScriptAddress and payToNestedScriptAddress give the P2WSH and P2SH-P2WSH addresses of a script.

The three functions return Either. A P2SH redeem script holds at most 520 bytes, which is a multisig of 15 compressed keys. Coins sent to a longer script could never be spent, so payToScriptAddress refuses it. A P2WSH script holds up to 10,000 bytes, so a multisig of 16 to 20 keys needs P2WSH.

Building and signing a transaction

-- The key at m/84'/0'/0'/0/0 and its address.
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 (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 [coin] [("bc1qnjg0jd8228aq7egyzacy8cys3knf9xvrerkf9g", 99000)]

-- SigInput describes the coin. The last argument is the redeem script.
signed <-
  either fail pure $
    signTx btc unsigned [SigInput coinScript amount coin sigHashAll Nothing] [key.key]

print (verifyStdTx btc signed [(coinScript, amount, coin)])
-- => True
print (txVirtualSize signed)
-- => 110
print (txHash signed)
-- => "9a079e6b7939909415b7b027a19e093bc539dac5a2ed50df8beb0942ec821848"

-- This hexadecimal form is what you broadcast.
print (encodeHex (runPutS (serialize signed)))
-- => "01000000000101..."

buildAddrTx adds no change output. Whatever the outputs do not spend goes to the miners as a fee, so list your change output along with the payments.

Fill in SigInput and pick the signing function by the type of the coin:

Coin script redeem Function
P2PKH PayPKHash Nothing signTx
P2SH multisig PayScriptHash Just (PayMulSig ks m) signTx
P2WPKH PayWitnessPKHash Nothing signTx
P2WSH PayWitnessScriptHash Just script signTx
P2SH-P2WPKH PayWitnessPKHash Nothing signNestedWitnessTx
P2SH-P2WSH PayWitnessScriptHash Just script signNestedWitnessTx
Taproot key path PayWitness 1 key Nothing signTx

For multisig, each signer can call signTx with their own keys. mergeTxs combines the results for legacy inputs. For SegWit multisig, use a PSBT.

The digest of a SegWit version 0 input, and of every input on Bitcoin Cash, is the one of BIP 143. It holds three hashes over all the inputs and all the outputs of the transaction, which are the same for every input. signTx, mergeTxs, verifyStdTx, judgeInputs, signPsbt and finalizePsbt compute them once for a transaction. Code that computes the digests itself does the same: txSigHashes takes the transaction once, and txSigHashForkIdWith gives the digest of one input. txSigHashForkId computes the three hashes at each call, so it is the function for one digest.

-- The hashes that the digests of the inputs share, computed once.
let hashes = txSigHashes unsigned

print $ do
  -- The script code of a P2WPKH coin is the P2PKH script of its key.
  code <- case coinScript of
    PayWitnessPKHash keyHash -> encodeOutput (PayPKHash keyHash)
    _ -> Left "not a P2WPKH coin"
  mapM (\i -> txSigHashForkIdWith btc hashes code amount i sigHashAll) [0 .. length unsigned.inputs - 1]
-- => Right ["06c4ab89d1c30437a3f32fb31384d908bc9902f09a294dffd54a820942d8152d"]

makeSignatureWith signs one input from the same hashes. The legacy digest of Bitcoin shares nothing between the inputs: it hashes a copy of the whole transaction for each of them, by its design.

Judging a transaction without a node

A full node checks a transaction by running the script of every coin that it spends. This library runs no scripts. But most of what makes a transaction bad needs none, and Haskoin.Transaction.Judge, a separate import, checks that: a coin that is not there, more paid than is held, a lock time that has not passed, tokens of Bitcoin Cash made from nothing, and the signature of a coin locked to one key, which is most coins.

It answers two questions:

Function The question What it holds the transaction to
judge Somebody wants to publish it: would a node relay it? The rules of the chain, and the rules of relay that have not changed in years
judgeRelayed A peer sent it: could a node have taken it? Only what no node takes, whatever its policy

Both give a Refusal with the reason, or Nothing when every signature was verified, or the first input that could not be judged:

import Haskoin
import Haskoin.Transaction.Judge (Refusal, judgeRelayed)

-- The outputs that the inputs of the transaction spend, in order.
relayed :: Tx -> [TxOut] -> Either Refusal (Maybe Int)
relayed = judgeRelayed btc

An input that could not be judged is no reason to refuse. It spends a coin locked by a script, which is a normal thing to do, and only a full node can say whether it is good. What to do with such a transaction depends on who vouches for it: from a node of your own it is as good as any, and from a stranger it is a claim that nothing here supports.

This is not validation. A transaction that passes may still be one that no node takes: a script that fails, a fee too low, a conflict with another transaction.

Coin selection and fees

Make your coin type an instance of Coin. The library then picks coins and estimates the fee from the kinds of the inputs and outputs. This example is a complete program.

{-# LANGUAGE OverloadedRecordDot #-}

module Main (main) where

import Data.Word (Word64)
import Haskoin

newtype Utxo = Utxo {amount :: Word64}

instance Coin Utxo where
  coinValue utxo = utxo.amount
  coinInputKind _ = InputWitnessPKHash

main :: IO ()
main = do
  let outputs = [OutputWitnessPKHash, OutputWitnessPKHash]
      coins = [Utxo 50000, Utxo 120000, Utxo 300000]
      target = 150000
      feeRate = 5

  -- The size is in virtual bytes, and the fee rate in satoshi per virtual byte.
  print (guessTxSize [InputWitnessPKHash] outputs)
  -- => 141
  print (guessTxFee feeRate [InputWitnessPKHash] outputs)
  -- => Right 705

  -- The result is the chosen coins and the change to send back to yourself.
  -- True keeps searching the rest of the list for a smaller solution.
  case chooseCoins target feeRate outputs True coins of
    Left err -> putStrLn err
    Right (chosen, change) -> print (map (.amount) chosen, change)
  -- => ([120000,50000],18955)

The change here is 170,000 - 150,000 - 1,045, where 1,045 is the fee for two inputs and two outputs.

chooseCoins takes the coins in the order of the list, so sort them the way you prefer first. The output list must include the change output.

The change can be smaller than the dustThreshold of its output kind, down to one satoshi. Nodes do not relay such an output, so leave that change to the fee. chooseCoins refuses a selection above maxStandardTxWeight, which nodes do not relay either.

The estimates are upper bounds, because they count 72 bytes per signature. The kinds include InputPKHash, InputWitnessPKHash and InputTaproot. See InputKind and OutputKind in Haskoin.Transaction.Builder for all of them.

PSBT

Use a PSBT when several parties or devices sign a transaction. This example continues the one in Building and signing.

-- Continues the example above.
import qualified Haskoin.Transaction.Psbt as Psbt

-- Creator: start from the unsigned transaction.
let created = psbtOf unsigned

-- Updater: attach the transaction that paid each coin. The signer checks the
-- amount of the coin against it.
    updated = created {Psbt.inputs = map (insertNonWitnessUtxo funding) created.inputs}

-- This base64 text is what you pass to the signers.
let shared = encodePsbtBase64 updated

-- Signer: read the text, and sign every input the keys can sign.
received <- either fail pure (decodePsbtBase64 shared)
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 signedPsbt)
extracted <- either fail pure (psbtTransaction finalized)

-- RFC 6979 signatures are deterministic, so this is the same transaction.
print (extracted == signed)
-- => True

Some other useful functions:

  • xPrvSigner signs from an extended private key, following the derivation records of the inputs.
  • combinePsbt merges the copies that different signers return.
  • signPsbt and finalizePsbt take one input at a time, as BIP 174 and Bitcoin Core do. signPsbt signs the inputs that the signer holds a key for. It leaves as it is an input that it cannot or may not sign, so each party can sign before the others have added their coins and scripts. It keeps the signatures that an input already has. To see what was signed, compare the inputs before and after.
  • signPsbt refuses a whole PSBT for a sighash type only: a type that the signer does not accept, as BIP 174 asks, or a signature already on an input that is of another type than the one the input is signed with, as in Bitcoin Core.
  • A Taproot signature commits to the coin of every input, so signPsbt leaves every Taproot input unsigned until each input has its coin, as Bitcoin Core does.
  • finalizePsbt finalizes the inputs that are ready and leaves the others as they are. It builds the one final script that Bitcoin Core would build, and verifies the signatures that this script uses.
  • decodePsbt checks the fields of BIP 174, BIP 370, BIP 371 and BIP 373. It keeps the hash preimages and the MuSig2 fields, and nothing here signs with them. A PSBT written here and the same PSBT written by Bitcoin Core can differ in the order of their keys, which BIP 174 leaves open: each side reads the other.
  • insertWitnessUtxo attaches a coin without the transaction that paid it. That is enough for a Taproot coin. For a SegWit version 0 coin, the amount is then a claim that the signature does not cover for the other inputs, and a signer can be led to burn coins as fee (CVE-2020-14199). keySigner and xPrvSigner therefore leave such a coin unsigned. Set requirePreviousTx = False on the Signer to sign it.
  • psbtFee and inputCoins give the fee and the coins as the signer checks them. Show those to the user, not amounts read from the fields yourself.
  • psbtTransaction refuses a PSBT whose inputs are not all final. psbtPartialTransaction gives the transaction of a PSBT that is still being signed.
  • insertInputRedeemScript and insertInputWitnessScript attach the scripts of P2SH and P2WSH coins.
  • withVersion Version2 converts a PSBT to version 2. addInput and addOutput then extend it.

Taproot

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 <- either fail pure (taprootScriptOutput (TaprootOutput internalKey Nothing))

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 [coin] [(output, 99000)]

signed <-
  either fail pure $
    signTx btc unsigned [SigInput output 100000 coin sigHashDefault Nothing] [key.key]

print (verifyStdTx btc signed [(output, 100000, coin)])
-- => True

The signature commits to every coin the transaction spends. signTx therefore needs a SigInput for every input of a Taproot transaction.

To commit to scripts, pass a MAST in place of Nothing. signTx only signs key path spends. signPsbt also signs a script path when the leaf is a single key check, <key> OP_CHECKSIG. For other scripts, build the witness yourself with taprootSigHash and encodeTaprootWitness.

taprootSigHash hashes every input and every output of the transaction, so it is the function for one digest. For the digest of each input, or for several digests of one input, take the hashes that they share once with taprootTxHashes, and each digest with taprootSigHashWith:

-- The outputs that the inputs spend, one for each input and in their order.
let spent = [TxOut 100000 (encodeSerial output)]

print $ do
  hashes <- taprootTxHashes unsigned spent
  mapM (\i -> taprootSigHashWith hashes i sigHashDefault Nothing Nothing) [0 .. length spent - 1]
-- => Right ["bc2a6f20493e9377e4214f713ff3168c3eec0e8d07c1c18f3d9756df8602ef6c"]

signTx, verifyStdTx, judgeInputs, signPsbt and finalizePsbt do this themselves: they hash the inputs and the outputs of a transaction once for all its Taproot inputs.

checkTapTree tells whether every leaf of a tree can be spent. A leaf can be at most 128 levels deep, and its version must be one that BIP 341 allows. taprootOutputKey and taprootScriptOutput give Left for a tree that it refuses, so that no address is made for a leaf that can never be spent. Bitcoin Core builds no output for a tree deeper than 128 either.

SLIP-39 secret sharing

SLIP-39 splits a secret into mnemonic shares, and a threshold of shares rebuilds it. It is available from version 1.6.0. The Haskoin module does not re-export it, so import it yourself.

import qualified Haskoin.Crypto.Keys.Slip39 as Slip39

-- One group of 3 members, of which 2 rebuild the secret.
let scheme = Slip39.Scheme 1 [(2, 3)]
    -- A secret has at least 16 bytes, and an even number of them.
    -- Use random bytes in practice.
    secret = "0123456789abcdef"

-- True makes the shares extendable. 1 sets the cost of the encryption.
groups <- either fail pure =<< Slip39.generateMnemonics scheme True 1 "passphrase" secret
let shares = concat groups

print (length shares)
-- => 3
print (Slip39.combineMnemonics "passphrase" (take 2 shares))
-- => Right "0123456789abcdef"
print (Slip39.combineMnemonics "passphrase" (take 1 shares))
-- => Left "Group 0 has 1 share, but its member threshold is 2"

A wrong passphrase is not an error. It returns a different secret, as the specification requires. The passphrase must be printable ASCII, which the specification requires too. A SLIP-39 share is not a BIP-39 mnemonic, and one cannot be converted into the other.

Scheme can also describe two levels. For example, Scheme 2 [(1, 1), (2, 3), (3, 5)] needs two of the three groups, each with its own member threshold.

Bitcoin Cash

Pass bch wherever the examples above pass btc. A few things differ.

-- The BIP-44 coin type of Bitcoin Cash is 145.
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)
-- => Just "bitcoincash:qqyx49mu0kkn9ftfj6hje6g2wfer34yfnq5tahq3q6"
print (addrToBase58 bch address)
-- => Just "1mW6fDEMjKrDHvLvoEsaeLxSCzZBf3Bfg"

-- textToAddr reads both forms.
print ((== Just address) (textToAddr bch "1mW6fDEMjKrDHvLvoEsaeLxSCzZBf3Bfg"))
-- => True

-- SegWit addresses do not exist on Bitcoin Cash.
print (addrToText bch (xPubWitnessAddr (deriveXPubKey key)))
-- => Nothing

signTx sets the fork id flag of the signature hash when the network needs it. Pass sigHashAll as usual.

Bitcoin Cash applies to every block three rules of encoding that Bitcoin applies only to the transactions it relays: the S of an ECDSA signature is low, a key is compressed or uncompressed, and an input script pushes each item by the shortest push that holds it. A node of Bitcoin Cash drops the peer that sends it a transaction that breaks one. verifyStdTx and judgeInputs verify no input that breaks one, on any network. decodeStrictSig, verifyHashSig and importPubKey follow the consensus of Bitcoin, and take more than a block of Bitcoin Cash can hold: to verify a signature of Bitcoin Cash with them, check isCanonicalHalfOrder too, and read the key with decodePubKey.

On Bitcoin Cash a signature of 64 bytes before its hash type byte is a Schnorr signature, also when its bytes are the DER form of an ECDSA signature that verifies. Such a signature is rare by accident, and a computer makes one on purpose in a minute. decodeTxSig refuses that length on the Bitcoin Cash networks, so decodeInput and verifyStdTx do not take it for an ECDSA signature, and judgeInputs reads it as a Schnorr signature. decodeStrictSig reads it: with that function, check isCashSchnorrLength too. signTx does not hand out such a signature. When one comes out, which the specification of Bitcoin Cash gives one chance in 2^49, it fails and says to change the transaction and sign again.

CashTokens

An output of Bitcoin Cash can hold tokens (CHIP-2022-02). They are written at the front of the script field of the output, before the locking script, as a token prefix that starts with the byte 0xef. splitTokenData reads the prefix into a TokenData, with the category, the fungible amount and the non-fungible token, and gives back the locking script after it. encodeTokenPrefix writes the prefix. scriptToAddressBS takes the prefix off by itself on the Bitcoin Cash networks; on Bitcoin 0xef is no prefix, and such a script has no address.

-- Output 4 of transaction e3abdbdc…f5a809 holds 110,830 tokens on a P2PKH script.
field <-
  maybe (fail "bad hex") pure . decodeHex $
    "ef2c06f3b2565d0818a8e41f58beff5918d5dbdc64b11ee8ad474e499751cde07f10feeeb00100\
    \76a9146e0810ceea13412b73feb41566a3d2d0ce54e10188ac"

-- The address is that of the locking script, in its plain form.
let address = either error id (scriptToAddressBS bch field)
print (addrToText bch address)
-- => Just "bitcoincash:qphqsyxwagf5z2mnl66p2e4r6tgvu48pqyhmvay0uy"

-- The token-aware form of the same address, for a wallet that handles tokens.
print (addrToText bch =<< tokenAwareAddress address)
-- => Just "bitcoincash:zphqsyxwagf5z2mnl66p2e4r6tgvu48pqys3lr2frh"

-- The tokens.
let tokens = either error fst (splitTokenData field)
print (fmap (.amount) tokens)
-- => Just 110830
print (fmap (.category) tokens)
-- => Just "7fe0cd5197494e47ade81eb164dcdbd51859ffbe581fe4a818085d56b2f3062c"

Why the plain form: a token-aware CashAddr (type 2 for P2PKH, 3 for P2SH and P2SH32) locks coins with the same script as the plain one. It only tells a sender that the receiver will not burn tokens by spending them as plain coins. A wallet receives coins with and without tokens at the same script, so an index that used the token-aware form for outputs with tokens would split the history and the balance of one address in two. Bitcoin Cash Node shows the plain form too, with the tokens beside it. Use tokenAwareAddress to show or hand out the token-aware form, and plainAddress to turn a token-aware address that a user gives back into the address that scriptToAddressBS returns.

The other side of that choice: nothing in the address says that an output holds tokens. A server that lists the unspent outputs of an address must give the tokens of each one too, from splitTokenData, so that a wallet can leave them out. A wallet that spends such an output as a plain coin burns its tokens, or signs without the token prefix and has the transaction refused. Nothing in this library signs these outputs.

Before 3.0.0 these outputs had no address. An index of addresses built with an older version left them out, and must be rebuilt, or have them added, before it runs with 3.0.0. Otherwise spending one of them takes from a balance an amount that was never added to it.

What is not checked: the rules that need the whole transaction, such as the category being an input of it and the amounts adding up, and the limit on the length of a commitment, which is a validation rule that has changed between network upgrades.

Blocks and headers

print (headerHash btc.genesisHeader)
-- => "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"
print (isValidPOW btc btc.genesisHeader)
-- => True

-- 3.125 BTC since the halving at this height.
print (computeSubsidy btc 840000)
-- => 312500000

connectBlocks validates headers and adds them to a chain. This covers proof of work, difficulty, timestamps, versions and checkpoints. It runs in any monad with a BlockHeaders instance. StateT HeaderMemory is the in-memory one. Write your own instance to keep headers in a database.

Give connectBlocks all the headers of a headers message at once rather than one by one with connectBlock. On Bitcoin Cash the difficulty depends on an anchor block far down the chain. On mainnet and testnet4 the Network record holds that block (asertAnchorBlock), as Bitcoin Cash Node does, and finding it is a walk down the chain: about 80 reads at height 100,000, and about 75 on mainnet today. On other networks, such as regtest, it is a binary search of about 1,500 reads at height 100,000. connectBlocks finds it once for the whole run, so either way it pays this cost once rather than for each header.

Once the best block has the minimumChainWork of the network, a fork with less work is refused. Below that work nothing bounds the side chains a peer can send, so a node that is still syncing should not keep headers from a peer it does not trust.

This example needs the mtl package.

import Control.Monad.State.Strict (runStateT)

-- Mine three regtest headers on top of the genesis block.
let net = btcRegTest
    headers = appendBlocks net 7 net.genesisHeader 3
    now = net.genesisHeader.timestamp + 3600

(result, chain) <- runStateT (connectBlocks net now headers) (initialChain net)
nodes <- either fail pure result

-- The nodes come back with the highest one first.
print (map (.height) nodes)
-- => [3,2,1]
print chain.best.height
-- => 3

buildMerkleRoot and buildPartialMerkle compute Merkle trees. extractMatches checks a partial tree from a merkleblock message against its Merkle root. The header and the number of transactions are claims of the sender, which the caller must check.

Peer-to-peer messages

The library encodes and decodes messages. Moving the bytes is up to you.

import Data.Bytes.Get (runGetS)

let bytes = runPutS (putMessage btc MVerAck)

print (encodeHex bytes)
-- => "f9beb4d976657261636b000000000000000000005df6e0e2"
print (runGetS (getMessage btc) bytes)
-- => Right MVerAck

getMessage checks the network magic and the checksum, and bounds the payload by the maxPayloadSize of its command. Read the 24-byte MessageHeader first to learn how many more bytes to take from the socket, and refuse a length above maxPayloadSize net command before you read them.

Message has a constructor for each message type. bloomCreate, bloomInsert and bloomContains build BIP-37 filters for filterload.

Protocol machines

The messages are half of the protocol. The other half is what a node does with them: which messages it drops before the handshake, which ones cost the peer its connection or its address, when it pings and how long it waits, what a whitelisted peer may do. No BIP says it; the code of the reference nodes does. Haskoin.Network.Protocol translates that code into pure state machines, one per network: Bitcoin Core 32.1 for the Bitcoin networks and Bitcoin Cash Node 29.2.0 for the Bitcoin Cash networks. A program that talks to these nodes can use them to know what the node will do, and its tests can use them as an oracle.

A machine models how the node treats one peer. start opens a connection from a Setup (who opened it, the peer’s permissions, its address network), and step feeds it one input: a message, a framing error, a tick of the clock, or news from the rest of the node. It returns what the node did, and each Effect carries a Cite of the upstream file and line that decides it. The machine reads nothing on its own: an Env gives the time and the answers about the chain and the mempool.

import qualified Data.Set as Set
import Haskoin
import Haskoin.Network.Protocol

let -- A peer that connects to the node, with no permissions.
    setup =
      Setup
        { connectionType = Inbound,
          permissions = Set.empty,
          peerNetwork = AddrIPv4,
          peerIsLocal = False,
          transport = TransportV1,
          openedAt = seconds 1700000000,
          seed = 42
        }
    -- A node that has only the genesis block of its network.
    envOf net =
      let info =
            BlockInfo
              { hash = headerHash net.genesisHeader,
                height = 0,
                status = HaveData,
                inActiveChain = True,
                work = 0,
                time = net.genesisHeader.timestamp
              }
       in defaultEnv info (genesisBlock net) (seconds 1700000001)
    -- The peer sends verack before version.
    tryIt net =
      snd (step (envOf net) (start (machine net) setup) (Receive MVerAck))

print (map (.action) (tryIt btc))
-- => [Ignore]
print (map (.action) (tryIt bch))
-- => [Misbehave 10]
print (map (.because) (tryIt bch))
-- => [Cite {file = "src/net_processing.cpp", line = 2311, reason = "missing-version"}]

Bitcoin Core drops the early verack; Bitcoin Cash Node adds 10 to the peer’s ban score, so ten such messages get its address discouraged. The report in doc/protocol describes the protocol of both nodes in prose, with the same references, and lists where they differ. It changes with the machines: scripts/protocol-cites.sh prints every citation next to the upstream line it names, which is how both are brought to a new release.

What the machines leave out: validation, the chain and the mempool, which come from the Env; decisions that span peers, such as which peer to download a block from, which come in as notifications; and bytes, since a machine sees whole messages.

Module overview

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.

Module Contents
Haskoin.Address Address types and Base58, Bech32 and CashAddr encoding
Haskoin.Block Block types, header chain, validation, difficulty and Merkle trees
Haskoin.Crypto Hashes, keys, signatures and the Crypto.Secp256k1 API
Haskoin.Crypto.Keys.Slip39 SLIP-39 secret sharing (separate import)
Haskoin.Network Network constants, P2P messages, Bloom filters
Haskoin.Network.Protocol State machines of the reference nodes’ protocol (separate import)
Haskoin.Script Scripts, standard templates, signature hashes and CashTokens
Haskoin.Transaction Transaction types, builder, signing, SegWit, Taproot and PSBT
Haskoin.Transaction.Judge What can be said of a transaction without a node (separate import)
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

Bugs in code that handles keys can lose money. Try your program on regtest or a test network before you use it on mainnet.

  • Randomness. Create keys and mnemonics with a cryptographic source, such as 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, 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, and the garbage collector can copy them.
  • Review before you sign. signPsbt checks that a PSBT is sound, but not that it pays who you expect. Show the outputs and psbtFee to the user first. By default the signer wants the previous transaction of every SegWit version 0 coin, because an amount in a witness output alone is a claim.
  • Signature hash types. By default signPsbt signs only SIGHASH_ALL and SIGHASH_DEFAULT, because the other types leave part of the transaction unsigned. To accept others, set acceptedSigHashes on the Signer.
  • Verification. verifyStdTx checks the signatures of the standard templates, and that outputs do not exceed inputs. It is not a script interpreter and does not apply every consensus rule. It answers True only for inputs in a form that Bitcoin Core relays. It answers False for a script that it does not read, and for an input that a block may hold and that nodes do not relay: a signature with a high S, a key in the hybrid form, an input script with a push longer than its data needs, a SegWit input signed with an uncompressed key and a Taproot input with an annex. True is still no promise that nodes relay the transaction: the rules on the whole transaction, such as its size, its fee and its outputs, are not looked at. judgeInputs tells a forged input from one that is left to a node.
  • Untrusted text. The cost of decodeBase58 and decodeBase58Check grows with the square of the input length. Limit the length of input you pass to them directly. The address and key decoders of the library already do. cash32decode reads data of any length by design, and holds hundreds of bytes for each character: limit its input too.

Development

git clone https://github.com/jprupp/haskoin-core.git
cd haskoin-core

stack build                                         # build the library
stack test                                          # run all the tests
stack test --test-arguments='--match "Slip39"'      # run the tests of one module
stack haddock --no-haddock-deps                     # build the API documentation

cabal build and cabal test work too. On NixOS, or with stack --nix, the nix section of stack.yaml provides libsecp256k1.

These commands build the library as it is released, with optimisation, which takes minutes. For the time between two commits there is a faster loop: haskell-dev, a script of jprupp/tools. Clone that repository once and put its folder on your PATH, for example in ~/.bashrc; a terminal opened before the change needs source ~/.bashrc.

git clone https://github.com/jprupp/tools.git ~/Source/tools
echo 'export PATH="$HOME/Source/tools:$PATH"' >> ~/.bashrc

Then run it from the top folder of haskoin-core:

haskell-dev test                                # build, then run all the tests
haskell-dev test Psbt                           # the specs with Psbt in their module name
haskell-dev test Psbt Block                     # the specs of several modules
haskell-dev test --match "/Haskoin.Block/asert/"  # one path, in one process
haskell-dev test --seed 12345                   # run a failure again
haskell-dev test --jobs 4                       # fewer processes, to save memory
haskell-dev build                               # build without optimisation
haskell-dev docs                                # build the documentation and check its comments

test builds first, so a separate build is not needed. A clean build takes about 30 seconds, and a run of all the tests 5 to 10, against minutes for stack test. The tests run in several processes at once, and haskell-dev.toml tells the script which spec modules are slow, so that it shares them between the processes. When a test fails, the output gives the seed: run the test again alone with --seed and --match on its path, which prints the usual output of hspec.

Do not mix the two kinds of build in one folder. When no source has changed, Stack does not see that the flags have, and keeps the objects of the other build: a plain stack build right after haskell-dev build gives a library without optimisation. Only what runs from this folder uses it, such as the tests: a package that depends on haskoin-core builds its own copy. After the next change to a source, everything compiles again. Never time the library with haskell-dev: see Benchmarks.

package.yaml is the source of the package description. Change it rather than haskoin-core.cabal, which hpack generates. Stack regenerates the file whenever it builds.

The tests are in test/ and use hspec. The test vectors from the BIPs, Bitcoin Core and other implementations are in data/.

Some tests check the library against a node of Bitcoin Core 32.1 on regtest: the library signs the PSBTs that Bitcoin Core makes, for every kind of coin, and Bitcoin Core accepts the transactions; twelve wallets sign a PSBT of nine coins, and the library must combine, finalize and extract it as Bitcoin Core does. They need rootless Podman on Linux: each group of these tests starts a node of its own in a container, through podman-test, so test processes that run at once share nothing. The first run builds the image of the node, which downloads Ubuntu and Bitcoin Core and takes a minute or two; after that a node starts in a few seconds. Without Podman these tests are pending, and say why; set PODMAN_TEST_SKIP to leave them out on purpose. The image and the RPC client are in test/BitcoinCore.hs.

data/psbt_complex_core32.json comes from such a node. To make a new one, run the tests with the path of the file in HASKOIN_COMPLEX_PSBT, and format it with jq . as the other files of data/ are:

HASKOIN_COMPLEX_PSBT=/tmp/complex.json haskell-dev test --match "sign as the tests run"

Benchmarks

The benchmarks are in bench/Bench.hs and use 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. The group headers times connectBlocks on a batch of 2,000 headers, the most that a headers message holds, on top of a Bitcoin Cash chain of 100,000 that uses the aserti3-2d difficulty rule, the case where a node syncing headers spends its time.

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

Pull requests are welcome.

  • Format the code with Ormolu. haskell-format, from jprupp/tools, does this for every Haskell file in the repository.
  • Add tests for the behaviour you change.
  • Describe the change under [Unreleased] in CHANGELOG.md. The file follows Keep a Changelog, and versions follow Semantic Versioning.

Related projects

License

Haskoin Core is released under the MIT License.

Changes

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog and this project adheres to Semantic Versioning.

[Unreleased]

[3.0.0] - 2026-11-25

This release breaks backwards compatibility in three places:

  • The Network record has a new field, asertAnchorBlock, so code that builds a Network field by field, or uses its constructor positionally, must change. Code that only reads networks, or updates a copy of one, compiles as before.
  • On Bitcoin Cash, outputs that hold CashTokens now have an address. An index of addresses built with an earlier version must be rebuilt, or have these outputs added, before it runs with 3.0.0: see “Upgrading an index of addresses” below.
  • The Bitcoin Cash testnet3 is renamed bchTest3, with the name bchtest3 for netByName, from bchTest and bchtest: see “Changed” below.

Bitcoin testnet3 is deprecated and still works.

Added

  • Protocol machines of the reference nodes. The new module Haskoin.Network.Protocol, a separate import, models how the reference node of each network treats one peer, as a pure state machine translated from the upstream source: Bitcoin Core 32.1 (Haskoin.Network.Protocol.BitcoinCore) for btc, btcTest, btcTest4 and btcRegTest, and Bitcoin Cash Node 29.2.0 (Haskoin.Network.Protocol.BitcoinCashNode) for bch, bchTest3, bchTest4 and bchRegTest. machine picks the machine of a network with the node’s default options, start opens a connection from a Setup and step feeds it a message, a framing error, a tick or a notification. Each Effect (send, ignore, misbehaviour score, discourage, ban, disconnect) carries a Cite of the upstream file and line that decides it. Connection types, the permissions of whitelisted peers, node options such as -blocksonly, and the timers of both nodes are modelled; validation and the state of the chain and the mempool come from an Env. The vocabulary is in Haskoin.Network.Protocol.Types.

  • A report of the protocol of both nodes, doc/protocol/README.md, with one file per node: every rule with a link to its upstream line and the Haskell function that implements it, the differences by network, by permission and by connection type, and where the two nodes differ. The script scripts/protocol-cites.sh prints every citation of a machine next to the upstream line it names, to check them and to bring the machines to a new release.

  • The opcodes of Bitcoin Cash. ScriptOp has constructors for the introspection opcodes of May 2022, OP_INPUTINDEX (0xc0) to OP_OUTPUTBYTECODE (0xcd), the token opcodes of May 2023, OP_UTXOTOKENCATEGORY (0xce) to OP_OUTPUTTOKENAMOUNT (0xd3), and OP_RESERVED3 and OP_RESERVED4 (0xd4, 0xd5). These bytes used to parse as OP_INVALIDOPCODE. Code that matches every constructor of ScriptOp must handle them.

  • Bitcoin Cash names of renamed opcodes, as pattern synonyms: OP_BEGIN, OP_UNTIL, OP_SPLIT, OP_NUM2BIN, OP_BIN2NUM, OP_DEFINE, OP_INVOKE, OP_LSHIFTNUM, OP_RSHIFTNUM, OP_LSHIFTBIN and OP_RSHIFTBIN are the same values as OP_VERIF, OP_VERNOTIF, OP_SUBSTR, OP_LEFT, OP_RIGHT, OP_RESERVED1, OP_RESERVED2, OP_2MUL, OP_2DIV, OP_LSHIFT and OP_RSHIFT, as OP_CHECKSIGADD already was for OP_CHECKDATASIG.

  • opName gives the name of an opcode on a network, as GetOpName of Bitcoin Core 32.1 or of Bitcoin Cash Node 29.2.0 gives it. A network and its testnets share their names.

  • CashTokens (CHIP-2022-02). The new module Haskoin.Script.CashToken, exported by Haskoin.Script and Haskoin, reads and writes the token prefix that Bitcoin Cash puts at the front of the script field of an output that holds tokens. splitTokenData splits a script field into a TokenData (category, fungible amount, and an NFToken with its TokenCapability and commitment) and the locking script after it. encodeTokenPrefix writes a prefix. TokenData has Serial, Binary, Serialize, Read, Show and JSON instances; the JSON is that of the CashTokens test vectors and of the RPC of Bitcoin Cash Node, with the amount as a string. The parser reads the amount strictly: a string of decimal digits without a leading zero, or a whole number whose exponent is checked before the number is built. The official test vectors of the token prefix, 62 valid and 55 invalid, are in data/ and pass.

  • tokenAwareAddress gives the token-aware CashAddr of a P2PKH, P2SH or P2SH32 address (type 2 or 3), and plainAddress turns a token-aware address back into its plain form.

  • arbitraryTokenData and arbitraryNFToken in Haskoin.Util.Arbitrary.

  • A generator of signed transactions with one input written another way, to test a verifier: the new module Haskoin.Util.Arbitrary.Spelling, exported by Haskoin.Util.Arbitrary. The other generators make what signTx writes, so a verifier that is wrong about any other form passed every test made from them. arbitraryRespelled makes a signed transaction of one to four inputs with one input in the Spelling asked for, and gives it with the outputs that it spends (Respelled). Every signature in it is good. The spellings are a longer push in an input script (LongPush), a longer push of a nested witness program (LongProgramPush), a high S (HighS), a key in the hybrid form (HybridKey), an uncompressed key in a SegWit input (UncompressedKey), a redeem script or a witness script in other bytes than the coin commits to (UncommittedScript), and a coin locked to another spelling of the script that was signed (UnsignedScript). The documentation of each says what the nodes of Bitcoin and of Bitcoin Cash do with it. The properties of the test suite state the answers of verifyStdTx and judgeInputs for each spelling on each chain.

  • arbitrarySigningDataOf is arbitrarySigningData for coins that the caller chooses. arbitraryLegacySigInput and arbitraryWitnessSigInput are the two halves of arbitrarySigInput without Taproot.

  • roundIterations in Haskoin.Crypto.Keys.Slip39: the PBKDF2 iterations of one round of the SLIP-39 cipher at an iteration exponent, 2500 × 2^e. The cipher computed this count in place. It has a name so that a test states it at each of the 16 exponents: one encryption at the exponent 15 takes minutes, and no test had an exponent above 3. The cipher itself is now tested at the exponents 4 and 5, and a share is read and written with every field of its header at its highest value.

  • The tests compare the SLIP-39 shares that generateSharesFrom draws with expected ones. They checked that drawn shares rebuild the secret, and shares do that also when a random value is replaced by zeros, where one share shows most of the secret. A source that gives the random values of a case of data/slip39_split.json must now give the mnemonics of that case, and two draws from the system must differ. The documentation of generateSharesFrom says in which order it asks its source for bytes: the order of the reference implementation.

  • The identity helpers of Haskoin.Util.Arbitrary have tests of their own. testIdentity and the five tests that it makes, for Read and Show, JSON, MarshalJSON, Serial and Marshal, are what about 200 tests of this library and the tests of the programs built on it rest on. Nothing checked that they can fail: with the comparison taken out of any of the five, every test passed. The new spec runs them on a type whose five forms are right, which must pass, and on types with one fault each, which must fail in the example of that fault and in no other. It also states the names of the groups and of the examples, which --match patterns rely on.

  • The Network record holds the aserti3-2d anchor block where it is known, in the new field asertAnchorBlock: block 661647 on Bitcoin Cash mainnet and block 16844 on testnet4, the constants of Bitcoin Cash Node. asertAnchor then finds the anchor with one walk down the skip pointers, about 80 reads at height 100,000, instead of a binary search of about 1,500 reads, so connectBlock and nextWorkRequired are fast on those networks too, not only connectBlocks. The constant is checked against the chain: a chain that does not hold that block at that height still gets the search, but the block itself is trusted to be the anchor: a custom network must give the first block whose median time past reaches the activation time. Code that builds a Network record field by field must now set this field.

  • taprootTxHashes and taprootSigHashWith give the Taproot digests of one transaction from the hashes that they share. The digest of BIP 341 commits to four hashes over all the inputs of the transaction and to one over all its outputs, which are the same for every input: the BIP says that they “may be cached across signatures of the same transaction”. taprootTxHashes computes them once, from the transaction and the output that each input spends, into a value of the new type TaprootTxHashes. taprootSigHashWith then gives the digest of one input, for a hash type, an annex and a leaf, in a time that does not depend on the size of the transaction. taprootSigHash is unchanged and gives the same digests: it is the function for a single digest, since it hashes the whole transaction at each call. Code that calls it for every input of a transaction should change to the two new functions.

  • txSigHashes and txSigHashForkIdWith give the BIP 143 digests of one transaction from the hashes that they share. The digest of BIP 143 is the one of a SegWit version 0 input on Bitcoin and of every input on Bitcoin Cash. It holds three hashes over all the inputs and all the outputs of the transaction (hashPrevouts, hashSequence and hashOutputs), which are the same for every input. txSigHashes computes them once, into a value of the new type TxSigHashes, and a function takes that value in place of the transaction: txSigHashForkIdWith, txSigHashCashTokenWith and txSigHashWith in Haskoin.Script.SigHash, makeSignatureWith in Haskoin.Transaction.Builder, and makeSigHashWith in Haskoin.Transaction.Builder.Sign. Each gives what the function without With gives, and fails as it does. sigHashesTx gives the transaction back. The functions without With are unchanged: each is the function for a single digest, since it hashes the whole transaction at each call. The legacy digest of Bitcoin shares nothing between the inputs, so txSigHashWith saves time on a network with a fork id only. inputSpends in Haskoin.Transaction.Builder.Sign gives the input script and the witness stack of each input of a transaction, which is what signing an input changes.

  • What can be said of a transaction without a full node. The new module Haskoin.Transaction.Judge, a separate import, has the checks that a program can make of a transaction with no interpreter of scripts, given the outputs that it spends.

    • judge is for a transaction that somebody wants to publish: its coins are there and unspent, it pays no more than it holds, its lock time has passed, it is no larger than nodes relay and has no dust, its input scripts only push data, its version is one that nodes take, its tokens follow the rules of Bitcoin Cash, and no signature of a coin locked to one key is forged. It moved here from haskoin-store, where it has judged what clients post since 1.13, with Coin, Refusal, Rules, maxTxSize, maxStandardSize, isDust and tokenRules. rulesAt gives the rules at a height and a median time.
    • judgeRelayed is new, for a transaction that a peer sent as one that its node took. It refuses only what no node takes whatever its policy: no inputs or outputs, an output spent twice, a coinbase, more paid than held, tokens of Bitcoin Cash that break their rules, and a forged signature of a coin locked to one key. It leaves out every rule of relay, since the policy of a node is its own, and the lock time, which a node holds to the block that it is at.
    • Both say whether every signature was verified, or name the first input that could not be judged, which is no refusal: what to do with such a transaction depends on who vouches for it. The names of the module are not exported by Haskoin, where Coin is already a class.

Deprecated

  • Bitcoin testnet3, btcTest. Using it gives a deprecation warning; use btcTest4. Bitcoin Core has deprecated testnet3 and says it will remove it in an upcoming release. It stays in allNets and netByName still finds it, and a later major version will remove it. bchTest3 is not deprecated: Bitcoin Cash Node still supports testnet3 without a notice.

Changed

  • signPsbt and finalizePsbt take one input at a time, as BIP 174 and Bitcoin Core do. They used to refuse a whole PSBT, with a reason, for many faults of one input. The parties of a transaction fill a PSBT in turn, so an input that one party cannot sign or finalize is the normal case. BIP 174 says “If a Signer cannot sign a transaction, it must not add a Partial Signature” and “For each input, the Input Finalizer determines if the input has enough data to pass validation”. Each rule below was compared with Bitcoin Core 32.1 on regtest. The order followed is: the BIPs, then Bitcoin Core, then the safer choice. A caller that relied on a refusal now finds the input without a signature, or not final: compare the inputs before and after, or call psbtTransaction, which tells whether every input is final.

    • What still refuses a PSBT. In signPsbt, a sighash type: one that no node accepts or that the signer does not accept (acceptedSigHashes), on any input that has its coin and is not final, as BIP 174 asks. New, as in Bitcoin Core: a signature already on an input that is of another type than the one the input is signed with (“a signature of the input does not use the sighash type 1”). In both functions, a previous transaction that is not the one its input spends, which decodePsbt does not read either. finalizePsbt refuses nothing else.
    • What signPsbt now leaves unsigned instead of refusing. A redeem script or a witness script that does not hash to the coin, or that the coin has no use for (BIP 174 has the signer check both; Bitcoin Core signs a coin that carries a script it does not use). A legacy coin known from its witness output only. A SegWit version 0 coin known from its witness output only, when the signer wants the previous transaction (requirePreviousTx, still the default). A legacy input asked to sign SIGHASH_SINGLE with no output at its index, and a Taproot input in that case. An uncompressed key on a SegWit version 0 coin gets no signature, and the other keys of that coin are still signed with.
    • What finalizePsbt now leaves not final instead of refusing. A signature that it would use and that does not verify, is no signature, has a high S or is of an uncompressed key on a SegWit version 0 coin. A signature of another sighash type than the input names, or than SIGHASH_ALL (SIGHASH_DEFAULT on a Taproot coin) when it names none. A Taproot leaf whose control block does not commit it to the coin.
    • The coin of an input is the output of its previous transaction when the input has one. A witness output beside it is not read, as Bitcoin Core does not read it. signPsbt, finalizePsbt, inputCoins and psbtFee used to refuse a witness output that was not that output.
    • signPsbt keeps the signatures that an input has. It used to sign again and replace them. A key that has a partial signature is not signed with again. A Taproot input that has a key path signature gets no other signature, and a leaf keeps the signature under its key.
    • A Taproot input gets a key path signature or leaf signatures, not both. When the signer holds the internal key and the key of a leaf, it signs the key path alone, as Bitcoin Core does.
    • signPsbt signs the key path of a Taproot coin whose output key is the key of the signer, when the input names no internal key that gives the coin. Such a coin pays to a key with no tweak, as the descriptor rawtr() of Bitcoin Core makes one.
    • signPsbt signs a Taproot leaf as Bitcoin Core does: by the leaf version in the value of its entry, whatever its control block holds, and with the key of any record of that key, whichever leaves the record lists. It used to want a control block that commits the leaf to the coin, and a record that lists the leaf. A signature of a leaf that is not in the tree of the coin spends nothing, and finalizePsbt makes a witness only of a leaf that its control block commits.
    • finalizePsbt builds the final script that Bitcoin Core would build, and verifies the signatures that it uses. A multisig takes the signatures of its first keys that have one. A Taproot coin takes its key path signature, or else the signed leaf with the shortest control block, where it took the first signed leaf. A signature that the final script does not use is no longer verified, so it cannot stop an input that is ready. When the script that Bitcoin Core would build does not pass, the input is left: no other choice of signatures is tried.
    • finalizePsbt no longer looks at a redeem script or a witness script that the coin has no use for, as Bitcoin Core does not: BIP 174 gives that check to the signer.
    • finalizePsbt clears the fields of the signers from an input that is final already, as it does from the inputs that it finalizes.
    • Edge cases closed. signPsbt signed a P2WSH coin whose witness script is a witness program, and finalizePsbt then refused that signature: no signature spends such a coin, and both now leave it. signPsbt signed a SegWit version 0 coin of more than 21 million bitcoin, which Bitcoin Core does not. On a network without SegWit, a script of the form of a Taproot output was handled as a Taproot coin. signPsbt did not check the sighash type of an input whose coin script does not parse.
    • Where the library does not do as Bitcoin Core, and why. BIP 174 decides: signPsbt leaves an input with a script that its coin has no use for; signPsbt refuses a sighash type that it does not accept on a coin that anyone can spend, which Bitcoin Core counts as signed; finalizePsbt leaves an input that asks for the sighash type 0 and has a partial signature; psbtTransaction extracts a final input that has no coin; combinePsbt keeps every entry of a final input. BIP 174 lets the signer choose: it wants the previous transaction of a SegWit version 0 coin by default. Bitcoin Core has a problem: signPsbt adds no key path signature with an internal key that does not give the coin, and none with SIGHASH_SINGLE on a legacy input without an output at its index. The library has a limit: it signs no leaf of more than one key, no script that is not a standard template, no P2SH coin whose redeem script is over 520 bytes, and it knows no descriptor, so it finds an internal key or a redeem script in the PSBT only.
  • decodePsbt follows the BIPs field by field, and Bitcoin Core where they are silent. The decoder and decodepsbt of Bitcoin Core 32.1 were compared on the 168 PSBTs of the BIPs and of the tests of Bitcoin Core, and on 89 hand-made cases. They now give another verdict for one PSBT of the 168, where they did for 19.

    • Read now, as Bitcoin Core reads them. A redeem script or a witness script, of an input or of an output, and a leaf script of the script tree of an output, that are no list of opcodes: BIP 174 and BIP 371 give them as bytes. A Taproot signature of 65 bytes whatever its last byte: BIP 371 gives its length only. The function that gives the field refuses such bytes (inputRedeemScript, outputTapTree, tapKeySig), and signPsbt and finalizePsbt leave the input as it is.
    • Refused now, as Bitcoin Core refuses them. A MuSig2 field of BIP 373 that is out of shape: an aggregate key or a participant key that is no compressed public key on the curve, a public nonce that has not 66 bytes, a partial signature that has not 32. The ten invalid PSBTs of BIP 373 were read. A hash preimage under a key that is not a hash of the size of its algorithm. A global extended key of depth 0 that has a child number or a parent fingerprint, which BIP 32 gives to no master key.
    • Refused now, by BIP 174 alone. A hash preimage that does not hash to its key: the preimage “must equal the key when run through” the algorithm of its field. Bitcoin Core reads it.
    • finalizePsbt clears the hash preimages and the MuSig2 fields of an input that it finalizes, as Bitcoin Core drops them.
    • Where the decoder still does not do as Bitcoin Core. A BIP is stricter, and Bitcoin Core reads what is refused here: the preimage above, a control block of more than 128 nodes (BIP 341), and an extended key whose path is not as deep as the key (BIP 174). And one case stays open: a PSBT of version 2 whose inputs require lock times that no transaction can have. Bitcoin Core reads it and gives no transaction. A Psbt always has its transaction, so it is refused.
    • The library keeps the MuSig2 fields and the preimages, and does not sign with them. The vectors of BIP 373 are in data/psbt_bip373.json.
    • The documentation said that a map is written “as Bitcoin Core writes it”. It is written with its keys in the order of their bytes. BIP 174 fixes no order, and Bitcoin Core writes another one, so the bytes of the two can differ for the same PSBT. Each reads the bytes of the other.
  • signTx, signNestedWitnessTx, signInput and signNestedInput refuse SIGHASH_SINGLE on any input that has no output at its index. They refused it on a legacy input only, where the digest is the constant 1, and signed a SegWit input and an input of Bitcoin Cash. That signature commits to no output, as one of SIGHASH_NONE does. No BIP has a rule for a signer here. The transaction signer of Bitcoin Core makes no such signature for any kind of input (SignTransaction: “Only sign SIGHASH_SINGLE if there’s a corresponding output”; run on regtest with signrawtransactionwithwallet), nor does the one of Bitcoin Cash Node. The error is signInput: SIGHASH_SINGLE without an output at the input index, also for a legacy input, where it named makeSignature. makeSignature is unchanged: it refuses the legacy case and signs the others, which the PSBT signer of Bitcoin Core signs too, so signPsbt is unchanged.

  • verifyStdInput, verifyStdTx and judgeInputs no longer verify an input that a block may hold and that nodes do not relay. They follow the rules by which Bitcoin Core relays an input, where they followed the rules of a block for three forms. A caller that hands a transaction to its peers when every input is verified sent these, and the peers dropped them. The answers were True, True and InputVerified. They are now False, False and InputUndecided for:

    • on Bitcoin, an input script with a push longer than its data needs: a signature, a key or a redeem script after OP_PUSHDATA1, 2 or 4 where a shorter push holds it. Bitcoin Core 32.1: “Data push larger than necessary”;
    • a SegWit version 0 input with a signature checked against an uncompressed key: a witness key hash, native or nested, and a key or a key hash in a witness script. Bitcoin Core 32.1: “Using non-compressed keys in segwit”. In a multisig witness script, the signatures must verify against the compressed keys after the last uncompressed one: OP_CHECKMULTISIG tries the keys from the last one, and Bitcoin Core relays the spend when it reaches no uncompressed key;
    • a Taproot input with an annex, by the key path or by a script path. Bitcoin Core 32.1: “bad-witness-nonstandard”.

    A high S, a key in the hybrid form and an undefined hash type were refused already. An input of one key in one of these forms is still InputForged when its signature does not verify. signInput still signs a SegWit coin with an uncompressed key that it is given, and verifyStdInput now answers False for that input. True is still no promise that nodes relay the transaction: the rules on the whole transaction, such as its size, its fee and its outputs, are not looked at. The tests hold 16 spends that Bitcoin Core 32.1 judged on regtest with the relay policy of mainnet.

  • taprootOutputKey and taprootScriptOutput give no output for a script tree that checkTapTree refuses. Their results are now Either String PubKey and Either String ScriptOutput. They gave an output for any tree, and left the check to the caller. A tree with a leaf deeper than 128, or with a leaf version that a control block cannot carry, then got an address like any other, and coins that could only be spent by that leaf were lost. Bitcoin Core builds no output for a tree deeper than 128 (TaprootBuilder).

    • Left carries the reason of checkTapTree, such as checkTapTree: a node is deeper than 128.
    • taprootOutputKey no longer calls error when the tweak gives no key, about one case in 2^128: that is Left too.
    • To recognise a coin that someone else paid to such a tree, or to spend it by its key path, pass the root in place of the tree: MASTCommitment (mastCommitment tree). A commitment is not looked into.
    • A caller without a script tree changes one line. For a BIP 86 address: outputAddress net =<< eitherToMaybe (taprootScriptOutput (TaprootOutput key Nothing)).
  • Bitcoin Cash testnet3 is bchTest3. The value bchTest is now bchTest3, and its name, the one netByName reads, is bchtest3 instead of bchtest, in the way of bchTest4 and bchtest4. With a number on both testnets, neither looks like the default test network of Bitcoin Cash. Code that names the network, and data that stores its name, must change. The CashAddr prefix is still bchtest, so addresses do not change.

  • The constants of the networks match the reference nodes, Bitcoin Core 32.1 and Bitcoin Cash Node 29.2.0:

    • btc and btcTest have no checkpoints, as Bitcoin Core has none. The minimum chain work still protects a header sync.
    • The checkpoints of bch, bchTest3 and bchTest4 are those of Bitcoin Cash Node: 39, 19 and 19 of them. Two checkpoints were not in Bitcoin Cash Node: block 504031 of bch and block 1188697 of bchTest3, the blocks before the DAA. It checkpoints 504032 and 1188698, the first blocks of the DAA.
    • bchRegTest has edaHeight and daaHeight of Just 1, from the heights of 0 in Bitcoin Cash Node. Regtest does not retarget, so no difficulty changes.
    • The regtest seeds are those of the nodes: none on bchRegTest, and the placeholder dummySeed.invalid on btcRegTest, in place of localhost.
  • Outputs that hold tokens have an address on Bitcoin Cash. scriptToAddressBS and scriptToAddress take the token prefix off before they match the templates, on the Bitcoin Cash networks only. Before, such an output had no address: transaction e3abdbdc…f5a809 of block 978089 had none for four of its five outputs. The address is the plain form, CashAddr type 0 or 1, as for an output without tokens and as Bitcoin Cash Node shows it, so that the coins of one script stay under one address. A script field with a prefix that is not valid still has no address. On Bitcoin nothing changed.

    Upgrading an index of addresses. An index built with an earlier version left these outputs out of the balances of their addresses. With 3.0.0 the same stored scripts have addresses, so when such an output is spent, its value is taken from a balance it was never added to. Rebuild the index, or add the outputs that hold tokens to it, before running it with 3.0.0. haskoin-store does the second in its migration to database version 24.

    Nothing in the address says that an output holds tokens. A server that lists the unspent outputs of an address must give their tokens too, from splitTokenData, or a wallet may spend them as plain coins and burn the tokens.

  • splitTokenPrefix is written on top of splitTokenData. It accepts and refuses the same prefixes as before.

  • The benchmark headers checks before it times that its 2,000 headers connect, so a change that made them fail cannot look fast. It also times connectBlock of one header with and without a known anchor.

  • CI runs through the workflow that the Haskell packages of jprupp share in jprupp/tools, with the check of stack.yaml for local paths (check-stack-paths) and the cache of the Nix build kept per release of nixpkgs.

  • scripts/format and scripts/release are gone: haskell-format and haskell-release, from jprupp/tools, replace them. haskell-release builds and tests before it tags and uploads.

  • scripts/dev, the fast loop of work on the code, is gone too: haskell-dev, from jprupp/tools, replaces it, with the same three commands, build, test and docs. What it needs to know about this package, the slow spec modules, is in the new haskell-dev.toml.

  • The PSBT scripts under scripts/ are tests of the suite now, written in Haskell, and scripts/ is gone. They run against Bitcoin Core 32.1 on regtest, in a rootless Podman container that podman-test starts for each group of tests, and they need no Bitcoin Core, bitcoin-cli or jq on the machine. psbt_sign_test.sh became the group “Bitcoin Core 32.1 accepts the transactions of its PSBTs that the library signs”, which also checks that the library finalizes each PSBT into the transaction Bitcoin Core gives. create_complex_psbt_data.sh became the group “The PSBT of nine coins of every kind, which twelve wallets of Bitcoin Core 32.1 sign as the tests run”, with the checks of the files of data/; set HASKOIN_COMPLEX_PSBT to a path to keep its PSBTs in a file of the same form. Without Podman these tests are pending, and say why. The test suite depends on podman-test, which must be on Hackage before this release.

  • testSerial fails for a codec that writes bytes that it does not read. The identity test of a SerialBox read the value back and did not look at what was left of the bytes, so a Serial instance that writes a byte more than it reads passed. Such bytes are refused by decodeSerial, and they shift every value that follows in a stream. The test of a MarshalBox already failed for them. No type of this library was at fault. A program that uses testIdentity or testSerial on its own types may see a test fail that passed: the codec of that type then writes more than it reads.

  • The test suite needs hspec 2.10 or later, for the functions that run the identity helpers apart from the suite. The library still builds with hspec 2.7.1.

  • generateSharesWith and splitSecret of Haskoin.Crypto.Keys.Slip39 refuse a random value that is given twice. generateSharesWith takes the random values of a SLIP-39 split from its caller, one SplitRandom for each split of the scheme. The random shares of a split are handed out as they are, to its first members. So one SplitRandom given to several splits, a mistake that compiles and gives shares that combine, gave the first member of every group the same share, which was also the share of the first group: one person then held what a threshold of members of that group are needed for. The same holds for a random share given twice to one split, and for a source of generateSharesFrom that is stuck on the same bytes. Each of them is now refused: “Two of the random values are equal: each one must be drawn on its own”. Values that are drawn at random have at least 96 bits and are never equal, so no honest caller is refused. The check cannot tell a value that is not random, such as zeros, from one that is. The documentation of SplitRandom and of generateSharesWith now says what the values must be: uniform, secret, drawn independently, and used for one split only. It said only “with the random values given”.

Fixed

  • A Taproot input of another party no longer makes signPsbt or finalizePsbt refuse the whole PSBT. The parties of a transaction fill a PSBT in turn, and each signs its own inputs. signPsbt already left alone an input for which the signer holds no key, except a Taproot one: it applied every check of a Taproot input before it knew whether the signer held a key of it. A wallet could then not sign its own input:

    • While another input had no coin yet. A Taproot signature commits to the coin of every input, and the signer refused the PSBT as soon as one Taproot input had its coin, with “a Taproot signature needs the output every input spends”. It now signs the inputs that it can, and leaves every Taproot input as it is until every input has its coin, as Bitcoin Core does. That holds for a Taproot coin of the signer too: a caller that relied on the refusal now finds that input without a signature.
    • Beside a Taproot input with an entry that the library cannot use: an internal key, a derivation record or a control block whose 32 bytes are no point of the curve, or a leaf script that is not a list of opcodes. decodePsbt reads these, as Bitcoin Core 32.1 does, and Bitcoin Core signs the other inputs. The signer now passes over such an entry: it gives no key, and the other entries of the input are still signed.
    • Beside a Taproot input whose internal key does not give its coin. The signer refused the PSBT with “the internal key and the Merkle root do not give the output key of the coin”. It now adds no key path signature to such an input, and signs the others. Bitcoin Core does not refuse such a PSBT either. When it holds the internal key it adds a signature that verifies for no coin, which the signer does not copy: BIP 174 has a signer make only valid signatures.

    No BIP says what a signer does with a Taproot input that it cannot sign, so signPsbt now does as Bitcoin Core does: only the sighash type refuses the PSBT.

    finalizePsbt had the same fault. It now passes over a leaf script that it cannot read, and a script path signature under 32 bytes that are no point. It leaves as it is a Taproot coin whose output key is no point, which it refused with “the coin is not a Taproot output”. It also leaves as it is a signed Taproot input while another input has no coin, as Bitcoin Core does: the signature cannot be verified yet, so the input is not ready. It used to refuse the PSBT with “a Taproot signature needs the output every input spends”, and a caller that relied on that refusal now finds the input not final. A sighash type that the signer does not accept still refuses the whole PSBT, on any input that has its coin, as BIP 174 asks of a signer and as Bitcoin Core does.

  • finalizePsbt wants one leaf version in a leaf script entry of a Taproot input. The entry names the leaf version twice: in its value, and in its control block, which is the one a spend takes. When the two differed, the signer signed the leaf of the value, and the finalizer wrote a witness that spends the leaf of the control block: a leaf that nodes do not relay, or one that is not in the tree. BIP 371 defines the entry with one leaf version, and Bitcoin Core writes the same version in both places. The finalizer now leaves not final an input whose signed leaf names two, as Bitcoin Core does. The signer signs the leaf of the value, as Bitcoin Core does.

  • Two rules of the Taproot signer of signPsbt have a test now. No code changed for them: a key that a Signer gives is used only when it is the key that was asked for, on the key path and on a leaf, and a leaf that is a single key check is signed only when its leaf version is 0xc0.

  • signPsbt and finalizePsbt no longer take time that grows with the square of the size of a Taproot input. One input of a PSBT can hold any number of leaf scripts, derivation records and script path signatures. For each leaf script, the signer went through every record of the input, and the finalizer through every signature. An input with 1024 leaf scripts and 8192 records, a PSBT of 730 kB, took signPsbt 50 seconds, and an input with 4000 leaf scripts and 4000 signatures, a PSBT of one megabyte, took finalizePsbt 4 seconds: four times as long, or more, for twice the size. Whoever writes a PSBT can make such an input at no cost. It needs no valid signature, and the signer need not hold a key of it. A program that signs or finalizes a PSBT from another party could be made to stall. Both functions now find the record of a key and the signature of a leaf by a lookup, and take 0.10 and 0.05 seconds for these two inputs. The signer also went through the leaves that a record lists once for each place of a leaf script in the tree, which was a second product of two numbers: 1.5 seconds for one leaf at 4000 places and a record of 32,000 leaves, and now 0.3 seconds. The signatures and the final witnesses are the same as before.

  • verifyStdTx, judgeInputs, signTx, signPsbt and finalizePsbt no longer hash the whole transaction again for each Taproot input. The digest of a Taproot signature commits to hashes over all the inputs and all the outputs of the transaction. These functions computed them again for every input, so a transaction with twice as many Taproot inputs took four times as long. They now compute them once for a transaction, as Bitcoin Core does, with the new taprootTxHashes. The seconds for a transaction of 2000 Taproot inputs, and of 5000:

    Function 2000, before 2000, now 5000, before 5000, now
    verifyStdTx 1.22 0.09 7.8 0.54
    judgeInputs 1.23 0.10 8.0 0.46
    signTx 1.34 0.19 7.9 0.74
    signPsbt 1.35 0.17 7.5 0.45
    finalizePsbt 1.22 0.06 7.7 0.15

    judgeInputs needs no valid signature to do that work, so a server that judges transactions from the network paid it for whoever asked: 0.93 seconds for a transaction of 1739 inputs, the most that 400,000 weight units hold, and now 0.08 seconds. In a PSBT the cost was also inside one input: a signer that held the keys of 1024 leaves of one input computed 1024 digests, 0.71 seconds in a transaction of 2000 inputs and now 0.12 seconds. The digests, the signatures and the answers are the same as before. The documentation of the verifier said that its time did not grow with the square of the number of inputs, which was not true of Taproot inputs.

  • The digest of a Taproot input signed with SIGHASH_ANYONECANPAY has a test of its sequence number now. No code changed for it. That digest commits to the sequence number of its own input, and every such input of the BIP 341 vector has the sequence number 0xffffffff, so a digest that always held that number passed the tests. The new test states the two digests of a transaction that Bitcoin Core 32.1 relayed and mined on regtest, whose inputs have the sequence numbers 0xfffffffe and 0xfffffffd.

  • verifyStdTx, judgeInputs, signTx, signPsbt and finalizePsbt no longer hash the whole transaction again for each SegWit version 0 input, nor for each input on Bitcoin Cash. The digest of BIP 143, which those inputs use, holds three hashes over all the inputs and all the outputs of the transaction. These functions computed them again for every input, so a transaction with twice as many inputs took four times as long. They now compute them once for a transaction, as Bitcoin Core and Bitcoin Cash Node do, with the new txSigHashes. The seconds for a transaction of 2000 inputs, and of 5000:

    Function and coins 2000, before 2000, now 5000, before 5000, now
    verifyStdTx, P2WPKH 0.56 0.06 3.3 0.14
    judgeInputs, P2WPKH 0.57 0.06 3.5 0.14
    signTx, P2WPKH 0.61 0.07 3.7 0.18
    signPsbt, P2WPKH 0.62 0.11 3.4 0.29
    finalizePsbt, P2WPKH 0.56 0.06 3.4 0.15
    verifyStdTx, Bitcoin Cash 0.56 0.06 3.3 0.14
    judgeInputs, Bitcoin Cash 0.59 0.06 3.4 0.14
    signTx, Bitcoin Cash 0.60 0.08 3.8 0.20

    judgeInputs needs no valid signature to do that work, so a server that judges transactions from the network paid it for whoever asked. The digests, the signatures and the answers are the same as before. A legacy input of Bitcoin is not faster: its digest hashes a copy of the whole transaction by its design, in Bitcoin Core too.

  • verifyStdTx, judgeInputs and signTx no longer walk the lists of a transaction up to each input. The verifier and judgeInputs read the input script, the witness and the coin of an input by its index in constant time. signTx signs each input on its own input script and witness stack, and puts the transaction together once. This is for an input of any kind: on a transaction of 5000 Taproot inputs, verifyStdTx goes from 0.54 to 0.14 seconds, judgeInputs from 0.46 to 0.16 and signTx from 0.74 to 0.34. The signed transactions, the answers and the error messages are the same as before.

  • mergeTxs no longer hashes the whole transaction again for each input on Bitcoin Cash, and no longer walks the lists of the transactions up to each input. It merged each input with txSigHash, which on a network with a fork id computed the three hashes of BIP 143 again at each call, and it read and wrote each input by its place in the lists. It now takes the hashes once (txSigHashes), merges each input on its own input scripts, and puts the transaction together once. The seconds for a transaction of 2000 inputs, and of 5000, that two cosigners each signed in a copy, for coins of the P2SH multisig 2 of 3:

    Network and hash type 2000, before 2000, now 5000, before 5000, now
    Bitcoin Cash, SIGHASH_ALL 0.95 0.19 5.5 0.49
    Bitcoin, SIGHASH_ALL 2.3 2.1 14.8 13.1
    Bitcoin, with ANYONECANPAY 0.43 0.22 2.4 0.58

    On Bitcoin Cash the time now grows with the size of the transaction. On Bitcoin the digest of a legacy input hashes a copy of the whole transaction by its design, in Bitcoin Core too. That is most of the time of a merge there, so mergeTxs gains little on Bitcoin, unless the signatures are ANYONECANPAY. A transaction that nodes relay holds about 340 such inputs: for 250 of them the merge goes from 0.035 to 0.023 seconds on Bitcoin Cash, and stays at 0.06 on Bitcoin. The merged transactions and the error messages are the same as before, and mergeTxInput keeps its type and its results. The coins are best given in the order of the inputs: each input still looks for its coin from the start of the list.

  • The text, the order and the append of a derivation path take time by the length of the path, and no longer by the square of it. A path holds its last step outermost, and three functions walked the earlier steps again at each step: pathToStr copied their text, compare tested them for equality and then compared them, and ++/ built the rest of its second path again. A path with twice as many steps took four times as long. Every text form of a path goes through pathToStr: the Show and JSON instances of DerivPath, HardPath, SoftPath and ParsedPath, and the Show of the Derivation and TapDerivation records of a PSBT. A path can be of any length: parsePath, the JSON and binary decoders and the derivation records of a PSBT read one of any number of steps, as Bitcoin Core does. So a program that shows a path that it was given, for example in an error message about a PSBT, could be held by a small file: a record of 16000 steps is a PSBT of 64 KB. Each of the three functions now walks a path once. The seconds on the release build, by the number of steps, for paths whose indices have one digit:

    Function 4000, before 16000, before 32000, before 32000, now 1000000, now
    pathToStr 0.14 2.8 12.5 0.004 0.13
    compare, twice 0.045 0.45 1.7 under 0.001 0.008
    ++/ 0.035 0.70 2.9 0.004 0.18

    The texts, the order and the appended paths are the same as before. A shorter path sorts first, then the first step that differs decides, a soft step before a hardened one: the order of the index lists of pathToList. That order had tests that a wrong compare could pass: the fixed cases used <, which calls compare with its arguments exchanged, and two random paths share no step. It is now stated with compare in both directions on fixed pairs, and on random pairs that differ in one step. ++/ has a test with a hardened step in its second path.

  • judgeInputs verifies a multisig of Bitcoin Cash with Schnorr signatures whose field of bits is the byte 0x81. That is two signatures of eight keys, by the first key and the last. The field of bits takes the place of the empty item of a multisig, and every block wants the shortest push of it, which for the byte 0x81 is the opcode OP_1NEGATE. judgeInputs read OP_1 to OP_16 there and not OP_1NEGATE, so it answered InputUndecided for a spend that Bitcoin Cash Node 29.2.0 takes. It now answers InputVerified. The second reading of an input script now reads every push opcode (pushOpData), OP_0 too. So the spend of a key hash coin with OP_0 or OP_1NEGATE where the key goes is InputForged, as it was already for OP_1 to OP_16 and for any other item that is not the key: no key hashes to the hash that the coin names but its own. It was InputUndecided.

  • The README said that verifyStdTx checks signatures “by the rules that nodes relay by”. It does not: it answers True for some inputs that a block may hold and nodes do not relay, a SegWit input signed with an uncompressed key, a Taproot input with an annex and, on Bitcoin, an input script with a longer push. It answers False for others, such as a high S. The README now says so under “Security notes”, and so do the comments of verifyStdTx and verifyStdInput, which also name the key in the hybrid form among the inputs that are refused. The functions did not change with that correction. They changed later in this version: see “no longer verify an input that a block may hold” above.

  • On Bitcoin Cash, an ECDSA signature whose DER form is 64 bytes is no longer read as an ECDSA signature. On Bitcoin Cash a signature of 64 bytes before its hash type byte is a Schnorr signature, whatever its bytes. Bitcoin Cash Node 29.2.0 verifies it as one in OP_CHECKSIG, where it fails, and takes no signature of that length in a multisig without a field of bits. It refuses the transaction both times (“mandatory-script-verify-flag-failed”) and drops the peer that sent it. A valid ECDSA signature of that length exists: its r and s take 29 bytes each, and a computer makes one in a minute, with a key of its own. verifyStdInput and verifyStdTx said True for an input signed with one, and judgeInputs said InputVerified.

    On a network with a fork id, decodeTxSig now refuses a signature of 64 bytes: “Non-canonical signature: a signature of 64 bytes is a Schnorr signature on this network”. So do the binary and JSON forms of TxSignature, and decodeInput does not read an input that has one. verifyStdInput and verifyStdTx answer False. judgeInputs reads the signature as a Schnorr signature, which does not verify: InputForged for a coin of one key and the hash type “all”, InputUndecided for a multisig. Blocks of Bitcoin Cash before May 2019 could hold such a signature, and decodeInput no longer reads its input. Nothing changes on Bitcoin, where it is an ordinary signature: Bitcoin Core 32.1 put one in a block on regtest, and the library verifies it.

    The new isCashSchnorrLength is the test of that length, to check with isCanonicalHalfOrder on a signature read by decodeStrictSig. The signer uses it too. makeSignature, and so signInput, signTx and signPsbt, said that they refuse what a node would refuse, and could hand out such a signature on Bitcoin Cash, once in 2^49 by the specification. They now fail with “makeSignature: the signature is 64 bytes long, which this network reads as a Schnorr signature: change the transaction and sign again”. The nonce is that of RFC 6979, so the same transaction gives the same signature again. encodeTxSig still writes such a value when a caller builds one.

  • On Bitcoin Cash, the verifiers no longer verify an input in an encoding that no block of Bitcoin Cash holds. Bitcoin Cash applies to every block three rules of encoding that Bitcoin applies only to the transactions it relays: the S of an ECDSA signature is low (LOW_S), a key is compressed or uncompressed (STRICTENC), and an input script pushes each item by the shortest push that holds it (MINIMALDATA). They are among the MANDATORY_SCRIPT_VERIFY_FLAGS of Bitcoin Cash Node 29.2.0, which refuses a transaction that breaks one (“mandatory-script-verify-flag-failed”) and drops the peer that sent it. The library applied them as Bitcoin does:

    • judgeInputs said InputVerified for a valid ECDSA signature whose S was replaced by the order of the curve less S. Anyone can change a signature seen on the network that way, without a key.
    • judgeInputs said InputVerified for the spend of a coin locked to the hash of a key in the hybrid form, 65 bytes that start with 0x06 or 0x07. Whoever makes the coin chooses the key, so anyone could make one.
    • verifyStdInput and verifyStdTx said True, and judgeInputs said InputVerified, for an input script that pushes a signature, a key or a redeem script by OP_PUSHDATA1, 2 or 4 where a shorter push holds it. judgeInputs said so too when the signature is a Schnorr signature, when the coin holds tokens, and when the field of bits of a multisig with Schnorr signatures is pushed as data in place of its opcode. Anyone can change the pushes of an input seen on the network, without a key.

    A caller that sends a transaction to its peers when every input is InputVerified sent these, and each node of Bitcoin Cash then closed its connection. On a network with a fork id the answers are now False and InputUndecided, also when the signature does not verify. An input in the encoding that every wallet makes is verified as before. Nothing changes on Bitcoin with this entry: there a block may hold the three forms, and a high S and a hybrid key were InputUndecided already. A longer push is no longer verified on Bitcoin either: see “no longer verify an input that a block may hold” above.

  • The documentation of isCanonicalHalfOrder, decodeStrictSig, verifyHashSig and decodePubKey gave the rules of Bitcoin as the rules of consensus. A low S and the form of a key are rules of the relay policy on Bitcoin and consensus rules on Bitcoin Cash. Each comment now says what holds on each chain, and that of verifyHashSig says that a signature with a high S verifies. To verify a signature of Bitcoin Cash with these functions, check isCanonicalHalfOrder too, and read the key with decodePubKey and not with importPubKey. The README says so under “Bitcoin Cash”. The functions themselves did not change.

  • decodeOutput no longer reads a multisig script whose keys are pushed by OP_PUSHDATA1, 2 or 4, and the signers and verifiers no longer sign or verify the spend of such a coin over another script. The signature of a multisig input covers the bytes of the script of its coin. decodeOutput read such a script as the same PayMulSig as the script with direct pushes, and a ScriptOutput does not keep the form of a push. So signTx, signPsbt, verifyStdInput, verifyStdTx and judgeInputs took the digest on what encodeOutput writes, the script with direct pushes, which is not the script of the coin:

    • signTx and signPsbt signed a bare coin of this kind with a signature that does not open it, and verifyStdTx and judgeInputs answered True and InputVerified for that spend. Bitcoin Core 32.1 refuses it in a block.
    • On Bitcoin Cash every push must be the shortest one, in a block too, so such a coin can never be spent. judgeInputs said InputVerified for its spend, with ECDSA signatures or with Schnorr signatures, bare or locked to the hash of the script. Bitcoin Cash Node 29.2.0 drops the peer that sends that transaction. Whoever makes the coin chooses its script, so anyone could make one.
    • With one more input that spends such a coin, the Taproot signature of signTx did not verify on a node, and verifyStdInput refused the one that does: the Taproot digest covers the script of every coin spent.
    • finalizePsbt refused a whole PSBT for a signature of Bitcoin Core on such a coin (“does not verify”), and signPsbt refused one for a coin locked to the hash of such a script (“the redeem script does not hash to the coin”), which was not true.

    Now decodeOutput, and so decodeSerial and parseJSON of a ScriptOutput, answer Left for such a script, as for any script that is no standard output: a PayMulSig stands for one script, the one encodeOutput writes. judgeInputs answers InputUndecided, and signPsbt and finalizePsbt leave the input as it is. This is stricter than decodescript of Bitcoin Core, which calls the script multisig, and the same as Bitcoin Cash Node. A multisig with direct pushes, which is what every wallet makes, is read, signed and verified as before. The library cannot sign the spend of such a coin: on Bitcoin a block may hold that spend, and nodes do not relay it.

  • judgeInputs no longer says InputVerified for a witness key hash nested in a script hash whose program is pushed by OP_PUSHDATA1, 2 or 4. BIP 141 wants the input script to be exactly the push of the program, Bitcoin Core takes the shortest push only, and no block holds another form. verifyStdInput refused the three forms already. judgeInputs reads an input that verifyStdInput refuses a second time, to tell a forged input from one it cannot judge, and that reading took a push of any form. The signature then verified, because the BIP 143 digest does not cover the input script. Anyone can make such a copy of a valid spend, without a key. The answer is now InputUndecided, also when the signature does not verify.

  • On a network without a fork id, judgeInputs says InputVerified only where verifyStdInput says True. The second reading takes more than a node does, so there it now only tells InputForged from InputUndecided. This changes the answer for an input that a block may hold and that nodes do not relay, when its signature verifies: a signature with a high S and a hybrid key were InputVerified and are InputUndecided. A caller that sends a transaction to its peers only when every input is InputVerified no longer sends those. On Bitcoin Cash nothing changed: the second reading still verifies what verifyStdInput does not read there, Schnorr signatures and coins that hold tokens.

  • verifyStdInput, verifyStdTx and judgeInputs no longer verify the spend of a Taproot multisig leaf of more than 999 keys. No block holds such a spend. The stack holds at most 1000 items after each opcode (BIP 342): the witness puts an item there for each key, and the script starts with the push of a key on top of them. So 999 keys is the most, the limit of multi_a in BIP 387 and MAX_PUBKEYS_PER_MULTI_A of Bitcoin Core. The three functions answered True, True and InputVerified for a leaf of 1000 keys or more when its signatures verified, and Bitcoin Core 32.1 refuses that spend in its mempool and in a block (“Stack size limit exceeded”). Whoever makes the coin chooses the leaf, so anyone could make such a transaction. The answers are now False, False and InputUndecided. A leaf of 999 keys or fewer is verified as before.

  • verifyStdInput, verifyStdTx and judgeInputs no longer verify a pay-to-witness-script-hash multisig input whose witness script is not the script the coin commits to. A multisig script can be written with each key after OP_PUSHDATA1, 2 or 4: the same keys, other bytes, another hash. BIP 141 wants the hash of the witness script to be the witness program, so no block holds a spend with such a copy of the script. decodeWitnessInput read the copy as the same PayMulSig, and the verifiers then took the hash and the digest on what encodeOutput writes for that value, which is the script of the coin. So they answered True, True and InputVerified, for the native form and for the form nested in a script hash, where Bitcoin Core 32.1 refuses the spend in its mempool and in a block (“Witness program hash mismatch”). Anyone can make such a copy of a spend, without a key: the witness is not part of the transaction id, and the signatures stay as they are. decodeWitnessInput now refuses a witness script that encodeOutput would write back as other bytes, as decodeInput does for a redeem script since 1.6.0, and the three answers are False, False and InputUndecided. A coin that does commit to such a script was not verified before and is not now: a block may hold its spend, and nodes do not relay it.

  • combineShares and combineMnemonics of Haskoin.Crypto.Keys.Slip39 refuse more than 256 shares, before any other work. A backup has at most 16 groups of 16 members, so a longer list rebuilds nothing. It was refused for another reason, but only after its shares were put in groups in time that grew with the square of their number: 6.7 seconds for 32,000 copies of one share in a build without optimisation, which are 4 MB of text, and four times as long for twice as many. combineMnemonics also read every mnemonic first. Both now count their input before anything else, and answer “There are 32000 shares, but a backup has at most 256” in the time it takes to walk the list. The shares of a group are also gathered in time by their number. No answer changes for 256 shares or fewer.

  • cash32decodeType of Haskoin.Address.CashAddr refuses a string that is too long before any other work. No valid string has more than 112 characters after its colon, since the largest hash that a version byte can name is 64 bytes. A longer one was refused too, but only after its data was turned into bytes through a list: one megabyte of text with a valid checksum took a second in a build without optimisation and held 564 MB. The function now reads the last 113 characters and refuses the string if the colon is not among them, in a time that does not depend on its length. cashAddrDecode, cashToAddr and textToAddr already had that bound. This one is for a program that reads a CashAddr under another prefix than those of the library, which is what the function is exported for. The prefix keeps no limit, as in the specification, and costs about a dozen bytes for each character. No answer changes.

  • bech32Encode of Haskoin.Address.Bech32 checks the length first. It built the whole string, then refused it if it had more than 90 characters: a million words took a third of a second in a build without optimisation and held 178 MB. It now counts the words up to the first one that does not fit, so a list that is too long is not read to its end. No answer changes. segwitEncode checked the witness program before the call, so no address function of the library was open to it.

[2.0.1] - 2026-11-18

Fixed

  • connectBlocks is fast on Bitcoin Cash again. It searched for the aserti3-2d anchor block for every header: a binary search over the whole chain with a median time past at each step, about 1,500 reads at height 100,000 (this entry said “some hundreds” until a review counted them). A node syncing Bitcoin Cash headers from a database took about 10 ms per header, 20 seconds for each headers message of 2,000. The anchor of a block is also the anchor of all its descendants, so connectBlocks now finds it once for a run of headers. The new benchmark headers connects 2,000 headers on top of 100,000 in memory: 4.7 s before, 72 ms after, at -O1.

Added

  • nextWorkRequiredWith: nextWorkRequired with the anchor block of the parent already found, for callers that connect many headers.

[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 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

  • 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.
  • encodeHexReversed and hexEncodingReversed, the hex of bytes in reverse order, as hashes are shown, as text and as JSON.

[1.6.3] - 2026-11-14

Changed

  • Writing and reading addresses is faster, for servers that show an address for every input and output. Measured on 20,000 addresses:
    • scriptToAddressBS tells the four standard kinds of output by their bytes, without parsing the script: 3 ms where it took 33, and the same answers as the parser for any script, which the tests check.
    • encodeBase58 divides by 58^5 in machine words instead of building an Integer, and checkSum32 reads its four bytes directly: Base58Check 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

Added

  • judgeInputs says of each input of a transaction whether its signature verifies, is forged, or cannot be told without running a script (InputVerdict). verifyStdTx answers no both for a forged signature and for a script it does not read; to refuse a transaction before sending it, the two have to be told apart. “Forged” is said only of a coin locked to one key, spent with the items such a coin takes and a hash type of all.
  • verifyCashSchnorr verifies a Schnorr signature of Bitcoin Cash, which is not the one of BIP 340 and has no function in libsecp256k1. It is held to the test vectors of Bitcoin Cash Node.
  • splitTokenPrefix takes the token prefix off the script of an output of Bitcoin Cash, and txSigHashCashToken is the digest of a coin that holds tokens. judgeInputs uses both, and reads Schnorr signatures, so it verifies inputs on Bitcoin Cash that verifyStdInput does not. The tests hold it to two transactions signed by Bitcoin Cash Node 29.2.0, one of them spending tokens.
  • judgeInputs verifies a multisig of Bitcoin Cash signed with Schnorr signatures, where a field of bits in place of the empty first item says which keys signed, as OP_CHECKMULTISIG of Bitcoin Cash Node reads it.
  • verifyStdInput, verifyStdTx and judgeInputs verify the multisig of Taproot: a script path whose leaf is multi_a of the output descriptors, with OP_CHECKSIGADD.

Changed

  • stack.yaml builds against secp256k1-haskell 2.0.1. The README’s Stack example names that version and the current haskoin-core release. The package and its bounds are unchanged.
  • The README shows a badge with the status of CI on master.
  • The Nix CI job deletes Stack’s cached Setup programs before building. One restored from an older nixos-unstable cache was linked against Nix store paths missing on the runner, and the build failed with “posix_spawnp: does not exist”.

[1.6.1] - 2026-11-06

Changed

  • encodeBase58, encodeBase58Check, cashAddrEncode, cash32encode and cash32encodeType, and with them addrToText and the JSON form of addresses, are faster. Base58 divides its big integer by 58^10 instead of once per digit and builds its bytes directly instead of a String. CashAddr looks its characters up in a ByteString instead of with (!!) on a String, converts to five-bit groups without lists, and unrolls the generators of its checksum. A P2PKH address takes 1.1 µs instead of 5.6 µs in CashAddr and 4.3 µs instead of 5.9 µs in Base58. The output is the same: 120,061 encodings of random payloads are byte for byte the same before and after.

[1.6.0] - 2026-11-06

Added

  • Haskoin.Crypto.Keys.Slip39: Shamir’s secret-sharing for mnemonic codes, SLIP-0039, as a standalone module. generateMnemonics splits a master secret, encrypted with a passphrase, into share mnemonics under a two-level scheme of groups and members, and combineMnemonics rebuilds it from a threshold of them. generateShares and generateMnemonics draw their random bytes from the operating system, through getEntropy of the entropy package; generateSharesFrom takes the source of random bytes as an argument, and generateSharesWith the identifier and the random values themselves, so that a split can be reproduced. encodeShare and decodeShare read and write one share, with its checksum, padding and ranges checked as the specification requires; a share has at most 1023 words, the length the checksum covers, which is a value of 1270 bytes. encryptMasterSecret and decryptMasterSecret are the passphrase step, and both refuse a passphrase outside printable ASCII, as the specification requires; decryptMasterSecretBytes takes the passphrase as unchecked bytes, to recover shares of software that allowed other characters. splitSecret, recoverSecret and interpolate are the sharing over GF(256), and rs1024Checksum the checksum. No error text and no Show instance holds a word or a value of a share: an unknown word is named by its position. The 45 vectors of the reference implementation, a share set of Sparrow’s library, and split cases with fixed random values made by an independent Python implementation of the specification, test/Haskoin/Crypto/Keys/slip39_verify.py, check it. The word list is data/slip39_wordlist.txt, the file of the specification, and its SHA-256 is checked.
  • tryDerivePath and tryDerivePubPath in Haskoin.Crypto.Keys.Extended derive along a path and return an error value when the path cannot be followed. Use them for a path that comes from outside, such as the path of a PSBT record. derivePath and derivePubPath throw DerivationException in that case, as before.
  • maxRedeemScriptSize (520) and maxWitnessScriptSize (10,000) in Haskoin.Script.Standard are the largest scripts that a pay-to-script-hash and a pay-to-witness-script-hash output can commit to and still be spent: MAX_SCRIPT_ELEMENT_SIZE and MAX_SCRIPT_SIZE of Bitcoin Core. p2shScriptHash and p2wshScriptHash give the hash of a script for those outputs, and fail above the limit.
  • p2shP2wpkhAddr in Haskoin.Address is the P2SH-P2WPKH address of a public key hash.
  • SigHashFlag has a Bounded instance.
  • decodeTx in Haskoin.Transaction.Common reads a transaction from bytes that hold the transaction and nothing else, as DecodeHexTx requires in Bitcoin Core. deserialize reads a transaction from the front of a longer input, as a block needs it to, and does not notice bytes that follow. Use decodeTx for a transaction that arrives on its own.
  • dustThreshold in Haskoin.Transaction.Builder gives the amount below which nodes do not relay an output of a kind, as GetDustThreshold computes it in Bitcoin Core at the default dust relay fee: 546 satoshi for pay-to-public-key-hash, 294 for pay-to-witness-public-key-hash, 330 for pay-to-witness-script-hash and Taproot. chooseCoins can return a change below it, and its documentation now says to leave such a change to the fee.
  • maxStandardTxWeight (400,000) in Haskoin.Transaction.Builder is the weight above which nodes do not relay a transaction: MAX_STANDARD_TX_WEIGHT of Bitcoin Core, and the 100,000 bytes of MAX_STANDARD_TX_SIZE of Bitcoin Cash Node.
  • data/core_signed_txs.json holds 97 transactions that Bitcoin Core 32.1 signed on regtest, one for each of 16 kinds of coin and each hash type. The tests verify them with verifyStdTx, so that the verifier is checked against signatures the library did not make.
  • arbitraryKeyPairC generates a key pair in compressed form.
  • maxPayloadSize in Haskoin.Network.Message gives the largest payload a message of a command may have on a network, and getMessage applies it. On Bitcoin Cash every message but block, cmpctblock and blocktxn is limited to 2 MiB, the new maxProtocolMessageSize of Network, as CMessageHeader::IsOversized does in Bitcoin Cash Node. The limit was 64 MB for every message, and one 33.5 MB getblocktxn took 19 seconds and 5.7 GiB to parse. A node should use maxPayloadSize on the message header before it buffers a payload.
  • getCompactBlock, getGetBlockTxn and getBlockTxn in Haskoin.Network.CompactBlock read the compact block messages of a network. On Bitcoin a transaction position above 65535, the new maxCompactBlockIndex of Network, fails the parse, and so does a compact block of more than 65535 transactions, as in BIP 152 and Bitcoin Core. Bitcoin Cash keeps 32 bits, as Bitcoin Cash Node. getMessage uses them.
  • getNetworkTx in Haskoin.Network.Data reads a transaction as a peer of the network sends it: without the SegWit format on a network that has no SegWit. getMessage uses it for tx, block, blocktxn and cmpctblock.
  • minimumChainWork in Network is the nMinimumChainWork of Bitcoin Core 32.1 and of Bitcoin Cash Node. Once the best block has that work, connectBlock and connectBlocks refuse a new header whose chain has less, which bounds cheap forks from far below the tip. A node that is still syncing below that work is not protected by this.
  • getVarIntListMax, and the limits maxInvSize (50000), maxAddrSize (1000), maxHeadersSize (2000), maxLocatorSize (101) and maxFilterHashes (2000) in Haskoin.Network.Common. The parsers of inv, getdata, addr, addrv2, headers, getheaders, getblocks and cfheaders fail above them, as soon as the count is read.
  • extractIndexedMatches and merkleBlockIndexedTxs in Haskoin.Block.Merkle give the position of each matching transaction of a partial Merkle tree. maxMerkleFlagBits is the number of flag bits a valid proof can use.
  • leafHashBytes in Haskoin.Transaction.Taproot is the tapleaf hash of a script given as bytes, for a script that is not a list of opcodes. checkTapTree tells whether every leaf of a script tree can be spent: it fails for a node deeper than 128, which no control block can prove, and for a leaf version that is odd or is 0x50. Run it on a tree before you give out its address. scriptPathScriptBytes gives the script bytes of a script path spend as they are in the witness. taprootSignature builds a TaprootSignature and fails for a hash type that Taproot does not define.
  • data/taproot_mainnet_spends.json holds 24 Taproot script path spends from Bitcoin mainnet blocks 840000 and 900000, with scripts of 34 to 635 bytes. The tests check that each one is read and that its script and control block commit to the output key of the coin it spends.
  • requirePreviousTx on a PSBT Signer. With it, the signer refuses a SegWit version 0 coin that is known from its witness output only, since the amount of such a coin is a claim of whoever wrote the PSBT (CVE-2020-14199). keySigner and xPrvSigner set it.
  • inputCoins and psbtFee: the coin of each PSBT input with whether it comes from the previous transaction, and the fee when every coin does.
  • psbtPartialTransaction: the transaction of a PSBT that is still being signed.
  • data/psbt_complex_core32.json: nine coins of every kind, signed by Bitcoin Core 32.1 without finalizing.

Changed

  • unmarshal and unmarshalLazy fail when bytes are left over after the value. They used to read a value from the start of the input and ignore the rest, so two different byte strings could read as the same public key, signature or extended key. Code that reads a value from the start of a longer stream must run marshalGet itself.
  • The binary form of XPubKey holds a compressed public key in exactly 33 bytes, as BIP 32 defines it and as xPubImport already required. A key in the 65-byte form used to be read.
  • decodeStrictSig, and with it the binary and JSON forms of Sig, apply the encoding rule of BIP 66 and nothing more. A signature with a high S value is now read. Low S is a relay rule of Bitcoin Core (SCRIPT_VERIFY_LOW_S), not a consensus rule of Bitcoin, and its blocks hold signatures with a high S. On Bitcoin Cash it is a consensus rule. isCanonicalHalfOrder tests the relay rule. The form of a transaction signature, TxSignature, still applies it. The signers make low-S signatures, as before.
  • makeXPrvKey throws DerivationException for a seed that is not 16 to 64 bytes long, the range that BIP 32 gives and that Bitcoin Core enforces. A seed of any length used to give a master key, the empty string included, and anyone can compute the keys of such a wallet. A wallet that was made from a seed of another length can still be opened without this function: its master key is XPrvKey 0 "00000000" 0 chain key, where key and chain are the two halves of hmac512 "Bitcoin seed" seed.
  • applyPath returns Left for a path that leads below depth 255, which no key can have. It used to throw DerivationException, although its type promises an error value.
  • The path constructors :| and :/ throw DerivationException for an index of 2^31 or more. Such a path could be built before, but its text and binary forms did not read back to the same path, and deriving along it threw. The two constructors are now pattern synonyms. Code that builds and matches paths with them compiles as before.
  • fromMiniKey requires a mini key to start with the letter S and to hold only characters of the Base58 alphabet, as the format defines. One arbitrary string of 22 or 30 characters in 256 used to be read as a private key.
  • getInteger reads only the encoding that putInteger writes: a tag byte of 0 or 1, a sign byte of 0x01 or 0xff, and the shortest bytes that hold the number. Several other byte strings used to read as the same number. Data written by putInteger reads as before. The reader also takes close to linear time now. A number of 400 KB used to take 54 seconds.
  • getIntMap refuses keys that are not in ascending order, which is how putIntMap writes them. A key given twice used to be read, and its second element silently replaced the first.
  • convertBits returns Nothing for a width that is zero or negative, where it used to loop forever, and for a digit that does not fit the width it is converted from, whose high bits it used to drop.
  • bech32Encode returns Nothing for a five-bit word above 31. It used to raise an array index error.
  • The JSON parser of Sig no longer copies the text it refuses into its error message.
  • data/key_io_valid.json and data/key_io_invalid.json are the files of Bitcoin Core 32.1, with its Bech32m and testnet4 vectors. The tests run every vector through textToAddr and fromWif, as key_io_tests.cpp does.
  • payToScriptAddress, payToWitnessScriptAddress and payToNestedScriptAddress return Either String Address, and toP2SH and toP2WSH return Either String ScriptOutput. They fail for a redeem script above 520 bytes and for a witness script above 10,000 bytes. A pay-to-script-hash redeem script is a push of the spending input, and consensus limits a push to 520 bytes, so coins sent to the hash of a longer script can never be spent. payToScriptAddress used to give an address for a multisig of 16 to 20 compressed keys (547 to 684 bytes), or of 8 or more uncompressed keys, and Bitcoin Core rejects every spend of such a coin with “Push value size limit exceeded”. Fifteen compressed keys fit, and twenty still fit a pay-to-witness-script-hash output. These functions also return the failure of encodeOutput for a multisig that no script can express, where payToScriptAddress used to raise an error call.
  • deriveMSAddr and derivePathMSAddr return Either String (Address, RedeemScript), and deriveMSAddrs and derivePathMSAddrs return Either String of their list. They fail for more than 15 keys, whose address would be unspendable as described above, and for a number of required signatures that is not between 1 and the number of keys, which used to raise an error call when the address was forced. Coins that were sent to an address these functions gave for 16 to 20 keys are lost: no spend of them is valid.
  • scriptToAddress, scriptToAddressBS and outputAddress take the Network as their first argument and give an address only for an output kind that the network has. A witness program has no address on Bitcoin Cash, and a 256-bit script hash (OP_HASH256 <32 bytes> OP_EQUAL) has none on Bitcoin, where Bitcoin Core reports that script as non-standard. Without the network these functions returned an address that has no text form on the chain it came from, and the JSON encoder of Address throws for such an address. One such output is in Bitcoin block 211997 (transaction a4bfa8ab6435ae5f25dae9d89e4eb67dfa94283ca751f393c1ddc5a837bbc31b, output 0), so an indexer that encoded the addresses of outputs failed on that transaction. Every address these functions return now has a text form on the network.
  • decodeInput only reads a pay-to-script-hash input whose redeem script is in the form encodeOutput writes. A multisig redeem script whose keys are pushed with OP_PUSHDATA1 used to decode, and inputAddress then gave the hash of the re-encoded script, an address that never held the coin. Such an input now fails to decode, so inputAddress is always the hash of the redeem script bytes of the input, and encoding a decoded input never rewrites its redeem script. Spending such a script breaks the MINIMALDATA rule of the relay policy, so standard transactions are not affected.
  • decodeInput reads a NestedWitnessInput only when the witness program is a direct push, as BIP 141 requires (“the scriptSig must be exactly a push of the BIP16 redeemScript”). A program pushed with OP_PUSHDATA1 used to decode, although such an input is invalid by consensus.
  • inputAddress gives no address for a redeem script above 520 bytes.
  • txSigHashForkId writes the hash type as four bytes on a network without a fork id, as SignatureHash of Bitcoin Core does for a SegWit input. It used to keep the low byte only, while txSigHash wrote all four. Nothing changes for a hash type that fits in one byte, which is every hash type a signature can carry.
  • cashAddrDecode, and with it textToAddr and the JSON parser of Address on Bitcoin Cash networks, refuse a string longer than the prefix of the network, the colon and 112 characters before any other work. No valid address is longer, since the largest hash of the format is 64 bytes. A string of 1 MB used to take 1.5 seconds and several hundred megabytes of memory, and now takes less than a millisecond.
  • cash32decode and cash32decodeType refuse a prefix that is not made of letters only, as the decoder of Bitcoin Cash Node does. A digit or a second colon in the prefix used to be read.
  • cash32encode returns Maybe Cash32. It fails for a prefix that is empty or not made of ASCII letters, and it writes an uppercase prefix in lowercase. It used to write strings that cash32decode refuses: with an empty prefix, a digit, a colon, or a prefix of another case than the data.
  • The Read instance of Address goes through witnessAddress and cashAddress for the two generic kinds. The derived instance read a witness version above 16, a program of any length and a CashAddr type above 15, which no other function builds.
  • enumFrom, enumFromTo, enumFromThen, enumFromThenTo, succ and pred of SigHashFlag walk the five flags in the order of their constructors. [SIGHASH_ALL ..] and succ SIGHASH_SINGLE used to raise “Not a valid sighash flag”, because the values of the flags are not consecutive.
  • The generators arbitraryMulSigSHInput, arbitraryMulSigSHInputC, arbitraryMulSigSHInputFull and arbitraryMulSigSHInputFullC draw a redeem script of at most 520 bytes. More than half of the inputs they drew could not exist. arbitraryP2SHMSParam, arbitraryP2SHMSParamC, arbitraryP2SHMSOutput and arbitraryP2SHMSOutputC are the new generators behind them. arbitrarySHSigInput and arbitraryPartialTxs use at most 7 keys for the same reason.
  • arbitraryScriptOutput draws a 256-bit script hash output on networks that have CashAddr, and arbitraryScriptInput draws a nested witness input only on networks that have SegWit. arbitraryBitcoinAddress draws a Taproot address one time in six, through the new arbitraryTaprootAddress, and arbitraryBitcoinCashAddress a payable token-aware address one time in five, through the new arbitraryTokenAddress.
  • makeSignature, and with it signTx, signInput, signNestedWitnessTx and signPsbt, refuse a hash type that no node accepts, with the reason: one that is not SIGHASH_ALL, SIGHASH_NONE or SIGHASH_SINGLE with or without SIGHASH_ANYONECANPAY (the test of IsDefinedHashtypeSignature in Bitcoin Core), the fork id flag on a network without a fork id, and a value that does not fit in the one byte a signature carries. On Bitcoin Cash this refuses SIGHASH_UTXOS (0x20), whose digest the library does not compute. The types 0x00, 0x04, 0x21, 0x41 and 0x80 used to be signed, and the result was a transaction that nodes do not relay. A type with upper bytes set, such as 0x101, gave a signature that does not verify. signTx still signs SIGHASH_NONE and SIGHASH_SINGLE when the SigInput asks for them: check the hash type of a SigInput that comes from someone else.
  • makeSignature refuses a pay-to-script-hash coin without its redeem script, with a redeem script above 520 bytes, or with one that does not hash to the coin, and the same for a pay-to-witness-script-hash coin and its witness script, above 10,000 bytes. It used to sign whatever script it was given, and the output script itself when it was given none. Such a signature spends nothing.
  • makeSignature refuses a SegWit coin, and signTx a Taproot coin, on a network without SegWit. signTx bch used to return a transaction with a witness, which no Bitcoin Cash node reads.
  • signTx, signNestedWitnessTx and sigKeys refuse to sign a SegWit version 0 coin with an uncompressed key, whether the coin pays to the hash of the key or to a witness script that holds it. Nodes do not relay such a spend (SCRIPT_VERIFY_WITNESS_PUBKEYTYPE in Bitcoin Core), so the transaction they returned could not be broadcast. A block may still hold the spend. To make it on purpose, call signInput with the PrivateKey in its uncompressed form.
  • signInput and signNestedInput refuse a key that is not a key of the coin: the key of a pay-to-public-key coin, the key whose hash the coin pays to, or a key of its multisig. They used to return an input that no node accepts.
  • signTaprootInput refuses a secret key whose x-only public key is not the output key of the coin, and a spent output that is not a Taproot output. Passing the internal key in place of its tweak used to give a signature that does not verify.
  • verifyStdInput and verifyStdTx require a multisig input to hold exactly as many signatures as its script requires, and no other item. OP_CHECKMULTISIG takes that many items as signatures, and the item below them must be empty (BIP 147), so no block can contain an input with an item after its signatures or with an empty item among them. They used to answer True for both, in bare, pay-to-script-hash and pay-to-witness-script-hash form. An empty item before the signatures is refused too: nodes do not relay it, and in a witness it is invalid.
  • verifyStdTx refuses a transaction in which two inputs spend the same outpoint, as CheckTransaction does in Bitcoin Core (bad-txns-inputs-duplicate).
  • verifyStdInput and verifyStdTx refuse a SegWit or Taproot input on a network without SegWit, and compare the input script of a nested SegWit input with the push of its program byte for byte.
  • verifyStdTx looks up the coins once for the whole transaction. It used to walk the list of coins for every input, and to rebuild the list of spent outputs for every Taproot input, so its time grew with the cube of the number of Taproot inputs: 400 of them took 1.6 s and now take 0.14 s.
  • signTx derives the public keys of its secret keys once for the whole transaction, not once per input. 400 Taproot inputs with 400 keys took 11.7 s and now take 0.2 s.
  • guessTxFee returns Either String Word64. It fails when the fee does not fit in 64 bits, where it used to wrap around: 192 bytes at 2^58 satoshi per byte gave a fee of 0. It also fails for a kind of input or output that cannot exist, such as InputMulSig 16 16, whose redeem script would be 547 bytes, or a multisig of 3 of 2.
  • chooseCoins and chooseCoinsSink add amounts as unbounded integers. A target near 2^64 used to wrap around with its fee, so that a coin of 1,000 satoshi “covered” a target of 2^64 - 101. They fail for a kind of input or output that cannot exist, and they stop with an error when the transaction would weigh more than maxStandardTxWeight. They keep the sums of the selection as coins are added: selecting 1,400 coins took 0.11 s and now takes under a millisecond.
  • greedyAddSink adds amounts as unbounded integers as well. chooseCoinsSink no longer uses it.
  • mergeTxs and mergeTxInput keep the witness of the transaction. They used to remove it, so a SegWit input that was signed before the multisig signers took their copies lost its signature. mergeTxs now answers “Transactions do not match” for copies whose witnesses differ, since it does not merge witnesses. mergeTxInput returns Left for an input index that one of the transactions does not have. It used to raise an error.
  • hasWitness looks only at the stacks of the inputs. A witness item in a stack beyond the inputs used to turn the witness format on, which gave bytes with the marker and no witness item, a wrong weight and a wrong witness transaction id. Neither Bitcoin Core nor this library reads those bytes.
  • The JSON form of Tx requires one witness stack per input, or none.
  • buildAddrTx refuses an amount above the maxSatoshi of the network, as createrawtransaction refuses an amount out of range in Bitcoin Core.
  • The generators of Haskoin.Util.Arbitrary.Transaction draw compressed keys for SegWit signing data, a pay-to-script-hash multisig InputKind of at most 15 keys, SegWit and Taproot signing data only on networks that have SegWit, and amounts of which a third are below 10,000 satoshi.
  • fromMnemonic and mnemonicToSeed no longer put words of the sentence or checksum values into their error text. An unknown word is named by its position, as in fromMnemonic: words 3 and 7 are not in the list, and a failed checksum is fromMnemonic: checksum failed. A sentence typed in capitals used to be echoed whole, and the text of a Left ends up in logs.
  • fromMnemonic and mnemonicToSeed do a bounded amount of work on text from an untrusted source. The sentence is split into words before anything is normalised, and a word longer than the eight letters of the longest list word is refused as it is. mnemonicToSeed refuses a passphrase whose NFKD form would hold more than 30 combining characters in a row, the limit of the Stream-Safe Text Format of Unicode (UAX #15), which no real text passes. 32 KB of combining characters used to take half a minute, and the time grew with the square of the length. Every sentence and passphrase that was accepted before, other than such a passphrase, gives the same seed. This adds a direct dependency on unicode-data, which unicode-transforms already used.
  • The parser of MerkleBlock refuses more hashes than transactions and more flag bytes than the tree can use, before it reads them. A merkleblock message used to cost about 95 bytes of memory per flag byte, 1.5 GB for a 16 MB message. Proofs that verify are not affected.
  • An empty witness item, and any empty byte string of the wire format, costs one list cell. A tx message with four million empty witness items kept 356 MB and now keeps 100 MB, as much as Bitcoin Core.
  • bloomRelevantUpdate matches a transaction as BIP 37 and IsRelevantAndUpdate of Bitcoin Core do: by its hash, by the data of its output scripts, by the outpoints it spends and by the data of its input scripts. It only looked at outputs, so a transaction that spends a watched coin was not matched. Pay-to-pubkey and multisig outputs are told by the shape of the script, as Solver does, so a hybrid key or a key that is not on the curve counts. The Ctx argument is no longer used.
  • The version, timestamp and startHeight fields of Version are Int32, Int64 and Int32, signed as in Bitcoin Core. A peer that sent version ffffffff appeared to have version 4294967295.
  • validVersion applies its three conditions independently, as ContextualCheckBlockHeader does. It accepted old block versions on networks whose activation heights are not in the order BIP 34, BIP 66, BIP 65, which are Bitcoin Cash regtest and testnet4.
  • chooseBest keeps the first block when two have the same work, whatever their heights, as Bitcoin Core does. It preferred the higher one.
  • connectBlock and connectBlocks return the stored node of a header that is already in the store, as AcceptBlockHeader does in Bitcoin Core. A known header at or below a checkpoint used to be refused as “Rewriting pre-checkpoint chain”.
  • The memory header store returns a node only for the hash that was asked for. It returned any node whose hash shared the first eight bytes.
  • calcHash returns Maybe Hash256 and no longer calls error outside the tree. splitIn with a length below one returns the list as one chunk and no longer loops. Hashable BlockNode hashes the header only, like Eq.
  • An addrv2 entry of the Tor v2 network is read whatever its length, since BIP 155 says to ignore such entries, and no longer fails the message. fromNetworkAddressV2 gives Nothing for an IPv6 entry that holds an IPv4-mapped or an OnionCat address. toNetworkAddressV2 gives a Tor v2 entry for an OnionCat address.
  • getMessage checks the magic bytes before the command name.
  • bloomCreate picks the number of hash functions with the integer division of Bitcoin Core.
  • Read MessageCommand reads what Show writes for any bytes.
  • btcRegTest has a target timespan of one day, as Bitcoin Core regtest, and btcTest4 pins no BIP 34 block hash, as Bitcoin Core testnet4.
  • The reader of BlockNode refuses a chain work that is negative or does not fit 256 bits.
  • The generators arbitraryMerkleBlock, arbitraryBlock, arbitraryBlockNode, arbitraryVarInt, arbitraryReject, arbitrarySendCompact, arbitraryCompactBlock and arbitraryBlockTxn cover more cases, and arbitraryNetworkTx, arbitraryNetworkGetBlockTxn and arbitraryPositionsUpTo are new.
  • A TaprootSignature only holds a hash type that isTaprootSigHash accepts. Its constructor is now a pattern that only matches. Build a value with taprootSignature or decodeTaprootSig; the fields sig and hash are read as before and cannot be updated. encodeTaprootSig used to cut any hash type to one byte, so 0x100 was written as a 65-byte signature ending in 00, which BIP 341 forbids, and 0x101 as SIGHASH_ALL.
  • ScriptPathData has a new last field, opaqueScript: the bytes of the script when they are not a list of opcodes, in which case script is empty. viewTaprootWitness now reads a script path spend whatever its script bytes are. It used to return Nothing for a Tapscript with an OP_SUCCESSx opcode followed by bytes that do not decode, and for a leaf of another version, although such spends can be valid. verifyScriptPathData takes the leaf hash on the script bytes of the witness, and is False for a proof of more than 128 hashes.
  • encodeTaprootWitness returns Either String WitnessStack. It fails for an annex that is empty or does not start with 0x50, for a proof of more than 128 hashes, and for a leaf version that is odd or is 0x50. It used to write a witness that reads back as another spend, or that every node refuses.
  • taprootSigHash fails for an annex that is empty or does not start with 0x50. No node takes such an item for an annex, so no node computes that digest.
  • data/bip341.json is the file of the BIPs repository, whose key is fullySignedTx.
  • Signer has a fourth field, requirePreviousTx.
  • keySigner and xPrvSigner refuse a SegWit version 0 coin without its previous transaction. Attach the previous transaction, or set requirePreviousTx = False to trust the PSBT writer.
  • psbtTransaction refuses a PSBT with an input that is not final. Use psbtPartialTransaction for the old behaviour.
  • decodePsbt refuses what Bitcoin Core refuses: a key type that is not a compact size in its shortest form, a public key that is not on the curve, a partial signature that is not in the encoding of BIP 66 with a defined sighash byte, a previous transaction that the input does not spend, and a script tree that is not whole.
  • signPsbt and finalizePsbt leave alone an input whose redeem or witness script is not a standard template, instead of failing the whole PSBT.
  • signPsbt signs only for keys that the signed script names. It adds no signature to a script-hash coin whose script is missing, and signs a Taproot leaf only when its control block commits it to the coin.
  • signPsbt and finalizePsbt refuse an uncompressed key on a SegWit version 0 coin.
  • finalizePsbt verifies only the signatures of keys the script names, against one digest per input.
  • finalizePsbt refuses a signature that is not SIGHASH_ALL (SIGHASH_DEFAULT for Taproot) when the input names no sighash type, and leaves alone a legacy coin known from its witness output only.
  • addInput and addOutput check the map they are given.
  • A PSBT error names at most 40 bytes of a key.

Fixed

  • The documentation of the hardened markers, of the depth limit and of decodeSecKey no longer describes old behaviour of Bitcoin Core and of the secp256k1 binding. The documentation of PrivateKey and XPrvKey says that the Show instance of the SecKey inside them prints the secret.
  • The documentation of TxSignature, decodeTxSig and decodeInput lists the rules they apply: strict DER, a low S and a defined hash type, the three signature rules of the relay policy of Bitcoin Core. A signature that only consensus accepts does not decode, so an input of an old block can fail to decode. The documentation also says that a Schnorr signature of Bitcoin Cash does not decode.
  • The documentation of decodeOutput says that a multisig whose keys are not direct pushes, and a data carrier whose pushes are not the shortest, come back from encodeOutput as other bytes, and lists the scripts that the Solver of Bitcoin Core classifies and this function does not: a key in hybrid form or off the curve, and OP_RETURN OP_RESERVED.
  • The documentation of txSigHash names SerializeScriptCode of Bitcoin Core for the removal of OP_CODESEPARATOR, and says that the pushes of the signature are not removed from the script, which FindAndDelete does in Bitcoin Core. The documentation of txSigHashForkId lists what is not supported on Bitcoin Cash: SIGHASH_UTXOS, coins that hold tokens, and Schnorr signatures.
  • The documentation of Address says that a token-aware CashAddr and its plain form are different values that pay the same script, and that a value built with a constructor or read from the binary form is not checked against a network. The documentation of textToAddr says that white space around an address is refused and that some CashAddr kinds decode without being payable. The documentation of addressToOutput says that it does not know the network.
  • The documentation of maxMultisigKeys says that 20 keys fit a bare and a pay-to-witness-script-hash multisig only.
  • The documentation of verifyStdTx and verifyStdInput says what they check and what they do not: they are not a script interpreter, they never answer True for an input of the kinds they know that no block can contain, and they answer False for some inputs that a block may hold but nodes do not relay.
  • The documentation of SigInput says that the value of a legacy coin is not committed to by its signature, so that a signer cannot check it without the previous transaction.
  • The documentation of guessTxSize and txVirtualSize says that they do not count signature operations, which Bitcoin Core charges for in a transaction that is dense in them.
  • The documentation of InputKind gives the ranges of a multisig kind, and that of buildTx and buildAddrTx says what they do not check.
  • leafHash, and with it mastCommitment, taprootOutputKey, taprootScriptOutput, getMerkleProofs and verifyScriptPathData, write the script length of a Taproot leaf as a CompactSize, as BIP 341 defines the tapleaf hash and as ComputeTapleafHash does in Bitcoin Core. They wrote a base-128 varint, which is the same byte below 128 only. A leaf script of 128 bytes or more, such as a multi_a of four keys, therefore got a leaf hash, an output key and an address that no other software derives, and that leaf could not be spent. The address of every script tree with such a leaf changes. Trees whose leaf scripts are all shorter than 128 bytes, and outputs without a tree, are not affected. Coins at an address that version 1.5.1 or earlier made from such a tree can still move by the key path, or by the script path of a leaf shorter than 128 bytes. To rebuild the old output, put the old hash of each long leaf in the tree as a MASTCommitment. The old hash is the tagged hash TapLeaf of the leaf version, the script length as Data.Bytes.VarInt.VarInt of the bytes package, and the script bytes. taprootOutputKey and taprootOutputSecKey then give the old output key and the secret key of its key path, and getMerkleProofs gives the proofs of the short leaves. The long leaves of such an output can never be spent. The test “An output made by versions up to 1.5.1 with a leaf of 128 bytes or more” in TaprootSpec.hs has the code.
  • getMerkleProofs lists the hashes of a proof from the leaf up to the root for a leaf at any depth, as BIP 341 and Bitcoin Core do. From depth 3 the order was wrong, and every node refused the control block built from it. It also hashes each subtree once instead of once per level.
  • The JSON form of XOnlyPubKey reads the hex of 32 bytes only. It used to read the first 32 bytes of a longer value, so a 33-byte compressed key was taken for another key.
  • tapTreeLeaves returns Nothing for a tree with a leaf deeper than 128, and no longer wraps the depth at 256.
  • xPrvSigner no longer throws for a derivation path of more than 255 steps. The input stays unsigned.
  • signPsbt signs a P2SH-P2WPKH coin by the hash of its key, without a derivation record.
  • signPsbt and finalizePsbt use SIGHASH_ALL with the fork id flag on Bitcoin Cash when an input names no sighash type.
  • signPsbt signs a Taproot key path when the record of the internal key lists a leaf.
  • The PSBT scripts under scripts/ run again, against Bitcoin Core 32.1.

[1.5.1] - 2026-11-04

Fixed

  • nextAsertWorkRequired evaluates the aserti3-2d formula at the parent of the new block, with the parent’s timestamp and height, as GetNextASERTWorkRequired does in Bitcoin Cash Node. It used the new block’s own timestamp and height, so the bits it required were wrong for every block that did not come exactly ten minutes after its parent. The bits check that 1.5.0 added to connectBlocks turned this into a rejected block on Bitcoin Cash mainnet at height 975899.

[1.5.0] - 2026-11-03

Added

  • Taproot signing and verification, BIP 341 and BIP 342: taprootSigHash computes the digest a Taproot signature signs, for the key path and for a leaf of a script path; taprootOutputSecKey tweaks a secret key as taprootOutputKey tweaks its public key; signTx signs a SigInput of a Taproot output by its key path, with a key whose x-only public key is the output key or whose tweak without a script tree is, as a BIP 86 wallet spends, and signTaprootInput signs one input; verifyStdTx verifies key path spends, and script path spends whose leaf is a single key check. TaprootSignature, encodeTaprootSig and decodeTaprootSig are a Schnorr signature with its hash type, isTaprootSigHash tells the hash types a Taproot signature may use, and sigHashDefault is the default one. The key path vectors of BIP 341 and the BIP 86 vectors check them.

  • The Taproot fields of PSBTs, BIP 371, in Haskoin.Transaction.Psbt: tapKeySig, tapScriptSigs, tapLeafScripts, inputTapDerivations, inputTapInternalKey, inputTapMerkleRoot, outputTapInternalKey, outputTapTree and outputTapDerivations, with their inserts. They are checked against the spec when a PSBT is read. signPsbt signs a Taproot coin by its key path when the input has its internal key, and by each leaf script that is a single key check; finalizePsbt finalizes both. The test vectors of BIP 371 check them.

  • tapTreeLeaves and tapTreeFromLeaves in Haskoin.Transaction.Taproot convert a script tree to and from its leaves with their depth, the form of PSBT_OUT_TAP_TREE. encodeControlBlock and decodeControlBlock build and read a control block, which must be 33 bytes plus 32 per node with at most maxControlBlockNodes (128) nodes. leafHash, keyParity and tapscriptLeafVersion are exported.

  • txWitnessHash in Haskoin.Transaction.Common is the witness transaction id of BIP 141. txWeight and txVirtualSize give the weight and the virtual size of a transaction, and hasWitness tells whether it has a witness.

  • InputKind and OutputKind in Haskoin.Transaction.Builder name the kinds of inputs and outputs: pay-to-public-key, pay-to-public-key-hash with a compressed or an uncompressed key, pay-to-script-hash multisig, the native and nested SegWit kinds, Taproot, pay-to-script-hash of a 256-bit hash, and any other output script by its size. guessTxWeight, guessTxSize and guessTxFee estimate the weight, the virtual size and the fee of a transaction of those kinds, with inputWeight and outputSize per kind. The guess is an upper bound: it counts 72 bytes per signature, the one-byte empty witness stack of a legacy input in a transaction with a witness, and two bytes for each count of a multisig script above 16.

  • Signer in Haskoin.Transaction.Psbt is a record: keyOfRecord gives the key a derivation record names, as before, and keyOfHash the key of a public key hash, so that signPsbt signs the coins whose keys it holds when the input has no derivation record. keySigner provides both, xPrvSigner the first.

  • Tests for every function of the Haskoin.Transaction and Haskoin.Util modules, with the key path vectors of BIP 341, the vectors of BIP 86 and BIP 371, and literal sizes, ids and fee estimates.

  • connectBlock and connectBlocks now check that a header carries the difficulty bits the chain requires, as ContextualCheckBlockHeader does in Bitcoin Core. validBlock takes the required bits as a new argument. Without this check a chain of headers mined at the minimum difficulty was accepted.

  • asertAnchor finds the anchor block of the aserti3-2d algorithm for the chain that ends at a given block. mtp is now the median time past of the block itself, as in Bitcoin Core, instead of its parent’s.

  • getVarIntList and putVarIntList in Haskoin.Network.Common read and write lists with their VarInt count. A count above maxListSize (32 MiB, the MAX_SIZE of Bitcoin Core) fails the parse instead of wrapping around and reading an empty list. Blocks, Merkle blocks, getblocks, getheaders, headers, inv, getdata, notfound and addr messages use them.

  • genesisTx in Network holds the coinbase transaction of the genesis block. Haskoin.Transaction.Genesis exports mainnetGenesisTx, testnet4GenesisTx and genesisCoinbase.

  • skipHeight and medianTime are exported from Haskoin.Block.Headers.

  • Tests for every function of the Haskoin.Block modules, with vectors from Bitcoin Core and from mainnet block 100000.

  • PSBT version 2 (BIP 370) in Haskoin.Transaction.Psbt: a PSBT of version 2 is read and written as its maps, with the unsigned transaction its fields describe and the lock time they determine. The roles take both versions, and version 2 has its constructor (addInput, addOutput), its updater (setInputSequence), the flags of PSBT_GLOBAL_TX_MODIFIABLE, which the signer and the combiner keep as the spec and Bitcoin Core do, and conversion between the versions (withVersion). The test vectors of BIP 370 and files of Bitcoin Core 32.1 check it.

  • addrToBase58, addrToBech32 and addrToCash encode an address in one chosen format. addrToBase58 gives the legacy form of a Bitcoin Cash address.

  • Token-aware CashAddr addresses (types 2 and 3) can be paid. addressToOutput, addressHash160 and addressHash256 treat them like their plain P2PKH, P2SH and P2SH32 counterparts.

  • decodeSecKey in Haskoin.Crypto.Keys.Common builds a secret key from 32 bytes and refuses zero and values at or above the curve order. fromWif, fromMiniKey, xPrvImport, makeXPrvKey and the binary form of PrivateKey use it. The secKey of secp256k1-haskell 1.7.0 only checks the length, so such keys used to import and then crash derivePubKey and signMsg with an error call.

  • Derivation paths accept h and H as hardened markers, so m/84h/0h/0h parses. Bitcoin Core and BIP 380 write ' or h, and BIP 32 writes a subscript H.

  • Tests for BIP32 test vectors 4 and 5, for a BIP39 passphrase with accented letters, and for every function of the Haskoin.Crypto modules.

  • The P2P messages added since 2016: addrv2 and sendaddrv2 (BIP 155) with AddrV2, NetworkAddressV2 and conversions from and to addr entries; feefilter (BIP 133); sendcmpct, cmpctblock, getblocktxn and blocktxn (BIP 152) in Haskoin.Network.CompactBlock; getcfilters, cfilter, getcfheaders, cfheaders, getcfcheckpt and cfcheckpt (BIP 157) in Haskoin.Network.BlockFilter; wtxidrelay (BIP 339) and sendtxrcncl (BIP 330). The inventory types InvCompactBlock and InvWTx, and the service bits nodeCompactFilters, nodeNetworkLimited and nodeP2PV2.

  • maxMessageSize in Network bounds the payload getMessage reads: 4,000,000 bytes on Bitcoin, as in Bitcoin Core, and twice the block size on Bitcoin Cash.

  • scriptPushData lists the data elements a script pushes, as GetOp does in Bitcoin Core.

  • getVarIntBytes and putVarIntBytes read and write bytes with their count, under the same limit as lists.

  • Tests with fixed wire bytes for every message type, the sample version, verack and addr messages of the protocol documentation, and every function of the Haskoin.Network modules.

  • pushOpData gives the data that a push opcode puts on the stack, and isMinimalPush tells whether a push is in its shortest encoding, the rule of CheckMinimalPush in Bitcoin Core.

  • OP_CHECKSIGADD is a pattern synonym for opcode 0xba, which OP_CHECKDATASIG also names, so a Tapscript can be written with the name of BIP 342.

  • NestedWitnessInput is the input script of a P2SH-P2WPKH or P2SH-P2WSH output: a push of the witness output script. decodeInput, encodeInput, inputAddress and the signer use it, and isNestedWitnessInput tests for it. Such an input used to fail to decode.

  • maxMultisigKeys is 20, the MAX_PUBKEYS_PER_MULTISIG of Bitcoin Core. decodeOutput reads a multisig output with 17 to 20 keys, whose counts are one-byte pushes, and encodeOutput writes one. Only 16 keys used to be supported.

  • decodePubKey in Haskoin.Crypto.Keys.Common reads a public key from bytes that must hold the key and nothing else.

  • Tests for every function of the Haskoin.Script modules, with literal vectors from BIP 67, BIP 143, BIP 173 and BIP 341.

Changed

  • makeSignature, and with it signTx, signInput and signPsbt, refuse to sign a legacy input with SIGHASH_SINGLE when the input has no output at its index. The digest of that case is the constant 1, which commits to nothing, so the signature would spend any other coin of the key wherever the same case comes up. txSigHash still computes that digest, as a node must to verify such signatures, and verifyStdInput still accepts them. A SegWit input is signed in that case, since the BIP 143 digest commits to the coin.
  • Signer has a new field, acceptedSigHashes: the sighash types it signs with. keySigner and xPrvSigner set it to defaultSigHashes, which are SIGHASH_DEFAULT and SIGHASH_ALL. signPsbt refuses an input that asks for another type, as BIP 174 asks of a signer: the other types leave part of the transaction unsigned, and the PSBT comes from someone else. A PSBT asking for SIGHASH_NONE or SIGHASH_SINGLE used to be signed as asked. The fork id flag is not compared, since the network decides it.
  • PrivateKey and XPrvKey show their secret as <redacted>, and no longer have a Read instance; nor does XKey. The derived instances printed the key, and for XPrvKey the chain code, so a value in a log or an error message gave the coins away. toWif and xPrvExport write a key out.
  • prvSubKey, pubSubKey, hardSubKey and cycleIndex throw DerivationException for a child index with the hard bit set, like every other failure of a derivation. They used to call error.
  • A transaction with no inputs whose next byte, the flags of BIP 144, is neither 0x00 nor 0x01 fails to parse with “Unknown transaction optional data”, as in Bitcoin Core. Such bytes used to parse as a legacy transaction with no inputs that did not serialize back to the same bytes. A Tx string literal must hold the transaction and nothing else, as DecodeHexTx requires in Bitcoin Core.
  • The documentation of decodeBase58 and decodeBase58Check says that their cost grows with the square of the length and that callers must bound untrusted input. The decoders of the library bound it already.
  • taprootOutputKey and taprootScriptOutput tweak the x-only internal key, as BIP 341 defines the output key. An internal key with an odd y coordinate used to be tweaked as a full point, which gave an output key and an address no other wallet derives from that key, and that a BIP 341 signer could not spend.
  • viewTaprootWitness reads a witness in the order of BIP 341: the annex last, then the control block, then the script, then the stack. It used to read the control block and the script in the other order, and so decoded no real script path witness. encodeTaprootWitness writes the annex only when there is one; it used to append an empty item, which made the witness invalid. The control block of a ScriptPathData is a list of digests, and a control block of a wrong length is refused. KeyPathSpend carries the annex of a key path spend.
  • signPsbt applies the checks of the BIP 174 signer. A coin known from PSBT_IN_WITNESS_UTXO alone is signed only with a witness signature, since the legacy digest does not commit to the amount; the previous transaction is used first, and a witness output that is not its output is refused. A sighash type no node accepts, or whose fork id flag does not fit the network, is refused instead of signed. A redeem script that does not hash to the coin, or a witness script that does not hash to the witness program, is refused. An input whose coin script is not standard is left alone instead of failing the PSBT.
  • finalizePsbt takes the Network and verifies every signature it uses, against the digest of the coin and the sighash type of the input when it has one, as PSBTInputSignedAndVerified does in Bitcoin Core. A signature that does not verify, is not a signature, or uses another sighash type is refused. It used to finalize any bytes stored as a signature.
  • mergeTxs leaves an input that no transaction signed as it is. It used to crash with Prelude.head: empty list.
  • chooseCoins takes the kinds of the outputs and a fee rate per virtual byte, and estimates the fee from the coinInputKind of each coin, a new method of Coin. chooseMSCoins, chooseMSCoinsSink, guessMSTxFee and guessMSSize are gone, since the kind of input lives on the coin. The old estimate counted every input as pay-to-public-key-hash and charged bytes rather than virtual bytes, so a SegWit wallet overpaid fees by about 60 %.
  • hexToTxHash, and the Read, string and JSON forms of TxHash and OutPoint, refuse hex that is not exactly 32 bytes. Longer hex used to be accepted with its leading bytes dropped.
  • Transaction parsing bounds the counts of inputs, outputs, witness stacks and witness items by maxListSize, as ReadCompactSize does in Bitcoin Core; a count of 2^64 - 1 used to wrap around and read as zero. A transaction with the witness marker but no witness item is refused (“Superfluous witness record”), as Bitcoin Core refuses it. A transaction whose witness stacks are all empty is serialized without the marker, and hasWitness is false for it.
  • verifyStdTx and verifyStdInput take the coins of every input, matched by outpoint, so that Taproot inputs can be verified. A witness on an input whose coin is not a witness program is refused, as VerifyScript refuses it in Bitcoin Core, and verifyStdTx refuses outputs that spend more than the coins hold.
  • nosigTxHash removes the witness as well as the input scripts, so that it is the same before and after signing a SegWit input.
  • getBits raises an error for input shorter than the bits asked, getList and getLengthBytes refuse a count that does not fit an Int, and unmarshalLazy returns Either String a instead of throwing.
  • setInputSequence refuses to change the sequence of an input that is signed, since every signature commits to it.
  • WitnessProgram, WitnessProgramPKH, MAST, TaprootWitness and ScriptPathData have Show and Eq instances.
  • The package requires secp256k1-haskell 2.0.0, whose normalizeSig is total. verifyHashSig normalises the signature with it, and isCanonicalHalfOrder is its isLowS.
  • buildMerkleRoot returns Either String MerkleRoot. It fails for an empty list, which used to crash, and for a mutated tree in which two sibling nodes are identical (CVE-2012-2459). extractMatches rejects such a tree too, as CPartialMerkleTree::TraverseAndExtract does in Bitcoin Core, and reports why a partial tree is malformed.
  • buildMerkleRoot, buildPartialMerkle and calcHash build the tree in linear time instead of quadratic. decodeMerkleFlags is linear too; it took a minute for 100 KB of flags, which a peer could send in a merkleblock message.
  • genesisBlock no longer takes a Ctx and returns the right coinbase for every network. Bitcoin testnet4 has its own genesis coinbase, so genesisBlock btcTest4 used to return a block whose transactions did not match its header.
  • The merkleroot field of the JSON form of BlockHeader is in display order, like prevblock and the getblockheader RPC call of Bitcoin Core. It was in internal byte order.
  • hexToBlockHash and the JSON parser of BlockHeader reject a hash that is not exactly 32 bytes. They used to accept longer input and drop the leading bytes.
  • computeAsertBits takes the proof-of-work limit of the network as its first argument instead of using the mainnet limit.
  • connectBlocks adds each header to the store as it passes, so a batch with a bad header keeps the headers before it and makes the last of them the best block when it has the most work.
  • Ord BlockNode compares the height and then the header, so that it agrees with Eq, which compares the header.
  • appendBlocks dates every block one target spacing after its parent, so the chains it mines pass the median time past rule.
  • blockLocatorNodes steps back like LocatorEntries in Bitcoin Core and lists the genesis block once.
  • encodeCompact raises an error for a number wider than 255 bytes instead of wrapping the exponent.
  • traverseAndBuild and traverseAndExtract are no longer exported.
  • getMessage consumes exactly one message. It used to leave the payload in the stream and let the payload parser read past the declared length, so bytes outside the checksum could end up in a message. It now checks the magic before reading the payload, refuses a payload above maxMessageSize, and accepts a payload on message types that carry none, as Bitcoin Core does.
  • VarInt refuses an encoding longer than the value needs, as ReadCompactSize does in Bitcoin Core. A transaction with such an encoding used to parse and re-serialize to different bytes. VarString refuses a count above maxListSize.
  • MessageCommand refuses a name with a byte outside printable ASCII or with a byte other than NUL after it, as Bitcoin Core does, and serializing a name longer than twelve bytes is an error instead of a silent truncation.
  • The extra field of Reject is a Maybe Hash256. It was a ByteString that only round-tripped when empty or 32 bytes long.
  • Version refuses a user agent longer than 256 bytes, as Bitcoin Core does.
  • BloomFilter refuses a filter above 36000 bytes or 50 hash functions when parsing, as Bitcoin Core refuses such a filterload, and reads its bytes in one go instead of one at a time. FilterAdd refuses an element above 520 bytes. BloomFlags reads only the two low bits of its byte, as Bitcoin Core does.
  • bloomRelevantUpdate matches the data pushed by every output script, standard or not, and inserts outpoints according to the flags, as IsRelevantAndUpdate does in Bitcoin Core. It used to raise an error for any transaction with a non-standard output, and for a matching output that was not pay-to-pubkey or pay-to-multisig under BloomUpdateP2PubKeyOnly. It returns Just the filter whenever an output matches, unchanged under BloomUpdateNone.
  • bloomInsert and bloomContains treat a filter with zero hash functions as matching everything, as Bitcoin Core does. bloomInsert used to loop over 2^32 hash functions and bloomContains used to answer False. bloomCreate gives zero hash functions for zero elements.
  • bip34Block in Network is split into bip34Height and bip34Hash, the hash being optional. btcRegTest activates BIP34, BIP65 and BIP66 at height 1, as Bitcoin Core regtest does; it had the heights of Bitcoin Cash Node regtest. bchRegTest has the 32 MB block size of Bitcoin Cash Node.
  • arbitraryBloomFilter generates a BloomFilter with random bits instead of a tuple.
  • Replace the PSBT module with Haskoin.Transaction.Psbt, which keeps every field of a PSBT, known or not, writes maps with their keys in order as Bitcoin Core does, refuses what breaks BIP 174 (duplicate keys, keys out of shape, bytes after the last map, other versions), and reads and writes the global xpub and proprietary fields. It still creates, combines, signs, finalizes and extracts. The Haskoin.Transaction.Partial module and its types are gone.
  • pubKeyWitnessAddr and pubKeyCompatWitnessAddr now return Maybe Address and refuse uncompressed keys. 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.
  • The WitnessAddress and CashAddress constructors are now patterns that can only match. Build these addresses with witnessAddress and cashAddress, which validate the version and payload and return the dedicated constructor when one exists. Every address now has a single representation, so equal addresses compare equal.
  • outputAddress and scriptToAddress no longer report the P2PKH address of the key for a pay-to-public-key output. Such coins cannot be spent with the P2PKH input script, so the address was misleading.
  • convertBits in Haskoin.Util.Helpers returns Maybe [Word] and fails on padding bits that are not zero, or that are wide enough to hold a whole input digit, when padding is not allowed.
  • JSON encoding of an address that has no text form on the given network now fails with an error instead of writing null.
  • mnemonicToSeed NFKD-normalises the sentence and the passphrase, as BIP39 requires and as Trezor, Electrum, python-mnemonic and bitcoinjs do. A passphrase with accented letters used to give a seed that no other wallet derives, so the funds could not be restored elsewhere. fromMnemonic normalises the sentence before looking up its words. This adds a dependency on unicode-transforms.
  • toMnemonic accepts 16 to 32 bytes of entropy and fromMnemonic accepts sentences of 12, 15, 18, 21 or 24 words, the sizes BIP39 allows. Entropy of 4 to 12 bytes and of 36 to 64 bytes, and sentences of 3 to 9 and 27 to 48 words, were accepted before, and no other wallet reads them. A word that is not in the list is reported with the fromMnemonic: prefix.
  • xPrvImport and xPubImport require a payload of exactly 78 bytes, as Bitcoin Core does. Trailing bytes and an uncompressed public key used to be accepted. They also refuse a key at depth 0 whose parent fingerprint or index is not zero, as BIP32 test vector 5 requires.
  • fromWif refuses strings longer than 52 characters, and xPrvImport and xPubImport strings longer than 112, before decoding them. No valid key is longer, and the time to decode Base58 grows with the square of the length.
  • prvSubKey, pubSubKey and hardSubKey throw DerivationException when the parent is at depth 255. The depth of the child used to wrap around to 0.
  • Parsing a derivation path reads each index as an unbounded integer and accepts decimal digits only. m/4294967296 used to wrap around to m/0, and hex, parenthesised and signed numbers were accepted.
  • The JSON form of Sig is decoded with decodeStrictSig, like the binary form, so a high-S signature is refused by both.
  • The Read instances of Hash160, Hash256 and Hash512, and textToFingerprint, refuse hex of the wrong length, as the string literal instances already did. A two-byte hash could be read and then crash signHash.
  • encodeOutput returns Either String Script. It fails for a PayMulSig whose required count is not between 1 and its number of keys or that has more than 20 keys, and for a PayWitness whose version is 0 or above 16 or whose program is not 2 to 40 bytes long. Those values used to crash with an error call. marshalPut still fails with an error call for them, since it cannot report a failure.
  • txSigHash and txSigHashForkId return Either String Hash256. They fail for an input index the transaction does not have. With SIGHASH_ALL, txSigHash used to return a digest over the transaction without any script code for such an index, and crash for the other hash types. makeSignature and makeSigHash return Either too.
  • On a network with a fork id, txSigHash requires the SIGHASH_FORKID flag and decodeTxSig rejects a signature without it. makeSignature sets the flag, so signTx bch with a plain sigHashAll produces a signature the network accepts. It used to sign the legacy digest, which Bitcoin Cash has rejected since 2017.
  • isSigHashUnknown is the test of IsDefinedHashtypeSignature in Bitcoin Core: after masking the SIGHASH_ANYONECANPAY and SIGHASH_FORKID bits, the hash type byte must be 1, 2 or 3. A byte such as 0x21 used to pass and be signed, although every node rejects it under STRICTENC.
  • opPushData gives the minimal encoding of BIP 62: OP_0 for the empty string, OP_1 to OP_16 for one byte from 1 to 16 and OP_1NEGATE for the byte 0x81. The empty push used to be an OP_PUSHDATA that serialized to the byte of OP_0 but was not equal to it.
  • DataCarrier holds the data of every push after OP_RETURN, as a list, since TxoutType::NULL_DATA of Bitcoin Core is OP_RETURN followed by any pushes. A bare OP_RETURN, several pushes and an empty push used to be “Non-standard output”.
  • intToScriptOp returns Either String ScriptOp instead of crashing outside 1 to 16. scriptOpToInt no longer serializes its argument, so it cannot crash on an OP_PUSHDATA whose payload does not fit its type.
  • sortMulSig returns any output that is not a multisig unchanged instead of crashing.
  • decodeInput reads the input of a pay-to-script-hash output as its redeem script requires. A multisig template with the redeem script and no signature yet, OP_0 <redeem>, is a SpendMulSig [], which mergeTxs used to reject. An input that does not fit its redeem script fails.
  • The generators of Haskoin.Util.Arbitrary.Script produce pushes of every PushDataType, pushes that are not minimal, multisig outputs of up to 20 keys, data carriers with any number of pushes, nested witness inputs, and, on networks with a fork id, only hash types with the flag.

Fixed

  • A block whose timestamp equals the median time past of its parent is rejected, as in Bitcoin Core. It used to be accepted.
  • connectBlocks keeps the block that was seen first as the best block when a competing block has the same work and height, as connectBlock and Bitcoin Core do. It used to switch the best block to every competitor.
  • calcNextWork and computeTarget measure the time span of a retarget period as a signed number. A period whose last block is dated before its first block used to wrap around to four times the target timespan instead of being limited to a quarter.
  • headerWork returns zero for bits that are negative, overflow or encode a zero target, like GetBlockProof in Bitcoin Core. It used to divide by zero for bits 0x03800001.
  • The block version is compared as a signed number, as in Bitcoin Core, so versions with the top bit set are rejected once BIP34 is active.
  • The Bitcoin Cash difficulty algorithms follow Bitcoin Cash Node: the minimum-difficulty rule of test networks applies to the ASERT algorithm and no longer applies to the EDA and DAA algorithms on mainnet, the EDA returns the bits of the last block without minimum difficulty on test networks, getSuitableBlock picks the same block as Bitcoin Cash Node when timestamps are equal, computeTarget no longer overshoots by one, the ASERT anchor is the first block whose own median time past reaches the activation time, and regtest never retargets.
  • A PSBT of another version is refused by its version. The unsigned transaction was looked for first, and a PSBT of version 2 holds none.
  • addressBytes returned a length-prefixed value for a generic CashAddr instead of the raw hash.
  • Base58, Bech32 and CashAddr decoders accepted non-ASCII look-alike characters. Base58 truncated code points to one byte and Bech32 used Unicode case folding. All three now accept ASCII only, as the specifications require.
  • cashAddrDecode accepted mixed-case strings, which the CashAddr specification rejects.
  • CashAddr decoding accepted non-canonical strings whose padding bits were not zero, or that carried an extra group of padding, so several strings could stand for the same address.
  • textToAddr decoded Base58 input of any length, with a cost growing with the square of the length. Strings longer than any valid address are now rejected first.
  • Binary deserialization of an address now validates the witness version, the CashAddr type and the payload length, and checks the length prefix before converting it to an Int. Previously an invalid value could be read and later crash addressToScript.
  • The Bech32 and bit conversion accumulators are masked so that they cannot overflow on long inputs.
  • encodeOutput had no case for PayScript32Hash and crashed on it, so a P2SH32 address could not be turned into a script.
  • The P2WSH test generator produced P2WPKH addresses.
  • fromWif threw an exception on a Base58Check string with an empty payload, such as 3QJmnh, also through the JSON parser of PrivateKey. It returns Nothing now.
  • The JSON parser of PublicKey accepted bytes after the key.
  • decodeOutput matches the output templates on their exact bytes, as Bitcoin Core does. A script that wrote the hash of a P2PKH, P2SH, P2SH32 or witness output with OP_PUSHDATA1 or a longer push used to decode as that output and give its address. By consensus such a script is not a P2SH or witness output at all, and anyone can spend it, so a wallet could credit a payment to its address that was not one.
  • A public key pushed in a script or a witness must fill its push. A 65-byte item that starts with 0x02 or 0x03 used to parse as the 33-byte key it starts with, so decodeOutput, decodeInput and the witness decoders reported a key the script did not hold, and verifyStdTx accepted a P2PKH or P2WPKH spend whose key item carried 32 extra bytes, which no node accepts.
  • verifyStdInput returns False for an input index the transaction does not have, and parseExistingSigs reads no witness signatures when the witness list is shorter than the input index. Both used to crash.

[1.4.0] - 2026-10-31

Added

  • Bitcoin testnet4 network (btctest4) with the BIP94 block storm and time warp rules.

Changed

  • Update DNS seeds to match Bitcoin Core and Bitcoin Cash Node. Drop the Bitcoin ABC seeds, which now serve eCash.
  • This package now requires base16 2.0 and secp256k1-haskell 0.7.

Fixed

  • Compute the difficulty retarget in nextPowWorkRequired and nextEdaWorkRequired, which never reached their retarget branches.
  • Fix the Bitcoin Cash DAA activation height, which had a typo (404031 instead of 504032).
  • Start the DAA one block later on Bitcoin Cash testnet and testnet4, to match Bitcoin Cash Node.
  • Fix the Bitcoin Cash ASERT half-life, which must be two days.

[1.3.0] - 2026-08-12

Changed

  • Make script and address parsing more strict.
  • Use smart constructors for addresses to avoid inconsistent or incorrect represtentations.

Fixed

  • Support Bitcoin Cash 256-bit pay-to-script-hash scripts and addresses.
  • Make addresses of incorrect length invalid.
  • Avoid decoding scripts as standard when hash or public key length incorrect.
  • Fix secp256 library function names.

[1.2.2] - 2025-05-08

Changed

  • Standardize author name and correct README link.

[1.2.1] - 2025-05-08

Changed

  • New home in github.com/jprupp rather than github.com/haskoin.

[1.2.0] - 2023-07-23

Changed

  • Move from cryptonite to crypton for now.

[1.1.0] - 2023-03-14

Changed

  • Update upstream dependencies & LTS Haskell.

[1.0.4] - 2023-10-09

Changed

  • Export the BIP39 word list
  • Add new BIP39 test vectors

[1.0.3] - 2023-09-02

Changed

  • New dependency on data-default
  • Renamed some arbitrary (test) functions for clarity
  • Reworked the identity testing tool to include Marshal and MarshalJSON classes

[1.0.2] - 2023-08-04

Fixed

  • Text files needed for testing now in tarball.

[1.0.1] - 2023-08-03

Changed

  • Do not use alternative monad for Either String values.

[1.0.0] - 2023-07-28

Changed

  • Shorten all field names allow duplicates, using DuplicateRecordFields extension.
  • Use OverloadedRecordDot language extension and syntax.
  • Use explicit context object from secp256k1-haskell library.
  • Unify serialization into custom Marhsal and MarshalJSON classes.
  • Use ormolu for formatting.
  • Simplify module organisation.
  • Strongly break backwards compatibility.

[0.22.0] - 2023-06-28

Changed

  • Upgrade to lastest secp256k1 and base16 packages.

[0.21.2] - 2022-04-13

Changed

  • Serialisation test now works for both strict and lazy bytestrings.

[0.21.1] - 2021-12-13

Changed

  • Make Base58 faster.

[0.21.0] - 2022-11-23

Added

  • BCH Testnet4 support.

Changed

  • Fix inconsistent serialization/deserialization issues.

Fixed

  • Makes finalScriptWitness field encoding conform to bitcoin core.
  • Fixes bug in finalizeTransaction

Added

  • Signing support for PSBTs
  • Helper function for merging PSBTs
  • More PSBT tests
  • Partial support for taproot

[0.20.5] - 2021-09-13

Added

  • Support Bech32m address format for Taproot.

[0.20.4] - 2021-06-08

Fixed

  • Add missing case for witness version.

[0.20.3] - 2021-05-17

Fixed

  • Allow unknown inv types.

[0.20.2] - 2021-05-17

Fixed

  • Allow unknown messages of zero length.

[0.20.1] - 2021-05-14

Fixed

  • Correct case where binary search returned the wrong element.

[0.20.0] - 2021-02-22

Chaged

  • Use bytes instead of binary or cereal.

[0.19.0] - 2021-01-25

Added

  • Hashable instances for extended keys.

Changed

  • Mnemonic passphrases now Text instead of ByteString.

Fixed

  • Tests now pass for witness addresses.

[0.18.0] - 2020-12-10

Added

  • Support SegWit addresses with version other than 0.

[0.17.6] - 2020-12-07

Added

  • Serialize instances for XPubKey and XPrvKey.

[0.17.5] - 2020-12-03

Fixed

  • Handle special case in block header binary search function.

[0.17.4] - 2020-12-03

Fixed

  • Bounds check too restrictive in block header binary search function.

[0.17.3] - 2020-11-17

Changed

  • Reduce minimum version of text package dependency.

[0.17.2] - 2020-11-17

Changed

  • Update lists of seeds for all networks.

[0.17.1] - 2020-11-02

Changed

  • Use the C-preprocessor to handle versions of base16-bytestring

[0.17.0] - 2020-10-21

Added

  • Support for Bitcoin Cash November 2020 hard fork.
  • Functions to find block headers matching arbitrary sorted attributes.

Removed

  • GenesisNode constructor for BlockNode type.

[0.15.0] - 2020-07-23

Added

  • Add more test vectors

Changed

  • stringToAddr renamed to textToAddr
  • Move ScriptOutput to Standard.hs
  • Move WIF encoding/decoding to Keys.hs
  • (breaking) rename OP_NOP2 and OP_NOP3 to OP_CHECKLOCKTIMEVERIFY and OP_CHECKSEQUENCEVERIFY resp.
  • Update to latest secp256k1 bindings.

[0.14.1] - 2020-06-14

Fixed

  • Correct some Bitcoin Cash Testnet3 seeds.
  • Add helpers for writing Data.Serialize and Data.Aeson identity tests

[0.14.0] - 2020-06-14

Changed

  • Expose all modules for tests.
  • Tests depend on library instead of having access to its source code.
  • Use MIT license.
  • Update seeds.
  • Bump secp256k1-haskell dependency.

[0.13.6] - 2020-06-05

Changed

  • Expose the Arbitrary test instances under Haskoin.Util.Arbitrary

[0.13.5] - 2020-05-16

Changed

  • Provide meaningful JSON instances for most types.

[0.13.4] - 2020-05-14

Added

  • Support for Bitcoin Cash May 2020 hard fork.

[0.13.3] - 2020-05-08

Changed

  • Improve code and documentation organisation.

[0.13.2] - 2020-05-08

Changed

  • Move all packages from Network.Haskoin namespace to Haskoin namespace.
  • Expose all top-level modules directly.

[0.13.1] - 2020-05-06

Changed

  • Faster JSON serialization.

[0.13.0] - 2020-05-06

Changed

  • Consolidate all modules in Haskoin module.

Removed

  • Deprecate Network.Haskoin namespace.
  • Hide QuickCheck generators in test suite.

[0.12.0] - 2020-04-10

Added

  • Support for signing segwit transactions.
  • High-level representation of segwit v0 data and auxilliary functions.

Changed

  • Adds handling of segwit signing parameters to transaction signing code.

[0.10.1] - 2020-02-08

Added

  • Lower bound versions for some dependencies.

[0.10.0] - 2020-01-15

Added

  • DeepSeq instances for all data types.

Changed

  • There is no SockAddr inside NetworkAddress anymore.

[0.9.8] - 2020-01-01

Added

  • Ord instance for DerivPathI

[0.9.7] - 2019-12-04

Added

  • JSON encoding/decoding for blocks.

Fixed

  • Fix lowercase HRP test for Bech32.

[0.9.6] - 2019-10-29

Added

  • bloomRelevantUpdate implementation for Bloom filters (thanks to @IlyasRidhuan).

Fixed

  • Fix for Bech32 encoding (thanks to @pavel-main).

[0.9.5] - 2019-10-23

Added

  • Expose functions added in 0.9.4.

[0.9.4] - 2019-10-23

Added

  • Support for (P2SH-)P2WPKH addresses derived from extended keys.

Changed

  • Change names of backwards-compatible P2SH-P2WPKH functions from 0.9.3.

[0.9.3] - 2019-10-22

Added

  • Some support for P2WPKH-over-P2SH addresses.

[0.9.2] - 2019-10-09

Removed

  • Disable unnecessary -O2 optimisation added in previous version.

Added

  • Allow decoding unknown P2P messages.

[0.9.1] - 2019-10-02

Added

  • Add a function to produce a structured signature over a transaction.
  • Enable -O2 optimisations.

[0.9.0] - 2019-04-12

Changed

  • Address conversion to string now defined for all inputs.

[0.8.4] - 2018-12-05

Added

  • Add reward computation to block functions.
  • Add PSBT BIP-174 types and functions.

[0.8.3] - 2018-12-04

Added

  • Add reward halving interval parameter to network constants.

[0.8.2] - 2018-11-06

Added

  • Recognize OP_CHECKDATASIG and OP_CHECKDATASIGVERIFY opcodes.

[0.8.1] - 2018-10-13

Added

  • Add instances of Hashable and Generic where possible.

[0.8.0] - 2018-10-13

Removed

  • Remove deepseq dependency.
  • Remove network constant reference from address and extended keys.

[0.7.0] - 2018-10-13

Added

  • Add Serialize instance for network constants.
  • Add Serialize instance for addresses that includes network constants.

Changed

  • Move functions related to addresses from Script to Address module.

[0.6.1] - 2018-10-09

Added

  • Compatibility with latest GHC and base.

Changed

  • Update minimum base to 4.9.

[0.6.0] - 2018-10-08

Changed

  • Force initialization of addresses through smart constructor.
  • Assume addresses are always valid when instantiated in code.
  • Allow to provide unwrapped private keys to transaction signing functions.

[0.5.2] - 2018-09-10

Changed

  • Make dependencies more specific.

[0.5.1] - 2018-09-10

Changed

  • Remove some unneeded dependencies from stack.yaml.
  • Change secp256k1 dependency to secp256k1-haskell.

[0.5.0] - 2018-09-09

Added

  • Support for Bitcoin Cash network block sychronization.
  • Support for Bitcoin Cash signatures.
  • Initial work on SegWit support.
  • New version of secp256k1 bindings.
  • Block header validation.
  • Support for RegTest networks on Bitcoin and Bitcoin Cash.
  • Support for Bitcoin Cash Testnet3 Network.
  • Support for new Haskoin Wallet.
  • Minikey decoding for Casascius coins.
  • New tests for various networks and new features.
  • Added CHANGELOG.md file.
  • Support for SegWit addresses.
  • Support for CashAddr addresses.

Changed

  • Use of hpack package.yaml file to auto-generate Cabal file.
  • Removal of dependency version limits, relying on stack.yaml instead.
  • Tests moved to hspec.
  • New documentation.
  • Updated .gitignore.
  • Renamed network constants to use same style for BTC and BCH.
  • Network constants must be passed explicitly.
  • Target LTS Haskell 12.9.

Removed

  • Removed .stylish-haskell.yaml files.
  • Removed old haskoin-node and haskoin-wallet packages from main repository.
  • Removed support for non-strict signatures and related tests.
  • Removed script evaluator and related tests.