diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,13 +5,949 @@
 The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
 and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
 
+## [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](https://github.com/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](https://github.com/jprupp/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, some hundreds of reads. A node
+  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
@@ -441,7 +1377,7 @@
 
 - `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, and blocks hold signatures with a high S. `isCanonicalHalfOrder` tests the relay rule. The form of a transaction signature, `TxSignature`, still applies it. The signers make low-S signatures, as before.
+- `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.
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -33,17 +33,18 @@
 
 | Area         | What you get                                                                                                         |
 | ------------ | -------------------------------------------------------------------------------------------------------------------- |
-| Networks     | Bitcoin and Bitcoin Cash: mainnet, testnet3, testnet4 and regtest                                                    |
+| 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 token-aware CashAddr types                                           |
-| Scripts      | Script parsing and serialization, standard input and output templates, BIP-67 sorted multisig                        |
+| 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
@@ -58,8 +59,8 @@
 - **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, `verifyStdTx` does not read them, and an
-  output with tokens has no address.
+  Nothing here signs them, and `verifyStdTx` does not read them. The tokens
+  of an output and its address are read: see [Bitcoin Cash](#bitcoin-cash).
 - **BIP-324 encrypted transport.**
 - **BIP-39 word lists other than English.**
 
@@ -115,7 +116,7 @@
 ```yaml
 resolver: nightly-2026-10-28
 extra-deps:
-  - haskoin-core-2.0.0
+  - haskoin-core-3.0.0
   - base16-2.0
   - secp256k1-haskell-3.0.0
 ```
@@ -180,10 +181,27 @@
 | `btcTest4`   | Bitcoin testnet4      | `btctest4`           |
 | `btcRegTest` | Bitcoin regtest       | `btcreg`             |
 | `bch`        | Bitcoin Cash mainnet  | `bch`                |
-| `bchTest`    | Bitcoin Cash testnet3 | `bchtest`            |
+| `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.
@@ -437,6 +455,49 @@
 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:
+
+```haskell
+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.
 
@@ -500,6 +561,70 @@
 For multisig, each signer can call `signTx` with their own keys. `mergeTxs`
 combines the results for legacy inputs. For SegWit multisig, use a [PSBT](#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.
+
+```haskell
+-- 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:
+
+```haskell
+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
@@ -593,12 +718,31 @@
 - `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 refuse such a coin. Set `requirePreviousTx = False` on the `Signer`
-  to accept it.
+  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.
@@ -614,9 +758,10 @@
 ```haskell
 let key = derivePath ("m/86'/0'/0'/0/0" :: DerivPath) master
     internalKey = (deriveXPubKey key).key
-    -- Nothing means that the output has no script tree.
-    output = taprootScriptOutput (TaprootOutput internalKey Nothing)
 
+-- 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"
 
@@ -640,8 +785,30 @@
 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`:
+
+```haskell
+-- 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
 
@@ -706,6 +873,90 @@
 `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.
+
+```haskell
+-- 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
 
 ```haskell
@@ -726,8 +977,13 @@
 
 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, and finding it takes some hundreds of reads
-from the store. `connectBlocks` finds it once for the whole run.
+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,
@@ -782,6 +1038,78 @@
 `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.
+
+```haskell
+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`](doc/protocol/README.md) 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
@@ -795,8 +1123,10 @@
 | `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.Script`              | Scripts, standard templates and signature hashes                     |
+| `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)        |
@@ -823,12 +1153,22 @@
 - **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
-  by the rules that nodes relay by, and that outputs do not exceed inputs. It is
-  not a script interpreter and does not apply every consensus rule.
+- **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
 
@@ -845,6 +1185,46 @@
 `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](https://github.com/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`.
+
+```sh
+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:
+
+```sh
+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](#benchmarks).
+
 `package.yaml` is the source of the package description. Change it rather than
 `haskoin-core.cabal`, which [hpack](https://github.com/sol/hpack) generates. Stack
 regenerates the file whenever it builds.
@@ -852,6 +1232,27 @@
 The tests are in `test/` and use [hspec](https://hspec.github.io/). The test
 vectors from the BIPs, Bitcoin Core and other implementations are in `data/`.
 
+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](https://podman.io/) on Linux: each group of
+these tests starts a node of its own in a container, through
+[podman-test](https://github.com/jprupp/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:
+
+```sh
+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
@@ -920,9 +1321,9 @@
 
 Pull requests are welcome.
 
-- Format the code with [Ormolu](https://github.com/tweag/ormolu). The script
-  [scripts/format](https://github.com/jprupp/haskoin-core/blob/master/scripts/format)
-  does this for all the sources.
+- Format the code with [Ormolu](https://github.com/tweag/ormolu).
+  `haskell-format`, from [jprupp/tools](https://github.com/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](https://keepachangelog.com/en/1.0.0/), and versions follow
diff --git a/bench/Bench.hs b/bench/Bench.hs
--- a/bench/Bench.hs
+++ b/bench/Bench.hs
@@ -46,7 +46,7 @@
 
 import Control.DeepSeq (NFData)
 import Control.Monad (unless, (<=<))
-import Control.Monad.State.Strict (runState)
+import Control.Monad.State.Strict (State, runState)
 import Data.Aeson (ToJSON (toEncoding))
 import Data.Aeson.Encoding (Encoding, encodingToLazyByteString, unsafeToEncoding)
 import Data.Base16.Types (extractBase16)
@@ -490,15 +490,32 @@
 -- target of a test network, so that the chain can be built in a moment, and
 -- kept in the memory store of the library, so that the figure is the cost of
 -- the validation and not of a database.
+--
+-- The network is regtest, which has no 'asertAnchorBlock', so 'connectBlocks'
+-- searches for the anchor once. 'connectBlock' of a single header is timed
+-- twice: on that network, where it searches, and with the anchor set as on
+-- mainnet, where it walks to it.
+--
+-- Each case is run once before it is timed, and the suite stops if its headers
+-- do not connect: a failure that came early would otherwise look fast.
 headerBenchmarks :: [Benchmark]
 headerBenchmarks =
-  [ env (return (chain, batch)) $ \ ~(mem, hs) ->
+  [ env (checked (connectBlocks net now batch) (length batch)) $ \ ~(mem, hs) ->
       bench "connectBlocks 2000 at 100000" $
-        nf (\hs' -> fst (runState (connectBlocks net now hs') mem)) hs
+        nf (\hs' -> fst (runState (connectBlocks net now hs') mem)) hs,
+    env (checked (fmap pure <$> connectBlock net now next) 1) $ \ ~(mem, _) ->
+      bench "connectBlock 1 at 100000, anchor searched" $
+        nf (\h -> fst (runState (connectBlock net now h) mem)) next,
+    env (checked (fmap pure <$> connectBlock anchorNet now next) 1) $ \ ~(mem, _) ->
+      bench "connectBlock 1 at 100000, anchor known" $
+        nf (\h -> fst (runState (connectBlock anchorNet now h) mem)) next
   ]
   where
     base = 100000
     (old, batch) = splitAt base (appendBlocks net 0 net.genesisHeader (base + 2000))
+    next = case batch of
+      h : _ -> h
+      [] -> error "Bench: no header to connect"
     now = net.genesisHeader.timestamp + 600 * fromIntegral (base + 3000)
     net =
       bchRegTest
@@ -509,6 +526,17 @@
           asertActivationTime = Just (net.genesisHeader.timestamp + 600 * 20),
           checkpoints = []
         }
+    -- The same network with the anchor of this chain set, as on mainnet.
+    anchorNet = (net :: Network) {asertAnchorBlock = Just (anchor.height, headerHash anchor.header)}
+    anchor = fromMaybe (error "Bench: no anchor") (fst (runState (asertAnchor net chain.best) chain))
+    -- The store and the batch, once the given connection gave the number of
+    -- headers expected.
+    checked :: State HeaderMemory (Either String [BlockNode]) -> Int -> IO (HeaderMemory, [BlockHeader])
+    checked run n = case fst (runState run chain) of
+      Right nodes
+        | length nodes == n -> return (chain, batch)
+        | otherwise -> fail ("Bench: connected " <> show (length nodes) <> " headers instead of " <> show n)
+      Left err -> fail ("Bench: the headers do not connect: " <> err)
     -- The store holding the first headers, built directly, without
     -- validation, so that building it is quick.
     chain = foldl' add (initialChain net) old
diff --git a/data/cashtokens_prefix_invalid.json b/data/cashtokens_prefix_invalid.json
new file mode 100644
--- /dev/null
+++ b/data/cashtokens_prefix_invalid.json
@@ -0,0 +1,222 @@
+[
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb00",
+    "error": "Invalid token prefix: must encode at least one token. Bitfield: 0b0"
+  },
+  {
+    "prefix": "ef",
+    "error": "Invalid token prefix: insufficient length. The minimum possible length is 34. Missing bytes: 33"
+  },
+  {
+    "prefix": "efbbbbbbbb1001",
+    "error": "Invalid token prefix: insufficient length. The minimum possible length is 34. Missing bytes: 27"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+    "error": "Invalid token prefix: insufficient length. The minimum possible length is 34. Missing bytes: 1"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb80",
+    "error": "Invalid token prefix: reserved bit is set. Bitfield: 0b10000000"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbba0",
+    "error": "Invalid token prefix: reserved bit is set. Bitfield: 0b10100000"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb9001",
+    "error": "Invalid token prefix: reserved bit is set. Bitfield: 0b10010000"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb23",
+    "error": "Invalid token prefix: capability must be none (0), mutable (1), or minting (2). Capability value: 3"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb24",
+    "error": "Invalid token prefix: capability must be none (0), mutable (1), or minting (2). Capability value: 4"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb25",
+    "error": "Invalid token prefix: capability must be none (0), mutable (1), or minting (2). Capability value: 5"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb26",
+    "error": "Invalid token prefix: capability must be none (0), mutable (1), or minting (2). Capability value: 6"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb27",
+    "error": "Invalid token prefix: capability must be none (0), mutable (1), or minting (2). Capability value: 7"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb28",
+    "error": "Invalid token prefix: capability must be none (0), mutable (1), or minting (2). Capability value: 8"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb29",
+    "error": "Invalid token prefix: capability must be none (0), mutable (1), or minting (2). Capability value: 9"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb2a",
+    "error": "Invalid token prefix: capability must be none (0), mutable (1), or minting (2). Capability value: 10"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb2b",
+    "error": "Invalid token prefix: capability must be none (0), mutable (1), or minting (2). Capability value: 11"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb2c",
+    "error": "Invalid token prefix: capability must be none (0), mutable (1), or minting (2). Capability value: 12"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb2d",
+    "error": "Invalid token prefix: capability must be none (0), mutable (1), or minting (2). Capability value: 13"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb2e",
+    "error": "Invalid token prefix: capability must be none (0), mutable (1), or minting (2). Capability value: 14"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb2f",
+    "error": "Invalid token prefix: capability must be none (0), mutable (1), or minting (2). Capability value: 15"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb1101",
+    "error": "Invalid token prefix: capability requires an NFT. Bitfield: 0b10001"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb1201",
+    "error": "Invalid token prefix: capability requires an NFT. Bitfield: 0b10010"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb40",
+    "error": "Invalid token prefix: commitment requires an NFT. Bitfield: 0b1000000"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb5001",
+    "error": "Invalid token prefix: commitment requires an NFT. Bitfield: 0b1010000"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb60",
+    "error": "Invalid token prefix: invalid non-fungible token commitment. Error reading CompactSize-prefixed bin: invalid CompactSize. Error reading CompactSize: requires at least one byte."
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb61",
+    "error": "Invalid token prefix: invalid non-fungible token commitment. Error reading CompactSize-prefixed bin: invalid CompactSize. Error reading CompactSize: requires at least one byte."
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb62",
+    "error": "Invalid token prefix: invalid non-fungible token commitment. Error reading CompactSize-prefixed bin: invalid CompactSize. Error reading CompactSize: requires at least one byte."
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb60fd0100cc",
+    "error": "Invalid token prefix: invalid non-fungible token commitment. Error reading CompactSize-prefixed bin: invalid CompactSize. Error reading CompactSize: CompactSize is not minimally encoded. Value: 1, encoded length: 3, canonical length: 1"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb60fe01000000cc",
+    "error": "Invalid token prefix: invalid non-fungible token commitment. Error reading CompactSize-prefixed bin: invalid CompactSize. Error reading CompactSize: CompactSize is not minimally encoded. Value: 1, encoded length: 5, canonical length: 1"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb60ff0100000000000000cc",
+    "error": "Invalid token prefix: invalid non-fungible token commitment. Error reading CompactSize-prefixed bin: invalid CompactSize. Error reading CompactSize: CompactSize is not minimally encoded. Value: 1, encoded length: 9, canonical length: 1"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb6000",
+    "error": "Invalid token prefix: if encoded, commitment length must be greater than 0."
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb700001",
+    "error": "Invalid token prefix: if encoded, commitment length must be greater than 0."
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb6001",
+    "error": "Invalid token prefix: invalid non-fungible token commitment. Error reading CompactSize-prefixed bin: insufficient bytes. Required bytes: 1, remaining bytes: 0"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb6101",
+    "error": "Invalid token prefix: invalid non-fungible token commitment. Error reading CompactSize-prefixed bin: insufficient bytes. Required bytes: 1, remaining bytes: 0"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb6102cc",
+    "error": "Invalid token prefix: invalid non-fungible token commitment. Error reading CompactSize-prefixed bin: insufficient bytes. Required bytes: 2, remaining bytes: 1"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb6202cc",
+    "error": "Invalid token prefix: invalid non-fungible token commitment. Error reading CompactSize-prefixed bin: insufficient bytes. Required bytes: 2, remaining bytes: 1"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb10",
+    "error": "Invalid token prefix: invalid fungible token amount encoding. Error reading CompactSize: requires at least one byte."
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb10fd00",
+    "error": "Invalid token prefix: invalid fungible token amount encoding. Error reading CompactSize: insufficient bytes. CompactSize prefix 253 requires at least 3 bytes. Remaining bytes: 2"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb10fe000000",
+    "error": "Invalid token prefix: invalid fungible token amount encoding. Error reading CompactSize: insufficient bytes. CompactSize prefix 254 requires at least 5 bytes. Remaining bytes: 4"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb10ff00000000000000",
+    "error": "Invalid token prefix: invalid fungible token amount encoding. Error reading CompactSize: insufficient bytes. CompactSize prefix 255 requires at least 9 bytes. Remaining bytes: 8"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7001cc",
+    "error": "Invalid token prefix: invalid fungible token amount encoding. Error reading CompactSize: requires at least one byte."
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7001ccfd00",
+    "error": "Invalid token prefix: invalid fungible token amount encoding. Error reading CompactSize: insufficient bytes. CompactSize prefix 253 requires at least 3 bytes. Remaining bytes: 2"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7001ccfe000000",
+    "error": "Invalid token prefix: invalid fungible token amount encoding. Error reading CompactSize: insufficient bytes. CompactSize prefix 254 requires at least 5 bytes. Remaining bytes: 4"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7001ccff00000000000000",
+    "error": "Invalid token prefix: invalid fungible token amount encoding. Error reading CompactSize: insufficient bytes. CompactSize prefix 255 requires at least 9 bytes. Remaining bytes: 8"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb30",
+    "error": "Invalid token prefix: invalid fungible token amount encoding. Error reading CompactSize: requires at least one byte."
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb1000",
+    "error": "Invalid token prefix: if encoded, fungible token amount must be greater than 0."
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb3000",
+    "error": "Invalid token prefix: if encoded, fungible token amount must be greater than 0."
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb10fd0100",
+    "error": "Invalid token prefix: invalid fungible token amount encoding. Error reading CompactSize: CompactSize is not minimally encoded. Value: 1, encoded length: 3, canonical length: 1"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb10fe01000000",
+    "error": "Invalid token prefix: invalid fungible token amount encoding. Error reading CompactSize: CompactSize is not minimally encoded. Value: 1, encoded length: 5, canonical length: 1"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb10ff0100000000000000",
+    "error": "Invalid token prefix: invalid fungible token amount encoding. Error reading CompactSize: CompactSize is not minimally encoded. Value: 1, encoded length: 9, canonical length: 1"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb30fd0100",
+    "error": "Invalid token prefix: invalid fungible token amount encoding. Error reading CompactSize: CompactSize is not minimally encoded. Value: 1, encoded length: 3, canonical length: 1"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb30fe01000000",
+    "error": "Invalid token prefix: invalid fungible token amount encoding. Error reading CompactSize: CompactSize is not minimally encoded. Value: 1, encoded length: 5, canonical length: 1"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb30ff0100000000000000",
+    "error": "Invalid token prefix: invalid fungible token amount encoding. Error reading CompactSize: CompactSize is not minimally encoded. Value: 1, encoded length: 9, canonical length: 1"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb10ff0000000000000080",
+    "error": "Invalid token prefix: exceeds maximum fungible token amount of 9223372036854775807. Encoded amount: 9223372036854775808"
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb30ff0000000000000080",
+    "error": "Invalid token prefix: exceeds maximum fungible token amount of 9223372036854775807. Encoded amount: 9223372036854775808"
+  }
+]
diff --git a/data/cashtokens_prefix_valid.json b/data/cashtokens_prefix_valid.json
new file mode 100644
--- /dev/null
+++ b/data/cashtokens_prefix_valid.json
@@ -0,0 +1,632 @@
+[
+  {
+    "prefix": "efaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1001",
+    "data": {
+      "amount": "1",
+      "category": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+    }
+  },
+  {
+    "prefix": "ef21430000000000000000000000000000000000000000000000000000000034121001",
+    "data": {
+      "amount": "1",
+      "category": "1234000000000000000000000000000000000000000000000000000000004321"
+    }
+  },
+  {
+    "prefix": "ef21436587090000000000000000000000000000000000000000000090785634121001",
+    "data": {
+      "amount": "1",
+      "category": "1234567890000000000000000000000000000000000000000000000987654321"
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb1001",
+    "data": {
+      "amount": "1",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb10fc",
+    "data": {
+      "amount": "252",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb10fdfd00",
+    "data": {
+      "amount": "253",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb10fdffff",
+    "data": {
+      "amount": "65535",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb10fe00000100",
+    "data": {
+      "amount": "65536",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb10fe01000100",
+    "data": {
+      "amount": "65537",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb10feffffffff",
+    "data": {
+      "amount": "4294967295",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb10ff0000000001000000",
+    "data": {
+      "amount": "4294967296",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb10ff0100000001000000",
+    "data": {
+      "amount": "4294967297",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb10ffffffffffffffff7f",
+    "data": {
+      "amount": "9223372036854775807",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb20",
+    "data": {
+      "amount": "0",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb3001",
+    "data": {
+      "amount": "1",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb30fc",
+    "data": {
+      "amount": "252",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb30fdfd00",
+    "data": {
+      "amount": "253",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb30fdffff",
+    "data": {
+      "amount": "65535",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb30fe00000100",
+    "data": {
+      "amount": "65536",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb30feffffffff",
+    "data": {
+      "amount": "4294967295",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb30ff0000000001000000",
+    "data": {
+      "amount": "4294967296",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb30ffffffffffffffff7f",
+    "data": {
+      "amount": "9223372036854775807",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb6001cc",
+    "data": {
+      "amount": "0",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cc",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb60051234567890",
+    "data": {
+      "amount": "0",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "1234567890",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7001cc01",
+    "data": {
+      "amount": "1",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cc",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7001ccfc",
+    "data": {
+      "amount": "252",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cc",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7001ccfdfd00",
+    "data": {
+      "amount": "253",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cc",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7001ccfdffff",
+    "data": {
+      "amount": "65535",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cc",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7001ccfe00000100",
+    "data": {
+      "amount": "65536",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cc",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7001ccfeffffffff",
+    "data": {
+      "amount": "4294967295",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cc",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7001ccff0000000001000000",
+    "data": {
+      "amount": "4294967296",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cc",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7001ccffffffffffffffff7f",
+    "data": {
+      "amount": "9223372036854775807",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cc",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb700accccccccccccccccccccfdffff",
+    "data": {
+      "amount": "65535",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccccccccccccccccccc",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7028ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccfe00000100",
+    "data": {
+      "amount": "65536",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7029ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccfe00000100",
+    "data": {
+      "amount": "65536",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb60fdfd00cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+    "data": {
+      "amount": "0",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb70fdfd00ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccfe00000100",
+    "data": {
+      "amount": "65536",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb70fde903ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccfe00000100",
+    "data": {
+      "amount": "65536",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+        "capability": "none"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb21",
+    "data": {
+      "amount": "0",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "",
+        "capability": "mutable"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb31feffffffff",
+    "data": {
+      "amount": "4294967295",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "",
+        "capability": "mutable"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb6101cc",
+    "data": {
+      "amount": "0",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cc",
+        "capability": "mutable"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7101ccff0000000001000000",
+    "data": {
+      "amount": "4294967296",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cc",
+        "capability": "mutable"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7102ccccffffffffffffffff7f",
+    "data": {
+      "amount": "9223372036854775807",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccc",
+        "capability": "mutable"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb710acccccccccccccccccccc01",
+    "data": {
+      "amount": "1",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccccccccccccccccccc",
+        "capability": "mutable"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7128ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccfc",
+    "data": {
+      "amount": "252",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+        "capability": "mutable"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7129ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccfc",
+    "data": {
+      "amount": "252",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+        "capability": "mutable"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb71fdfd00cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc01",
+    "data": {
+      "amount": "1",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+        "capability": "mutable"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb22",
+    "data": {
+      "amount": "0",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "",
+        "capability": "minting"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb3201",
+    "data": {
+      "amount": "1",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "",
+        "capability": "minting"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb32fdfd00",
+    "data": {
+      "amount": "253",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "",
+        "capability": "minting"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb32fe00000100",
+    "data": {
+      "amount": "65536",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "",
+        "capability": "minting"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb32ff0000000001000000",
+    "data": {
+      "amount": "4294967296",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "",
+        "capability": "minting"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb32ffffffffffffffff7f",
+    "data": {
+      "amount": "9223372036854775807",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "",
+        "capability": "minting"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb6201cc",
+    "data": {
+      "amount": "0",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cc",
+        "capability": "minting"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb6229cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+    "data": {
+      "amount": "0",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+        "capability": "minting"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7201ccfdffff",
+    "data": {
+      "amount": "65535",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cc",
+        "capability": "minting"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7202ccccfe00000100",
+    "data": {
+      "amount": "65536",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccc",
+        "capability": "minting"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb720accccccccccccccccccccff0100000001000000",
+    "data": {
+      "amount": "4294967297",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccccccccccccccccccc",
+        "capability": "minting"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7228ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccffffffffffffffff7f",
+    "data": {
+      "amount": "9223372036854775807",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+        "capability": "minting"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7229ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccffffffffffffffff7f",
+    "data": {
+      "amount": "9223372036854775807",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+        "capability": "minting"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb62fdfd00cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+    "data": {
+      "amount": "0",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+        "capability": "minting"
+      }
+    }
+  },
+  {
+    "prefix": "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb72fdfd00ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccfe00000100",
+    "data": {
+      "amount": "65536",
+      "category": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+      "nft": {
+        "commitment": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+        "capability": "minting"
+      }
+    }
+  }
+]
diff --git a/data/psbt_bip373.json b/data/psbt_bip373.json
new file mode 100644
--- /dev/null
+++ b/data/psbt_bip373.json
@@ -0,0 +1,128 @@
+{
+  "description": "Test vectors of BIP 373, MuSig2 fields in PSBT",
+  "source": "https://github.com/bitcoin/bips/blob/master/bip-0373.mediawiki",
+  "invalid": [
+    {
+      "case": "PSBT with x-only aggregate pubkey in input participant pubkeys keydata",
+      "hex": "70736274ff01005202000000015686dff400165f4e040a5855f658093472c9bcf8108b272a5d31f181f7b4ffb10100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f505000000002251200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d421160b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d405002680dd6e2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a822116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd65592211a0b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f90000",
+      "base64": "cHNidP8BAFICAAAAAVaG3/QAFl9OBApYVfZYCTRyybz4EIsnKl0x8YH3tP+xAQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEgC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9QhFgtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUBQAmgN1uIRY0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAUAWAsIhyEWT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwFAMMkmoIhFvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5BQB91lWSIRoLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1GMCNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQACT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkAAA=="
+    },
+    {
+      "case": "PSBT with an x-only input participant pubkey",
+      "hex": "70736274ff01005202000000015686dff400165f4e040a5855f658093472c9bcf8108b272a5d31f181f7b4ffb10100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f505000000002251200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d421160b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d405002680dd6e2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a822116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd65592221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d462346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f90000",
+      "base64": "cHNidP8BAFICAAAAAVaG3/QAFl9OBApYVfZYCTRyybz4EIsnKl0x8YH3tP+xAQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEgC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9QhFgtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUBQAmgN1uIRY0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAUAWAsIhyEWT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwFAMMkmoIhFvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5BQB91lWSIhoDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RiNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQACT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkAAA=="
+    },
+    {
+      "case": "PSBT with x-only aggregate pubkey in output participant pubkeys keydata",
+      "hex": "70736274ff01007d02000000012589e7767958ba154f9018cccf0dedea6147bb60cd1a194b6e3590a9965690d60000000000fdffffff0280969800000000002251202967d2d020a9795da72b51be4f3fca25bb0e57e91c5b3e7a81abfa7232a349420fc0927c00000000160014349c5d330278c3002a64f597d2b01aa3dc1bd903000000000001007d02000000019a8b4a50796b9600990f7fe11dfa00bc70efd296048afc86719af0fb1fa919370000000000fdffffff02895c2b7d00000000160014cfd98ba1027ea4ed4bd2ae1b348b6156a015037500e1f50500000000225120d0b226c6599f273874df8fe684ab6c3028081bee8a2cbed31a136f5865f6cfa4e100000001011f895c2b7d00000000160014cfd98ba1027ea4ed4bd2ae1b348b6156a0150375220602a66650f08bffa4f089eb22edcdbe7616645ff6cd180a36484d4bc81054595b7b18bfff44a3540000800100008000000080010000008a020000000105200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d421070b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d405002680dd6e2107346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721074fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a822107f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd6559221080b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f900220203be4ae53d37cc075f40b30d6da4729d40adeeb983533af1616192bc76d5b2612a18bfff44a3540000800100008000000080010000008d02000000",
+      "base64": "cHNidP8BAH0CAAAAASWJ53Z5WLoVT5AYzM8N7ephR7tgzRoZS241kKmWVpDWAAAAAAD9////AoCWmAAAAAAAIlEgKWfS0CCpeV2nK1G+Tz/KJbsOV+kcWz56gav6cjKjSUIPwJJ8AAAAABYAFDScXTMCeMMAKmT1l9KwGqPcG9kDAAAAAAABAH0CAAAAAZqLSlB5a5YAmQ9/4R36ALxw79KWBIr8hnGa8PsfqRk3AAAAAAD9////AolcK30AAAAAFgAUz9mLoQJ+pO1L0q4bNIthVqAVA3UA4fUFAAAAACJRINCyJsZZnyc4dN+P5oSrbDAoCBvuiiy+0xoTb1hl9s+k4QAAAAEBH4lcK30AAAAAFgAUz9mLoQJ+pO1L0q4bNIthVqAVA3UiBgKmZlDwi/+k8InrIu3NvnYWZF/2zRgKNkhNS8gQVFlbexi//0SjVAAAgAEAAIAAAACAAQAAAIoCAAAAAQUgC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9QhBwtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUBQAmgN1uIQc0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAUAWAsIhyEHT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwFAMMkmoIhB/kwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5BQB91lWSIQgLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1GMCNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQACT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkAIgIDvkrlPTfMB19Asw1tpHKdQK3uuYNTOvFhYZK8dtWyYSoYv/9Eo1QAAIABAACAAAAAgAEAAACNAgAAAA=="
+    },
+    {
+      "case": "PSBT with an x-only output participant pubkey",
+      "hex": "70736274ff01007d02000000012589e7767958ba154f9018cccf0dedea6147bb60cd1a194b6e3590a9965690d60000000000fdffffff0280969800000000002251202967d2d020a9795da72b51be4f3fca25bb0e57e91c5b3e7a81abfa7232a349420fc0927c00000000160014349c5d330278c3002a64f597d2b01aa3dc1bd903000000000001007d02000000019a8b4a50796b9600990f7fe11dfa00bc70efd296048afc86719af0fb1fa919370000000000fdffffff02895c2b7d00000000160014cfd98ba1027ea4ed4bd2ae1b348b6156a015037500e1f50500000000225120d0b226c6599f273874df8fe684ab6c3028081bee8a2cbed31a136f5865f6cfa4e100000001011f895c2b7d00000000160014cfd98ba1027ea4ed4bd2ae1b348b6156a0150375220602a66650f08bffa4f089eb22edcdbe7616645ff6cd180a36484d4bc81054595b7b18bfff44a3540000800100008000000080010000008a020000000105200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d421070b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d405002680dd6e2107346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721074fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a822107f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd655922208030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d462346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f900220203be4ae53d37cc075f40b30d6da4729d40adeeb983533af1616192bc76d5b2612a18bfff44a3540000800100008000000080010000008d02000000",
+      "base64": "cHNidP8BAH0CAAAAASWJ53Z5WLoVT5AYzM8N7ephR7tgzRoZS241kKmWVpDWAAAAAAD9////AoCWmAAAAAAAIlEgKWfS0CCpeV2nK1G+Tz/KJbsOV+kcWz56gav6cjKjSUIPwJJ8AAAAABYAFDScXTMCeMMAKmT1l9KwGqPcG9kDAAAAAAABAH0CAAAAAZqLSlB5a5YAmQ9/4R36ALxw79KWBIr8hnGa8PsfqRk3AAAAAAD9////AolcK30AAAAAFgAUz9mLoQJ+pO1L0q4bNIthVqAVA3UA4fUFAAAAACJRINCyJsZZnyc4dN+P5oSrbDAoCBvuiiy+0xoTb1hl9s+k4QAAAAEBH4lcK30AAAAAFgAUz9mLoQJ+pO1L0q4bNIthVqAVA3UiBgKmZlDwi/+k8InrIu3NvnYWZF/2zRgKNkhNS8gQVFlbexi//0SjVAAAgAEAAIAAAACAAQAAAIoCAAAAAQUgC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9QhBwtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUBQAmgN1uIQc0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAUAWAsIhyEHT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwFAMMkmoIhB/kwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5BQB91lWSIggDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RiNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQACT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkAIgIDvkrlPTfMB19Asw1tpHKdQK3uuYNTOvFhYZK8dtWyYSoYv/9Eo1QAAIABAACAAAAAgAEAAACNAgAAAA=="
+    },
+    {
+      "case": "PSBT with x-only aggregate pubkey in public nonce keydata",
+      "hex": "70736274ff01005202000000015686dff400165f4e040a5855f658093472c9bcf8108b272a5d31f181f7b4ffb10100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f505000000002251200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d421160b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d405002680dd6e2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a822116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd65592221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9421b02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d44202529b19d7879ccc04c915487f5f1341bc6858b0bc74e5036c643d37b53a4371b503b7f8afe3263fcb3ef2454fe16f3a6759c5600c78e637b8dfa0d83e8552882056431b024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d44203a81d973499e74f82d2b5ab13f1e69e9e11a5fdb40f5466ef672e6e4ceba0be7903499593767150394eece384d051c45b615c52dbe1c8eb3610d7b344b43b7dad6d431b02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d442033949dbff31b9d50251d8821e66cc5c97b7e3afd7d95bfdc77500fda8947f3ae0023f20e4f0bf0b76f0d40cd3abfe7ce373d6685bbd77b5fa28e7f49fb429d189b00000",
+      "base64": "cHNidP8BAFICAAAAAVaG3/QAFl9OBApYVfZYCTRyybz4EIsnKl0x8YH3tP+xAQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEgC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9QhFgtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUBQAmgN1uIRY0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAUAWAsIhyEWT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwFAMMkmoIhFvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5BQB91lWSIhoDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RjAjRrmVkzVxB8nTRZ6d66jT6vROZjbIXH+FPrkLpS6M0AAk+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsAvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5QhsCNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQALWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1EICUpsZ14eczATJFUh/XxNBvGhYsLx05QNsZD03tTpDcbUDt/iv4yY/yz7yRU/hbzpnWcVgDHjmN7jfoNg+hVKIIFZDGwJPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLAMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1EIDqB2XNJnnT4LStasT8eaenhGl/bQPVGbvZy5uTOugvnkDSZWTdnFQOU7s44TQUcRbYVxS2+HI6zYQ17NEtDt9rW1DGwL5MIoBkljDEEk0T4X4nVIptTHIRYNvmbCGAfETvOA2+QMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1EIDOUnb/zG51QJR2IIeZsxcl7fjr9fZW/3HdQD9qJR/OuACPyDk8L8LdvDUDNOr/nzjc9ZoW713tfoo5/SftCnRibAAAA=="
+    },
+    {
+      "case": "PSBT with an x-only participant pubkey in public nonce keydata",
+      "hex": "70736274ff01005202000000015686dff400165f4e040a5855f658093472c9bcf8108b272a5d31f181f7b4ffb10100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f505000000002251200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d421160b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d405002680dd6e2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a822116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd65592221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9421b346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d44202529b19d7879ccc04c915487f5f1341bc6858b0bc74e5036c643d37b53a4371b503b7f8afe3263fcb3ef2454fe16f3a6759c5600c78e637b8dfa0d83e8552882056431b024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d44203a81d973499e74f82d2b5ab13f1e69e9e11a5fdb40f5466ef672e6e4ceba0be7903499593767150394eece384d051c45b615c52dbe1c8eb3610d7b344b43b7dad6d431b02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d442033949dbff31b9d50251d8821e66cc5c97b7e3afd7d95bfdc77500fda8947f3ae0023f20e4f0bf0b76f0d40cd3abfe7ce373d6685bbd77b5fa28e7f49fb429d189b00000",
+      "base64": "cHNidP8BAFICAAAAAVaG3/QAFl9OBApYVfZYCTRyybz4EIsnKl0x8YH3tP+xAQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEgC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9QhFgtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUBQAmgN1uIRY0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAUAWAsIhyEWT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwFAMMkmoIhFvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5BQB91lWSIhoDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RjAjRrmVkzVxB8nTRZ6d66jT6vROZjbIXH+FPrkLpS6M0AAk+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsAvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5Qhs0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1EICUpsZ14eczATJFUh/XxNBvGhYsLx05QNsZD03tTpDcbUDt/iv4yY/yz7yRU/hbzpnWcVgDHjmN7jfoNg+hVKIIFZDGwJPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLAMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1EIDqB2XNJnnT4LStasT8eaenhGl/bQPVGbvZy5uTOugvnkDSZWTdnFQOU7s44TQUcRbYVxS2+HI6zYQ17NEtDt9rW1DGwL5MIoBkljDEEk0T4X4nVIptTHIRYNvmbCGAfETvOA2+QMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1EIDOUnb/zG51QJR2IIeZsxcl7fjr9fZW/3HdQD9qJR/OuACPyDk8L8LdvDUDNOr/nzjc9ZoW713tfoo5/SftCnRibAAAA=="
+    },
+    {
+      "case": "PSBT with invalid public nonce valuedata length",
+      "hex": "70736274ff01005202000000015686dff400165f4e040a5855f658093472c9bcf8108b272a5d31f181f7b4ffb10100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f505000000002251200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d421160b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d405002680dd6e2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a822116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd65592221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9431b02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d44102529b19d7879ccc04c915487f5f1341bc6858b0bc74e5036c643d37b53a4371b503b7f8afe3263fcb3ef2454fe16f3a6759c5600c78e637b8dfa0d83e85528820431b024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d44203a81d973499e74f82d2b5ab13f1e69e9e11a5fdb40f5466ef672e6e4ceba0be7903499593767150394eece384d051c45b615c52dbe1c8eb3610d7b344b43b7dad6d431b02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d442033949dbff31b9d50251d8821e66cc5c97b7e3afd7d95bfdc77500fda8947f3ae0023f20e4f0bf0b76f0d40cd3abfe7ce373d6685bbd77b5fa28e7f49fb429d189b00000",
+      "base64": "cHNidP8BAFICAAAAAVaG3/QAFl9OBApYVfZYCTRyybz4EIsnKl0x8YH3tP+xAQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEgC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9QhFgtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUBQAmgN1uIRY0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAUAWAsIhyEWT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwFAMMkmoIhFvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5BQB91lWSIhoDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RjAjRrmVkzVxB8nTRZ6d66jT6vROZjbIXH+FPrkLpS6M0AAk+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsAvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5QxsCNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQADC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RBAlKbGdeHnMwEyRVIf18TQbxoWLC8dOUDbGQ9N7U6Q3G1A7f4r+MmP8s+8kVP4W86Z1nFYAx45je436DYPoVSiCBDGwJPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLAMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1EIDqB2XNJnnT4LStasT8eaenhGl/bQPVGbvZy5uTOugvnkDSZWTdnFQOU7s44TQUcRbYVxS2+HI6zYQ17NEtDt9rW1DGwL5MIoBkljDEEk0T4X4nVIptTHIRYNvmbCGAfETvOA2+QMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1EIDOUnb/zG51QJR2IIeZsxcl7fjr9fZW/3HdQD9qJR/OuACPyDk8L8LdvDUDNOr/nzjc9ZoW713tfoo5/SftCnRibAAAA=="
+    },
+    {
+      "case": "PSBT with x-only aggregate pubkey in partial sig keydata",
+      "hex": "70736274ff01005202000000019a8b4a50796b9600990f7fe11dfa00bc70efd296048afc86719af0fb1fa919370100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f5050000000022512056bdb481b4d67103f6d5dea8a9aafd3684a6a79b4a2e247799db8d4b1a86e1f841140b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c402667d52f6cc07fe06db31b1a5f7efe81903f9cbeef40fa64dafca01d2cb1d56403bc7504898e55872557d16d2ca79bc55fef10973841a33ec032d884758c9fe62215c050929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac023200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4acc021160b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d42501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c2680dd6e2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd002501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c2501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2cc3249a82211650929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac005007c461e5d2116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f92501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c7dd6559201172050929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0011820b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9631b02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c4202d99e7c8719b3ad08566b0cb9c7d5eda3127c9e8119185b7d584d939b173915f50240df22aab78332cf0f25329d103dc0d2060a03742e9448026e736bcf3db98f3c631b024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c4202e702a7075226a0d9313a77e6db10b8e742d4cffdc948a0edc9b856c13b412e5403386a0298f308fb3099155772e45b2aa8e770f435bedfe2041d1cc4d3d37538c6631b02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c4202b1d912d45d753ceed0954417ba982656d2aec53f8638bd6f297dae3b743d71b0032f424537d599d28f14d59fe0a11b82fea2aa226a2980ffdacad5fdab20f80683621c02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c20ada78b70af8cffa4c50863aef515ac58a327cd58c55bad29a162e67d9c413322631c024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c201fa8b7e6741c21eb8d9b0f65269df9e423369fc390ad2e918420c57feb2a1b61631c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c20366c31ad65e533f6d2b45e5910f3f587543f8061918167bf5a818b13be5792a40000",
+      "base64": "cHNidP8BAFICAAAAAZqLSlB5a5YAmQ9/4R36ALxw79KWBIr8hnGa8PsfqRk3AQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEgVr20gbTWcQP21d6oqar9NoSmp5tKLiR3mduNSxqG4fhBFAtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+ixAJmfVL2zAf+BtsxsaX37+gZA/nL7vQPpk2vygHSyx1WQDvHUEiY5VhyVX0W0sp5vFX+8QlzhBoz7AMtiEdYyf5iIVwFCSm3TBoElUt4tLYDXpel4HiloPKOyW1Ue/7prOgDrAIyALWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1KzAIRYLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1CUBsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+iwmgN1uIRY0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNACUBsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+ixYCwiHIRZPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLCUBsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+izDJJqCIRZQkpt0waBJVLeLS2A16XpeB4paDyjsltVHv+6azoA6wAUAfEYeXSEW+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvklAbEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosfdZVkgEXIFCSm3TBoElUt4tLYDXpel4HiloPKOyW1Ue/7prOgDrAARggsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+iwiGgMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1GMCNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQACT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvljGwI0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1LEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosQgLZnnyHGbOtCFZrDLnH1e2jEnyegRkYW31YTZObFzkV9QJA3yKqt4Myzw8lMp0QPcDSBgoDdC6USAJuc2vPPbmPPGMbAk+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsAwtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+ixCAucCpwdSJqDZMTp35tsQuOdC1M/9yUig7cm4VsE7QS5UAzhqApjzCPswmRVXcuRbKqjncPQ1vt/iBB0cxNPTdTjGYxsC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9SxH+2qY6CVZQGnMIyTtWNzcedhPZuK3heD1J4mwGz6LEICsdkS1F11PO7QlUQXupgmVtKuxT+GOL1vKX2uO3Q9cbADL0JFN9WZ0o8U1Z/goRuC/qKqImopgP/aytX9qyD4BoNiHAI0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+iwgraeLcK+M/6TFCGOu9RWsWKMnzVjFW60poWLmfZxBMyJjHAJPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLAMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1LEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosIB+ot+Z0HCHrjZsPZSad+eQjNp/DkK0ukYQgxX/rKhthYxwC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9SxH+2qY6CVZQGnMIyTtWNzcedhPZuK3heD1J4mwGz6LCA2bDGtZeUz9tK0XlkQ8/WHVD+AYZGBZ79agYsTvleSpAAA"
+    },
+    {
+      "case": "PSBT with an x-only participant pubkey in partial sig keydata",
+      "hex": "70736274ff01005202000000019a8b4a50796b9600990f7fe11dfa00bc70efd296048afc86719af0fb1fa919370100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f5050000000022512056bdb481b4d67103f6d5dea8a9aafd3684a6a79b4a2e247799db8d4b1a86e1f841140b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c402667d52f6cc07fe06db31b1a5f7efe81903f9cbeef40fa64dafca01d2cb1d56403bc7504898e55872557d16d2ca79bc55fef10973841a33ec032d884758c9fe62215c050929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac023200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4acc021160b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d42501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c2680dd6e2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd002501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c2501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2cc3249a82211650929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac005007c461e5d2116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f92501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c7dd6559201172050929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0011820b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9631b02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c4202d99e7c8719b3ad08566b0cb9c7d5eda3127c9e8119185b7d584d939b173915f50240df22aab78332cf0f25329d103dc0d2060a03742e9448026e736bcf3db98f3c631b024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c4202e702a7075226a0d9313a77e6db10b8e742d4cffdc948a0edc9b856c13b412e5403386a0298f308fb3099155772e45b2aa8e770f435bedfe2041d1cc4d3d37538c6631b02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c4202b1d912d45d753ceed0954417ba982656d2aec53f8638bd6f297dae3b743d71b0032f424537d599d28f14d59fe0a11b82fea2aa226a2980ffdacad5fdab20f80683621c346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c20ada78b70af8cffa4c50863aef515ac58a327cd58c55bad29a162e67d9c413322631c024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c201fa8b7e6741c21eb8d9b0f65269df9e423369fc390ad2e918420c57feb2a1b61631c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c20366c31ad65e533f6d2b45e5910f3f587543f8061918167bf5a818b13be5792a40000",
+      "base64": "cHNidP8BAFICAAAAAZqLSlB5a5YAmQ9/4R36ALxw79KWBIr8hnGa8PsfqRk3AQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEgVr20gbTWcQP21d6oqar9NoSmp5tKLiR3mduNSxqG4fhBFAtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+ixAJmfVL2zAf+BtsxsaX37+gZA/nL7vQPpk2vygHSyx1WQDvHUEiY5VhyVX0W0sp5vFX+8QlzhBoz7AMtiEdYyf5iIVwFCSm3TBoElUt4tLYDXpel4HiloPKOyW1Ue/7prOgDrAIyALWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1KzAIRYLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1CUBsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+iwmgN1uIRY0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNACUBsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+ixYCwiHIRZPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLCUBsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+izDJJqCIRZQkpt0waBJVLeLS2A16XpeB4paDyjsltVHv+6azoA6wAUAfEYeXSEW+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvklAbEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosfdZVkgEXIFCSm3TBoElUt4tLYDXpel4HiloPKOyW1Ue/7prOgDrAARggsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+iwiGgMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1GMCNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQACT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvljGwI0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1LEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosQgLZnnyHGbOtCFZrDLnH1e2jEnyegRkYW31YTZObFzkV9QJA3yKqt4Myzw8lMp0QPcDSBgoDdC6USAJuc2vPPbmPPGMbAk+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsAwtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+ixCAucCpwdSJqDZMTp35tsQuOdC1M/9yUig7cm4VsE7QS5UAzhqApjzCPswmRVXcuRbKqjncPQ1vt/iBB0cxNPTdTjGYxsC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9SxH+2qY6CVZQGnMIyTtWNzcedhPZuK3heD1J4mwGz6LEICsdkS1F11PO7QlUQXupgmVtKuxT+GOL1vKX2uO3Q9cbADL0JFN9WZ0o8U1Z/goRuC/qKqImopgP/aytX9qyD4BoNiHDRrmVkzVxB8nTRZ6d66jT6vROZjbIXH+FPrkLpS6M0AAwtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+iwgraeLcK+M/6TFCGOu9RWsWKMnzVjFW60poWLmfZxBMyJjHAJPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLAMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1LEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosIB+ot+Z0HCHrjZsPZSad+eQjNp/DkK0ukYQgxX/rKhthYxwC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9SxH+2qY6CVZQGnMIyTtWNzcedhPZuK3heD1J4mwGz6LCA2bDGtZeUz9tK0XlkQ8/WHVD+AYZGBZ79agYsTvleSpAAA"
+    },
+    {
+      "case": "PSBT with invalid partial sig valuedata length",
+      "hex": "70736274ff01005202000000019a8b4a50796b9600990f7fe11dfa00bc70efd296048afc86719af0fb1fa919370100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f5050000000022512056bdb481b4d67103f6d5dea8a9aafd3684a6a79b4a2e247799db8d4b1a86e1f841140b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c402667d52f6cc07fe06db31b1a5f7efe81903f9cbeef40fa64dafca01d2cb1d56403bc7504898e55872557d16d2ca79bc55fef10973841a33ec032d884758c9fe62215c050929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac023200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4acc021160b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d42501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c2680dd6e2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd002501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c2501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2cc3249a82211650929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac005007c461e5d2116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f92501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c7dd6559201172050929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0011820b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9631b02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c4202d99e7c8719b3ad08566b0cb9c7d5eda3127c9e8119185b7d584d939b173915f50240df22aab78332cf0f25329d103dc0d2060a03742e9448026e736bcf3db98f3c631b024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c4202e702a7075226a0d9313a77e6db10b8e742d4cffdc948a0edc9b856c13b412e5403386a0298f308fb3099155772e45b2aa8e770f435bedfe2041d1cc4d3d37538c6631b02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c4202b1d912d45d753ceed0954417ba982656d2aec53f8638bd6f297dae3b743d71b0032f424537d599d28f14d59fe0a11b82fea2aa226a2980ffdacad5fdab20f80683631c02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c1fa78b70af8cffa4c50863aef515ac58a327cd58c55bad29a162e67d9c413322631c024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c201fa8b7e6741c21eb8d9b0f65269df9e423369fc390ad2e918420c57feb2a1b61631c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c20366c31ad65e533f6d2b45e5910f3f587543f8061918167bf5a818b13be5792a40000",
+      "base64": "cHNidP8BAFICAAAAAZqLSlB5a5YAmQ9/4R36ALxw79KWBIr8hnGa8PsfqRk3AQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEgVr20gbTWcQP21d6oqar9NoSmp5tKLiR3mduNSxqG4fhBFAtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+ixAJmfVL2zAf+BtsxsaX37+gZA/nL7vQPpk2vygHSyx1WQDvHUEiY5VhyVX0W0sp5vFX+8QlzhBoz7AMtiEdYyf5iIVwFCSm3TBoElUt4tLYDXpel4HiloPKOyW1Ue/7prOgDrAIyALWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1KzAIRYLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1CUBsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+iwmgN1uIRY0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNACUBsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+ixYCwiHIRZPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLCUBsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+izDJJqCIRZQkpt0waBJVLeLS2A16XpeB4paDyjsltVHv+6azoA6wAUAfEYeXSEW+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvklAbEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosfdZVkgEXIFCSm3TBoElUt4tLYDXpel4HiloPKOyW1Ue/7prOgDrAARggsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+iwiGgMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1GMCNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQACT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvljGwI0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1LEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosQgLZnnyHGbOtCFZrDLnH1e2jEnyegRkYW31YTZObFzkV9QJA3yKqt4Myzw8lMp0QPcDSBgoDdC6USAJuc2vPPbmPPGMbAk+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsAwtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+ixCAucCpwdSJqDZMTp35tsQuOdC1M/9yUig7cm4VsE7QS5UAzhqApjzCPswmRVXcuRbKqjncPQ1vt/iBB0cxNPTdTjGYxsC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9SxH+2qY6CVZQGnMIyTtWNzcedhPZuK3heD1J4mwGz6LEICsdkS1F11PO7QlUQXupgmVtKuxT+GOL1vKX2uO3Q9cbADL0JFN9WZ0o8U1Z/goRuC/qKqImopgP/aytX9qyD4BoNjHAI0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1LEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosH6eLcK+M/6TFCGOu9RWsWKMnzVjFW60poWLmfZxBMyJjHAJPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLAMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1LEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosIB+ot+Z0HCHrjZsPZSad+eQjNp/DkK0ukYQgxX/rKhthYxwC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9SxH+2qY6CVZQGnMIyTtWNzcedhPZuK3heD1J4mwGz6LCA2bDGtZeUz9tK0XlkQ8/WHVD+AYZGBZ79agYsTvleSpAAA"
+    }
+  ],
+  "valid": [
+    {
+      "case": "Spend of a Taproot output where the output key is a MuSig2 Aggregate Pubkey: with participant pubkeys only",
+      "hex": "70736274ff01005202000000015686dff400165f4e040a5855f658093472c9bcf8108b272a5d31f181f7b4ffb10100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f505000000002251200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d421160b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d405002680dd6e2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a822116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd65592221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f90000",
+      "base64": "cHNidP8BAFICAAAAAVaG3/QAFl9OBApYVfZYCTRyybz4EIsnKl0x8YH3tP+xAQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEgC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9QhFgtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUBQAmgN1uIRY0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAUAWAsIhyEWT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwFAMMkmoIhFvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5BQB91lWSIhoDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RjAjRrmVkzVxB8nTRZ6d66jT6vROZjbIXH+FPrkLpS6M0AAk+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsAvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5AAA="
+    },
+    {
+      "case": "Spend of a Taproot output where the output key is a MuSig2 Aggregate Pubkey: with all pubnonces",
+      "hex": "70736274ff01005202000000015686dff400165f4e040a5855f658093472c9bcf8108b272a5d31f181f7b4ffb10100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f505000000002251200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d421160b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d405002680dd6e2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a822116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd65592221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9431b02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d44202529b19d7879ccc04c915487f5f1341bc6858b0bc74e5036c643d37b53a4371b503b7f8afe3263fcb3ef2454fe16f3a6759c5600c78e637b8dfa0d83e8552882056431b024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d44203a81d973499e74f82d2b5ab13f1e69e9e11a5fdb40f5466ef672e6e4ceba0be7903499593767150394eece384d051c45b615c52dbe1c8eb3610d7b344b43b7dad6d431b02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d442033949dbff31b9d50251d8821e66cc5c97b7e3afd7d95bfdc77500fda8947f3ae0023f20e4f0bf0b76f0d40cd3abfe7ce373d6685bbd77b5fa28e7f49fb429d189b00000",
+      "base64": "cHNidP8BAFICAAAAAVaG3/QAFl9OBApYVfZYCTRyybz4EIsnKl0x8YH3tP+xAQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEgC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9QhFgtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUBQAmgN1uIRY0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAUAWAsIhyEWT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwFAMMkmoIhFvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5BQB91lWSIhoDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RjAjRrmVkzVxB8nTRZ6d66jT6vROZjbIXH+FPrkLpS6M0AAk+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsAvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5QxsCNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQADC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RCAlKbGdeHnMwEyRVIf18TQbxoWLC8dOUDbGQ9N7U6Q3G1A7f4r+MmP8s+8kVP4W86Z1nFYAx45je436DYPoVSiCBWQxsCT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RCA6gdlzSZ50+C0rWrE/Hmnp4Rpf20D1Rm72cubkzroL55A0mVk3ZxUDlO7OOE0FHEW2FcUtvhyOs2ENezRLQ7fa1tQxsC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RCAzlJ2/8xudUCUdiCHmbMXJe346/X2Vv9x3UA/aiUfzrgAj8g5PC/C3bw1AzTq/5843PWaFu9d7X6KOf0n7Qp0YmwAAA="
+    },
+    {
+      "case": "Spend of a Taproot output where the output key is a MuSig2 Aggregate Pubkey: with all partial signatures",
+      "hex": "70736274ff01005202000000015686dff400165f4e040a5855f658093472c9bcf8108b272a5d31f181f7b4ffb10100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f505000000002251200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d421160b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d405002680dd6e2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a822116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd65592221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9431b02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d44202529b19d7879ccc04c915487f5f1341bc6858b0bc74e5036c643d37b53a4371b503b7f8afe3263fcb3ef2454fe16f3a6759c5600c78e637b8dfa0d83e8552882056431b024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d44203a81d973499e74f82d2b5ab13f1e69e9e11a5fdb40f5466ef672e6e4ceba0be7903499593767150394eece384d051c45b615c52dbe1c8eb3610d7b344b43b7dad6d431b02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d442033949dbff31b9d50251d8821e66cc5c97b7e3afd7d95bfdc77500fda8947f3ae0023f20e4f0bf0b76f0d40cd3abfe7ce373d6685bbd77b5fa28e7f49fb429d189b0431c02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4200e57ca4ca0de1a3116d3fd6baf19d38572e47e8ff024e7efc39512751e54ed31431c024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4207254079cab166b0d50b54283fccb4aea15f776747a5d2a53d7da06239340dbcc431c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d42001245e8861e62ac5bfc0008418fd057ce6b03c17b1d6b5c6980413c5c4e358970000",
+      "base64": "cHNidP8BAFICAAAAAVaG3/QAFl9OBApYVfZYCTRyybz4EIsnKl0x8YH3tP+xAQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEgC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9QhFgtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUBQAmgN1uIRY0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAUAWAsIhyEWT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwFAMMkmoIhFvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5BQB91lWSIhoDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RjAjRrmVkzVxB8nTRZ6d66jT6vROZjbIXH+FPrkLpS6M0AAk+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsAvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5QxsCNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQADC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RCAlKbGdeHnMwEyRVIf18TQbxoWLC8dOUDbGQ9N7U6Q3G1A7f4r+MmP8s+8kVP4W86Z1nFYAx45je436DYPoVSiCBWQxsCT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RCA6gdlzSZ50+C0rWrE/Hmnp4Rpf20D1Rm72cubkzroL55A0mVk3ZxUDlO7OOE0FHEW2FcUtvhyOs2ENezRLQ7fa1tQxsC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RCAzlJ2/8xudUCUdiCHmbMXJe346/X2Vv9x3UA/aiUfzrgAj8g5PC/C3bw1AzTq/5843PWaFu9d7X6KOf0n7Qp0YmwQxwCNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQADC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9QgDlfKTKDeGjEW0/1rrxnThXLkfo/wJOfvw5USdR5U7TFDHAJPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLAMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1CByVAecqxZrDVC1QoP8y0rqFfd2dHpdKlPX2gYjk0DbzEMcAvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5AwtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUIAEkXohh5irFv8AAhBj9BXzmsDwXsda1xpgEE8XE41iXAAA="
+    },
+    {
+      "case": "Spend of a Taproot output where the internal key is a MuSig2 Aggregate Pubkey: with participant pubkeys only",
+      "hex": "70736274ff01005202000000015818a9cd644b369c306c7fb191ec014ff625e63c283f00f9d17a959fefa3e8f60000000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f505000000002251202967d2d020a9795da72b51be4f3fca25bb0e57e91c5b3e7a81abfa7232a3494221160b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d405002680dd6e2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a822116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd655920117200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f90000",
+      "base64": "cHNidP8BAFICAAAAAVgYqc1kSzacMGx/sZHsAU/2JeY8KD8A+dF6lZ/vo+j2AAAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEgKWfS0CCpeV2nK1G+Tz/KJbsOV+kcWz56gav6cjKjSUIhFgtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUBQAmgN1uIRY0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAUAWAsIhyEWT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwFAMMkmoIhFvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5BQB91lWSARcgC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9QiGgMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1GMCNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQACT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkAAA=="
+    },
+    {
+      "case": "Spend of a Taproot output where the internal key is a MuSig2 Aggregate Pubkey: with all pubnonces",
+      "hex": "70736274ff01005202000000015818a9cd644b369c306c7fb191ec014ff625e63c283f00f9d17a959fefa3e8f60000000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f505000000002251202967d2d020a9795da72b51be4f3fca25bb0e57e91c5b3e7a81abfa7232a3494221160b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d405002680dd6e2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a822116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd655920117200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9431b02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00032967d2d020a9795da72b51be4f3fca25bb0e57e91c5b3e7a81abfa7232a349424203cc17485ca01c2ebb0eba1c80b3eadaf5ee9cc14629fa4f1071d19820e2d07fcc02adfcad45a68cfb67759c9849cdd579639e4d1867272b991a0363d1ca76283efc431b024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c032967d2d020a9795da72b51be4f3fca25bb0e57e91c5b3e7a81abfa7232a349424202343bb8359c434f5f6a9d6b46f7573258fbfbb561bb5212cbf5850a82a9a02f7e0246e83221664427aca6d13c10809a2cb4b54dae9a7b2f5ab764213dd479a6a942431b02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9032967d2d020a9795da72b51be4f3fca25bb0e57e91c5b3e7a81abfa7232a3494242039dee4258b8dfe34460086ff1703209e478437c6ab0f598a2e6e809fd30a9ff3a03e06b4e04ec4de4f757c84d51acdaf6cb1ef4bccbfd8103703bc01a845dcf33650000",
+      "base64": "cHNidP8BAFICAAAAAVgYqc1kSzacMGx/sZHsAU/2JeY8KD8A+dF6lZ/vo+j2AAAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEgKWfS0CCpeV2nK1G+Tz/KJbsOV+kcWz56gav6cjKjSUIhFgtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUBQAmgN1uIRY0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAUAWAsIhyEWT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwFAMMkmoIhFvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5BQB91lWSARcgC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9QiGgMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1GMCNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQACT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvlDGwI0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAMpZ9LQIKl5XacrUb5PP8oluw5X6RxbPnqBq/pyMqNJQkIDzBdIXKAcLrsOuhyAs+ra9e6cwUYp+k8QcdGYIOLQf8wCrfytRaaM+2d1nJhJzdV5Y55NGGcnK5kaA2PRynYoPvxDGwJPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLAMpZ9LQIKl5XacrUb5PP8oluw5X6RxbPnqBq/pyMqNJQkICNDu4NZxDT19qnWtG91cyWPv7tWG7UhLL9YUKgqmgL34CRugyIWZEJ6ym0TwQgJostLVNrpp7L1q3ZCE91HmmqUJDGwL5MIoBkljDEEk0T4X4nVIptTHIRYNvmbCGAfETvOA2+QMpZ9LQIKl5XacrUb5PP8oluw5X6RxbPnqBq/pyMqNJQkIDne5CWLjf40RgCG/xcDIJ5HhDfGqw9Zii5ugJ/TCp/zoD4GtOBOxN5PdXyE1RrNr2yx70vMv9gQNwO8AahF3PM2UAAA=="
+    },
+    {
+      "case": "Spend of a Taproot output where the internal key is a MuSig2 Aggregate Pubkey: with all partial signatures",
+      "hex": "70736274ff01005202000000015818a9cd644b369c306c7fb191ec014ff625e63c283f00f9d17a959fefa3e8f60000000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f505000000002251202967d2d020a9795da72b51be4f3fca25bb0e57e91c5b3e7a81abfa7232a349420113402e89a7bdf9085c6438d15ddf1a86772a65222244276e9302ffdd9fa93b1c20ae58a6b11a6be98b151d8582daa84c10017c994d9235b13ec518a94782c67c40e221160b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d405002680dd6e2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a822116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd655920117200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9431b02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00032967d2d020a9795da72b51be4f3fca25bb0e57e91c5b3e7a81abfa7232a349424203cc17485ca01c2ebb0eba1c80b3eadaf5ee9cc14629fa4f1071d19820e2d07fcc02adfcad45a68cfb67759c9849cdd579639e4d1867272b991a0363d1ca76283efc431b024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c032967d2d020a9795da72b51be4f3fca25bb0e57e91c5b3e7a81abfa7232a349424202343bb8359c434f5f6a9d6b46f7573258fbfbb561bb5212cbf5850a82a9a02f7e0246e83221664427aca6d13c10809a2cb4b54dae9a7b2f5ab764213dd479a6a942431b02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9032967d2d020a9795da72b51be4f3fca25bb0e57e91c5b3e7a81abfa7232a3494242039dee4258b8dfe34460086ff1703209e478437c6ab0f598a2e6e809fd30a9ff3a03e06b4e04ec4de4f757c84d51acdaf6cb1ef4bccbfd8103703bc01a845dcf3365431c02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00032967d2d020a9795da72b51be4f3fca25bb0e57e91c5b3e7a81abfa7232a3494220109ad32155722014ddca21ae3b8d3c3a93a6d0ab5c7e19d0c693d565c47c1626431c024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c032967d2d020a9795da72b51be4f3fca25bb0e57e91c5b3e7a81abfa7232a349422035d5eecc404fa2a63644f30cf8af43fdbd829e5cd9c74707ca9b33a9134c756e431c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9032967d2d020a9795da72b51be4f3fca25bb0e57e91c5b3e7a81abfa7232a3494220b9c855defd44676ff3fc5342adbc90c2dec15624eab55b1ff29765315603db6e0000",
+      "base64": "cHNidP8BAFICAAAAAVgYqc1kSzacMGx/sZHsAU/2JeY8KD8A+dF6lZ/vo+j2AAAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEgKWfS0CCpeV2nK1G+Tz/KJbsOV+kcWz56gav6cjKjSUIBE0Auiae9+QhcZDjRXd8ahncqZSIiRCdukwL/3Z+pOxwgrlimsRpr6YsVHYWC2qhMEAF8mU2SNbE+xRipR4LGfEDiIRYLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1AUAJoDdbiEWNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQAFAFgLCIchFk+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsBQDDJJqCIRb5MIoBkljDEEk0T4X4nVIptTHIRYNvmbCGAfETvOA2+QUAfdZVkgEXIAtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUIhoDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RjAjRrmVkzVxB8nTRZ6d66jT6vROZjbIXH+FPrkLpS6M0AAk+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsAvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5QxsCNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQADKWfS0CCpeV2nK1G+Tz/KJbsOV+kcWz56gav6cjKjSUJCA8wXSFygHC67DrocgLPq2vXunMFGKfpPEHHRmCDi0H/MAq38rUWmjPtndZyYSc3VeWOeTRhnJyuZGgNj0cp2KD78QxsCT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwDKWfS0CCpeV2nK1G+Tz/KJbsOV+kcWz56gav6cjKjSUJCAjQ7uDWcQ09fap1rRvdXMlj7+7Vhu1ISy/WFCoKpoC9+AkboMiFmRCesptE8EICaLLS1Ta6aey9at2QhPdR5pqlCQxsC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkDKWfS0CCpeV2nK1G+Tz/KJbsOV+kcWz56gav6cjKjSUJCA53uQli43+NEYAhv8XAyCeR4Q3xqsPWYouboCf0wqf86A+BrTgTsTeT3V8hNUaza9sse9LzL/YEDcDvAGoRdzzNlQxwCNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQADKWfS0CCpeV2nK1G+Tz/KJbsOV+kcWz56gav6cjKjSUIgEJrTIVVyIBTdyiGuO408OpOm0KtcfhnQxpPVZcR8FiZDHAJPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLAMpZ9LQIKl5XacrUb5PP8oluw5X6RxbPnqBq/pyMqNJQiA11e7MQE+ipjZE8wz4r0P9vYKeXNnHRwfKmzOpE0x1bkMcAvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5Ayln0tAgqXldpytRvk8/yiW7DlfpHFs+eoGr+nIyo0lCILnIVd79RGdv8/xTQq28kMLewVYk6rVbH/KXZTFWA9tuAAA="
+    },
+    {
+      "case": "Spend of a Taproot output where a key in a script is a MuSig2 Aggregate Pubkey: with participant pubkeys only",
+      "hex": "70736274ff01005202000000019a8b4a50796b9600990f7fe11dfa00bc70efd296048afc86719af0fb1fa919370100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f5050000000022512056bdb481b4d67103f6d5dea8a9aafd3684a6a79b4a2e247799db8d4b1a86e1f82215c050929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac023200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4acc021160b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d42501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c2680dd6e2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd002501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c2501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2cc3249a82211650929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac005007c461e5d2116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f92501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c7dd6559201172050929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0011820b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f90000",
+      "base64": "cHNidP8BAFICAAAAAZqLSlB5a5YAmQ9/4R36ALxw79KWBIr8hnGa8PsfqRk3AQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEgVr20gbTWcQP21d6oqar9NoSmp5tKLiR3mduNSxqG4fgiFcBQkpt0waBJVLeLS2A16XpeB4paDyjsltVHv+6azoA6wCMgC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9SswCEWC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9QlAbEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosJoDdbiEWNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQAlAbEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosWAsIhyEWT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwlAbEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPoswySagiEWUJKbdMGgSVS3i0tgNel6XgeKWg8o7JbVR7/ums6AOsAFAHxGHl0hFvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5JQGxH+2qY6CVZQGnMIyTtWNzcedhPZuK3heD1J4mwGz6LH3WVZIBFyBQkpt0waBJVLeLS2A16XpeB4paDyjsltVHv+6azoA6wAEYILEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosIhoDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RjAjRrmVkzVxB8nTRZ6d66jT6vROZjbIXH+FPrkLpS6M0AAk+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsAvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5AAA="
+    },
+    {
+      "case": "Spend of a Taproot output where a key in a script is a MuSig2 Aggregate Pubkey: with all pubnonces",
+      "hex": "70736274ff01005202000000019a8b4a50796b9600990f7fe11dfa00bc70efd296048afc86719af0fb1fa919370100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f5050000000022512056bdb481b4d67103f6d5dea8a9aafd3684a6a79b4a2e247799db8d4b1a86e1f82215c050929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac023200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4acc021160b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d42501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c2680dd6e2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd002501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c2501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2cc3249a82211650929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac005007c461e5d2116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f92501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c7dd6559201172050929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0011820b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9631b02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c4202d99e7c8719b3ad08566b0cb9c7d5eda3127c9e8119185b7d584d939b173915f50240df22aab78332cf0f25329d103dc0d2060a03742e9448026e736bcf3db98f3c631b024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c4202e702a7075226a0d9313a77e6db10b8e742d4cffdc948a0edc9b856c13b412e5403386a0298f308fb3099155772e45b2aa8e770f435bedfe2041d1cc4d3d37538c6631b02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c4202b1d912d45d753ceed0954417ba982656d2aec53f8638bd6f297dae3b743d71b0032f424537d599d28f14d59fe0a11b82fea2aa226a2980ffdacad5fdab20f806830000",
+      "base64": "cHNidP8BAFICAAAAAZqLSlB5a5YAmQ9/4R36ALxw79KWBIr8hnGa8PsfqRk3AQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEgVr20gbTWcQP21d6oqar9NoSmp5tKLiR3mduNSxqG4fgiFcBQkpt0waBJVLeLS2A16XpeB4paDyjsltVHv+6azoA6wCMgC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9SswCEWC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9QlAbEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosJoDdbiEWNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQAlAbEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosWAsIhyEWT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwlAbEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPoswySagiEWUJKbdMGgSVS3i0tgNel6XgeKWg8o7JbVR7/ums6AOsAFAHxGHl0hFvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5JQGxH+2qY6CVZQGnMIyTtWNzcedhPZuK3heD1J4mwGz6LH3WVZIBFyBQkpt0waBJVLeLS2A16XpeB4paDyjsltVHv+6azoA6wAEYILEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosIhoDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RjAjRrmVkzVxB8nTRZ6d66jT6vROZjbIXH+FPrkLpS6M0AAk+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsAvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5YxsCNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQADC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9SxH+2qY6CVZQGnMIyTtWNzcedhPZuK3heD1J4mwGz6LEIC2Z58hxmzrQhWawy5x9XtoxJ8noEZGFt9WE2Tmxc5FfUCQN8iqreDMs8PJTKdED3A0gYKA3QulEgCbnNrzz25jzxjGwJPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLAMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1LEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosQgLnAqcHUiag2TE6d+bbELjnQtTP/clIoO3JuFbBO0EuVAM4agKY8wj7MJkVV3LkWyqo53D0Nb7f4gQdHMTT03U4xmMbAvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5AwtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+ixCArHZEtRddTzu0JVEF7qYJlbSrsU/hji9byl9rjt0PXGwAy9CRTfVmdKPFNWf4KEbgv6iqiJqKYD/2srV/asg+AaDAAA="
+    },
+    {
+      "case": "Spend of a Taproot output where a key in a script is a MuSig2 Aggregate Pubkey: with all partial signatures",
+      "hex": "70736274ff01005202000000019a8b4a50796b9600990f7fe11dfa00bc70efd296048afc86719af0fb1fa919370100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f5050000000022512056bdb481b4d67103f6d5dea8a9aafd3684a6a79b4a2e247799db8d4b1a86e1f841140b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c402667d52f6cc07fe06db31b1a5f7efe81903f9cbeef40fa64dafca01d2cb1d56403bc7504898e55872557d16d2ca79bc55fef10973841a33ec032d884758c9fe62215c050929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac023200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4acc021160b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d42501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c2680dd6e2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd002501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c2501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2cc3249a82211650929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac005007c461e5d2116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f92501b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c7dd6559201172050929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0011820b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9631b02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c4202d99e7c8719b3ad08566b0cb9c7d5eda3127c9e8119185b7d584d939b173915f50240df22aab78332cf0f25329d103dc0d2060a03742e9448026e736bcf3db98f3c631b024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c4202e702a7075226a0d9313a77e6db10b8e742d4cffdc948a0edc9b856c13b412e5403386a0298f308fb3099155772e45b2aa8e770f435bedfe2041d1cc4d3d37538c6631b02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c4202b1d912d45d753ceed0954417ba982656d2aec53f8638bd6f297dae3b743d71b0032f424537d599d28f14d59fe0a11b82fea2aa226a2980ffdacad5fdab20f80683631c02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c20ada78b70af8cffa4c50863aef515ac58a327cd58c55bad29a162e67d9c413322631c024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c201fa8b7e6741c21eb8d9b0f65269df9e423369fc390ad2e918420c57feb2a1b61631c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d4b11fedaa63a0956501a7308c93b5637371e7613d9b8ade1783d49e26c06cfa2c20366c31ad65e533f6d2b45e5910f3f587543f8061918167bf5a818b13be5792a40000",
+      "base64": "cHNidP8BAFICAAAAAZqLSlB5a5YAmQ9/4R36ALxw79KWBIr8hnGa8PsfqRk3AQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEgVr20gbTWcQP21d6oqar9NoSmp5tKLiR3mduNSxqG4fhBFAtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+ixAJmfVL2zAf+BtsxsaX37+gZA/nL7vQPpk2vygHSyx1WQDvHUEiY5VhyVX0W0sp5vFX+8QlzhBoz7AMtiEdYyf5iIVwFCSm3TBoElUt4tLYDXpel4HiloPKOyW1Ue/7prOgDrAIyALWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1KzAIRYLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1CUBsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+iwmgN1uIRY0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNACUBsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+ixYCwiHIRZPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLCUBsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+izDJJqCIRZQkpt0waBJVLeLS2A16XpeB4paDyjsltVHv+6azoA6wAUAfEYeXSEW+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvklAbEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosfdZVkgEXIFCSm3TBoElUt4tLYDXpel4HiloPKOyW1Ue/7prOgDrAARggsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+iwiGgMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1GMCNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQACT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvljGwI0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1LEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosQgLZnnyHGbOtCFZrDLnH1e2jEnyegRkYW31YTZObFzkV9QJA3yKqt4Myzw8lMp0QPcDSBgoDdC6USAJuc2vPPbmPPGMbAk+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsAwtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+ixCAucCpwdSJqDZMTp35tsQuOdC1M/9yUig7cm4VsE7QS5UAzhqApjzCPswmRVXcuRbKqjncPQ1vt/iBB0cxNPTdTjGYxsC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9SxH+2qY6CVZQGnMIyTtWNzcedhPZuK3heD1J4mwGz6LEICsdkS1F11PO7QlUQXupgmVtKuxT+GOL1vKX2uO3Q9cbADL0JFN9WZ0o8U1Z/goRuC/qKqImopgP/aytX9qyD4BoNjHAI0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1LEf7apjoJVlAacwjJO1Y3Nx52E9m4reF4PUnibAbPosIK2ni3CvjP+kxQhjrvUVrFijJ81YxVutKaFi5n2cQTMiYxwCT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9SxH+2qY6CVZQGnMIyTtWNzcedhPZuK3heD1J4mwGz6LCAfqLfmdBwh642bD2UmnfnkIzafw5CtLpGEIMV/6yobYWMcAvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5AwtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUsR/tqmOglWUBpzCMk7Vjc3HnYT2bit4Xg9SeJsBs+iwgNmwxrWXlM/bStF5ZEPP1h1Q/gGGRgWe/WoGLE75XkqQAAA=="
+    },
+    {
+      "case": "Spend of a Taproot output where the internal key is derived from a MuSig2 Aggregate Pubkey: with participant pubkeys only",
+      "hex": "70736274ff01005202000000012589e7767958ba154f9018cccf0dedea6147bb60cd1a194b6e3590a9965690d60100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f50500000000225120d0b226c6599f273874df8fe684ab6c3028081bee8a2cbed31a136f5865f6cfa42116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a8221168dd96ab858b259c518218c014a46eb4e6ac899e51c675ef774fbb68a8799ce2f0d002680dd6e01000000020000002116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd655920117208dd96ab858b259c518218c014a46eb4e6ac899e51c675ef774fbb68a8799ce2f221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f90000",
+      "base64": "cHNidP8BAFICAAAAASWJ53Z5WLoVT5AYzM8N7ephR7tgzRoZS241kKmWVpDWAQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEg0LImxlmfJzh034/mhKtsMCgIG+6KLL7TGhNvWGX2z6QhFjRrmVkzVxB8nTRZ6d66jT6vROZjbIXH+FPrkLpS6M0ABQBYCwiHIRZPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLAUAwySagiEWjdlquFiyWcUYIYwBSkbrTmrImeUcZ173dPu2ioeZzi8NACaA3W4BAAAAAgAAACEW+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkFAH3WVZIBFyCN2Wq4WLJZxRghjAFKRutOasiZ5RxnXvd0+7aKh5nOLyIaAwtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUYwI0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAJPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLAL5MIoBkljDEEk0T4X4nVIptTHIRYNvmbCGAfETvOA2+QAA"
+    },
+    {
+      "case": "Spend of a Taproot output where the internal key is derived from a MuSig2 Aggregate Pubkey: with all pubnonces",
+      "hex": "70736274ff01005202000000012589e7767958ba154f9018cccf0dedea6147bb60cd1a194b6e3590a9965690d60100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f50500000000225120d0b226c6599f273874df8fe684ab6c3028081bee8a2cbed31a136f5865f6cfa42116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a8221168dd96ab858b259c518218c014a46eb4e6ac899e51c675ef774fbb68a8799ce2f0d002680dd6e01000000020000002116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd655920117208dd96ab858b259c518218c014a46eb4e6ac899e51c675ef774fbb68a8799ce2f221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9431b02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd0002d0b226c6599f273874df8fe684ab6c3028081bee8a2cbed31a136f5865f6cfa442024eefc9fdd12be74746485c678b8268949cc9236e9fce82241395523af04262bf038c276e832aad4bfb9e90485162f574c8b2619df5bd19db8ffa2eb0059493bf1b431b024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02d0b226c6599f273874df8fe684ab6c3028081bee8a2cbed31a136f5865f6cfa44203a324a3f4221bfab2b6fa0786a7048f3345ce344f1458e151ba187b59aab498cb02a3638259ba4ccc46fe79d8d79a4d9e704ec0f7701b5e664d4d8733838af49196431b02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f902d0b226c6599f273874df8fe684ab6c3028081bee8a2cbed31a136f5865f6cfa44202c12eb4ef8760321c072a51d8fb65c34ee8b452a14818557f61df061285a5809103a08e41b262942c6e5932fd1fb5d99236897989f6e912dc21476d2771874114930000",
+      "base64": "cHNidP8BAFICAAAAASWJ53Z5WLoVT5AYzM8N7ephR7tgzRoZS241kKmWVpDWAQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEg0LImxlmfJzh034/mhKtsMCgIG+6KLL7TGhNvWGX2z6QhFjRrmVkzVxB8nTRZ6d66jT6vROZjbIXH+FPrkLpS6M0ABQBYCwiHIRZPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLAUAwySagiEWjdlquFiyWcUYIYwBSkbrTmrImeUcZ173dPu2ioeZzi8NACaA3W4BAAAAAgAAACEW+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkFAH3WVZIBFyCN2Wq4WLJZxRghjAFKRutOasiZ5RxnXvd0+7aKh5nOLyIaAwtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUYwI0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAJPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLAL5MIoBkljDEEk0T4X4nVIptTHIRYNvmbCGAfETvOA2+UMbAjRrmVkzVxB8nTRZ6d66jT6vROZjbIXH+FPrkLpS6M0AAtCyJsZZnyc4dN+P5oSrbDAoCBvuiiy+0xoTb1hl9s+kQgJO78n90SvnR0ZIXGeLgmiUnMkjbp/OgiQTlVI68EJivwOMJ26DKq1L+56QSFFi9XTIsmGd9b0Z24/6LrAFlJO/G0MbAk+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsAtCyJsZZnyc4dN+P5oSrbDAoCBvuiiy+0xoTb1hl9s+kQgOjJKP0Ihv6srb6B4anBI8zRc40TxRY4VG6GHtZqrSYywKjY4JZukzMRv552NeaTZ5wTsD3cBteZk1NhzODivSRlkMbAvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5AtCyJsZZnyc4dN+P5oSrbDAoCBvuiiy+0xoTb1hl9s+kQgLBLrTvh2AyHAcqUdj7ZcNO6LRSoUgYVX9h3wYShaWAkQOgjkGyYpQsblky/R+12ZI2iXmJ9ukS3CFHbSdxh0EUkwAA"
+    },
+    {
+      "case": "Spend of a Taproot output where the internal key is derived from a MuSig2 Aggregate Pubkey: with all partial signatures",
+      "hex": "70736274ff01005202000000012589e7767958ba154f9018cccf0dedea6147bb60cd1a194b6e3590a9965690d60100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd000000000001012b00e1f50500000000225120d0b226c6599f273874df8fe684ab6c3028081bee8a2cbed31a136f5865f6cfa40113409e39897ac2ffe27525dc460f8584fddd11fe9a97ce2e50c1489b8c1a4e92fcc07e48db63a1a4ccb9d297537d0c038838378bbf278de7aa1a128995d1625cc5cd2116346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721164fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a8221168dd96ab858b259c518218c014a46eb4e6ac899e51c675ef774fbb68a8799ce2f0d002680dd6e01000000020000002116f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd655920117208dd96ab858b259c518218c014a46eb4e6ac899e51c675ef774fbb68a8799ce2f221a030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9431b02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd0002d0b226c6599f273874df8fe684ab6c3028081bee8a2cbed31a136f5865f6cfa442024eefc9fdd12be74746485c678b8268949cc9236e9fce82241395523af04262bf038c276e832aad4bfb9e90485162f574c8b2619df5bd19db8ffa2eb0059493bf1b431b024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02d0b226c6599f273874df8fe684ab6c3028081bee8a2cbed31a136f5865f6cfa44203a324a3f4221bfab2b6fa0786a7048f3345ce344f1458e151ba187b59aab498cb02a3638259ba4ccc46fe79d8d79a4d9e704ec0f7701b5e664d4d8733838af49196431b02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f902d0b226c6599f273874df8fe684ab6c3028081bee8a2cbed31a136f5865f6cfa44202c12eb4ef8760321c072a51d8fb65c34ee8b452a14818557f61df061285a5809103a08e41b262942c6e5932fd1fb5d99236897989f6e912dc21476d277187411493431c02346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd0002d0b226c6599f273874df8fe684ab6c3028081bee8a2cbed31a136f5865f6cfa420657db286be14e80ece0dd84b4d17c4dc414c3e56bc8cef0827b061b4dd2c8f43431c024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02d0b226c6599f273874df8fe684ab6c3028081bee8a2cbed31a136f5865f6cfa420e78552fb4ce9b2d00e1ed0e2cb98e087199127477e8f1a1c681a00b9c4ce7098431c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f902d0b226c6599f273874df8fe684ab6c3028081bee8a2cbed31a136f5865f6cfa420cbcc95786a1c674d48d8ac52e322dd7c6eabac3bfc4be79b750de28df82e2f730000",
+      "base64": "cHNidP8BAFICAAAAASWJ53Z5WLoVT5AYzM8N7ephR7tgzRoZS241kKmWVpDWAQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAAEBKwDh9QUAAAAAIlEg0LImxlmfJzh034/mhKtsMCgIG+6KLL7TGhNvWGX2z6QBE0CeOYl6wv/idSXcRg+FhP3dEf6al84uUMFIm4waTpL8wH5I22OhpMy50pdTfQwDiDg3i78njeeqGhKJldFiXMXNIRY0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAUAWAsIhyEWT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwFAMMkmoIhFo3ZarhYslnFGCGMAUpG605qyJnlHGde93T7toqHmc4vDQAmgN1uAQAAAAIAAAAhFvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5BQB91lWSARcgjdlquFiyWcUYIYwBSkbrTmrImeUcZ173dPu2ioeZzi8iGgMLWOM3qk04UqjCk4fEJAjYz746YTpeOX4KnwGl+3EH1GMCNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQACT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvlDGwI0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAALQsibGWZ8nOHTfj+aEq2wwKAgb7oosvtMaE29YZfbPpEICTu/J/dEr50dGSFxni4JolJzJI26fzoIkE5VSOvBCYr8DjCdugyqtS/uekEhRYvV0yLJhnfW9GduP+i6wBZSTvxtDGwJPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLALQsibGWZ8nOHTfj+aEq2wwKAgb7oosvtMaE29YZfbPpEIDoySj9CIb+rK2+geGpwSPM0XONE8UWOFRuhh7Waq0mMsCo2OCWbpMzEb+edjXmk2ecE7A93AbXmZNTYczg4r0kZZDGwL5MIoBkljDEEk0T4X4nVIptTHIRYNvmbCGAfETvOA2+QLQsibGWZ8nOHTfj+aEq2wwKAgb7oosvtMaE29YZfbPpEICwS6074dgMhwHKlHY+2XDTui0UqFIGFV/Yd8GEoWlgJEDoI5BsmKULG5ZMv0ftdmSNol5ifbpEtwhR20ncYdBFJNDHAI0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAALQsibGWZ8nOHTfj+aEq2wwKAgb7oosvtMaE29YZfbPpCBlfbKGvhToDs4N2EtNF8TcQUw+VryM7wgnsGG03SyPQ0McAk+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsAtCyJsZZnyc4dN+P5oSrbDAoCBvuiiy+0xoTb1hl9s+kIOeFUvtM6bLQDh7Q4suY4IcZkSdHfo8aHGgaALnEznCYQxwC+TCKAZJYwxBJNE+F+J1SKbUxyEWDb5mwhgHxE7zgNvkC0LImxlmfJzh034/mhKtsMCgIG+6KLL7TGhNvWGX2z6Qgy8yVeGocZ01I2KxS4yLdfG6rrDv8S+ebdQ3ijfguL3MAAA=="
+    },
+    {
+      "case": "Receiving a Taproot output where the internal key is a MuSig2 Aggregate Pubkey",
+      "hex": "70736274ff01007d02000000012589e7767958ba154f9018cccf0dedea6147bb60cd1a194b6e3590a9965690d60000000000fdffffff0280969800000000002251202967d2d020a9795da72b51be4f3fca25bb0e57e91c5b3e7a81abfa7232a349420fc0927c00000000160014349c5d330278c3002a64f597d2b01aa3dc1bd903000000000001007d02000000019a8b4a50796b9600990f7fe11dfa00bc70efd296048afc86719af0fb1fa919370000000000fdffffff02895c2b7d00000000160014cfd98ba1027ea4ed4bd2ae1b348b6156a015037500e1f50500000000225120d0b226c6599f273874df8fe684ab6c3028081bee8a2cbed31a136f5865f6cfa4e100000001011f895c2b7d00000000160014cfd98ba1027ea4ed4bd2ae1b348b6156a0150375220602a66650f08bffa4f089eb22edcdbe7616645ff6cd180a36484d4bc81054595b7b18bfff44a3540000800100008000000080010000008a020000000105200b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d421070b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d405002680dd6e2107346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721074fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a822107f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd655922208030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f900220203be4ae53d37cc075f40b30d6da4729d40adeeb983533af1616192bc76d5b2612a18bfff44a3540000800100008000000080010000008d02000000",
+      "base64": "cHNidP8BAH0CAAAAASWJ53Z5WLoVT5AYzM8N7ephR7tgzRoZS241kKmWVpDWAAAAAAD9////AoCWmAAAAAAAIlEgKWfS0CCpeV2nK1G+Tz/KJbsOV+kcWz56gav6cjKjSUIPwJJ8AAAAABYAFDScXTMCeMMAKmT1l9KwGqPcG9kDAAAAAAABAH0CAAAAAZqLSlB5a5YAmQ9/4R36ALxw79KWBIr8hnGa8PsfqRk3AAAAAAD9////AolcK30AAAAAFgAUz9mLoQJ+pO1L0q4bNIthVqAVA3UA4fUFAAAAACJRINCyJsZZnyc4dN+P5oSrbDAoCBvuiiy+0xoTb1hl9s+k4QAAAAEBH4lcK30AAAAAFgAUz9mLoQJ+pO1L0q4bNIthVqAVA3UiBgKmZlDwi/+k8InrIu3NvnYWZF/2zRgKNkhNS8gQVFlbexi//0SjVAAAgAEAAIAAAACAAQAAAIoCAAAAAQUgC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9QhBwtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUBQAmgN1uIQc0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAUAWAsIhyEHT6/WX4FpGG/Cv9siM8d+Yw0QvigKJMcWXAmidhF3XCwFAMMkmoIhB/kwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5BQB91lWSIggDC1jjN6pNOFKowpOHxCQI2M++OmE6Xjl+Cp8BpftxB9RjAjRrmVkzVxB8nTRZ6d66jT6vROZjbIXH+FPrkLpS6M0AAk+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsAvkwigGSWMMQSTRPhfidUim1MchFg2+ZsIYB8RO84Db5ACICA75K5T03zAdfQLMNbaRynUCt7rmDUzrxYWGSvHbVsmEqGL//RKNUAACAAQAAgAAAAIABAAAAjQIAAAA="
+    },
+    {
+      "case": "Receiving a Taproot output where the internal key is derived from a MuSig2 Aggregate Pubkey",
+      "hex": "70736274ff01007d0200000001f835a5ec8e4008f96f17407e13f0c34912c39d27620800fae02baf86b8a78e760000000000fdffffff028096980000000000225120d0b226c6599f273874df8fe684ab6c3028081bee8a2cbed31a136f5865f6cfa49e405d05000000001600149f94ac2db46420b95dc0db1cc8f4bec0bb9234d8000000000001005202000000015686dff400165f4e040a5855f658093472c9bcf8108b272a5d31f181f7b4ffb10100000000fdffffff0118ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd0000000001011f18ddf50500000000160014c9123e06e8d7f0966c5d1cd0f933002d4eb757cd220603293c8d8dc47b712d7c13a5d0536b7f2e3193267e60f7e66e563939dbe507479c18bfff44a35400008001000080000000800000000097010000000105208dd96ab858b259c518218c014a46eb4e6ac899e51c675ef774fbb68a8799ce2f2107346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd000500580b088721074fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c0500c3249a8221078dd96ab858b259c518218c014a46eb4e6ac899e51c675ef774fbb68a8799ce2f0d002680dd6e01000000020000002107f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f905007dd655922208030b58e337aa4d3852a8c29387c42408d8cfbe3a613a5e397e0a9f01a5fb7107d46302346b99593357107c9d3459e9deba8d3eaf44e6636c85c7f853eb90ba52e8cd00024fafd65f8169186fc2bfdb2233c77e630d10be280a24c7165c09a27611775c2c02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f900220202ce69de967622b1c82eb0a0f80ceb0573a0f768b02fdb047b13c171e79174fcce18bfff44a3540000800100008000000080010000008e02000000",
+      "base64": "cHNidP8BAH0CAAAAAfg1peyOQAj5bxdAfhPww0kSw50nYggA+uArr4a4p452AAAAAAD9////AoCWmAAAAAAAIlEg0LImxlmfJzh034/mhKtsMCgIG+6KLL7TGhNvWGX2z6SeQF0FAAAAABYAFJ+UrC20ZCC5XcDbHMj0vsC7kjTYAAAAAAABAFICAAAAAVaG3/QAFl9OBApYVfZYCTRyybz4EIsnKl0x8YH3tP+xAQAAAAD9////ARjd9QUAAAAAFgAUyRI+BujX8JZsXRzQ+TMALU63V80AAAAAAQEfGN31BQAAAAAWABTJEj4G6NfwlmxdHND5MwAtTrdXzSIGAyk8jY3Ee3EtfBOl0FNrfy4xkyZ+YPfmblY5OdvlB0ecGL//RKNUAACAAQAAgAAAAIAAAAAAlwEAAAABBSCN2Wq4WLJZxRghjAFKRutOasiZ5RxnXvd0+7aKh5nOLyEHNGuZWTNXEHydNFnp3rqNPq9E5mNshcf4U+uQulLozQAFAFgLCIchB0+v1l+BaRhvwr/bIjPHfmMNEL4oCiTHFlwJonYRd1wsBQDDJJqCIQeN2Wq4WLJZxRghjAFKRutOasiZ5RxnXvd0+7aKh5nOLw0AJoDdbgEAAAACAAAAIQf5MIoBkljDEEk0T4X4nVIptTHIRYNvmbCGAfETvOA2+QUAfdZVkiIIAwtY4zeqTThSqMKTh8QkCNjPvjphOl45fgqfAaX7cQfUYwI0a5lZM1cQfJ00Weneuo0+r0TmY2yFx/hT65C6UujNAAJPr9ZfgWkYb8K/2yIzx35jDRC+KAokxxZcCaJ2EXdcLAL5MIoBkljDEEk0T4X4nVIptTHIRYNvmbCGAfETvOA2+QAiAgLOad6WdiKxyC6woPgM6wVzoPdosC/bBHsTwXHnkXT8zhi//0SjVAAAgAEAAIAAAACAAQAAAI4CAAAA"
+    }
+  ]
+}
diff --git a/haskoin-core.cabal b/haskoin-core.cabal
--- a/haskoin-core.cabal
+++ b/haskoin-core.cabal
@@ -5,7 +5,7 @@
 -- see: https://github.com/sol/hpack
 
 name:           haskoin-core
-version:        2.0.1
+version:        3.0.0
 synopsis:       Bitcoin & Bitcoin Cash library for Haskell
 description:    Please see the README on GitHub at <https://github.com/jprupp/haskoin-core#readme>
 category:       Bitcoin, Finance, Network
@@ -20,6 +20,8 @@
     data/block_100000.hex
     data/bip341.json
     data/bip39_vectors.json
+    data/cashtokens_prefix_invalid.json
+    data/cashtokens_prefix_valid.json
     data/complex_psbt.json
     data/core_signed_txs.json
     data/forkid_script_tests.json
@@ -29,6 +31,7 @@
     data/psbt_bip174.json
     data/psbt_bip370.json
     data/psbt_bip371.json
+    data/psbt_bip373.json
     data/psbt_complex_core32.json
     data/psbt_core32.json
     data/rfc6979cash.json
@@ -90,7 +93,24 @@
       Haskoin.Network.Constants
       Haskoin.Network.Data
       Haskoin.Network.Message
+      Haskoin.Network.Protocol
+      Haskoin.Network.Protocol.BitcoinCashNode
+      Haskoin.Network.Protocol.BitcoinCashNode.Blocks
+      Haskoin.Network.Protocol.BitcoinCashNode.Constants
+      Haskoin.Network.Protocol.BitcoinCashNode.Handshake
+      Haskoin.Network.Protocol.BitcoinCashNode.Options
+      Haskoin.Network.Protocol.BitcoinCashNode.Relay
+      Haskoin.Network.Protocol.BitcoinCashNode.State
+      Haskoin.Network.Protocol.BitcoinCore
+      Haskoin.Network.Protocol.BitcoinCore.Blocks
+      Haskoin.Network.Protocol.BitcoinCore.Constants
+      Haskoin.Network.Protocol.BitcoinCore.Handshake
+      Haskoin.Network.Protocol.BitcoinCore.Machine
+      Haskoin.Network.Protocol.BitcoinCore.Relay
+      Haskoin.Network.Protocol.BitcoinCore.State
+      Haskoin.Network.Protocol.Types
       Haskoin.Script
+      Haskoin.Script.CashToken
       Haskoin.Script.Common
       Haskoin.Script.SigHash
       Haskoin.Script.Standard
@@ -99,6 +119,7 @@
       Haskoin.Transaction.Builder.Sign
       Haskoin.Transaction.Common
       Haskoin.Transaction.Genesis
+      Haskoin.Transaction.Judge
       Haskoin.Transaction.Psbt
       Haskoin.Transaction.Segwit
       Haskoin.Transaction.Taproot
@@ -111,6 +132,7 @@
       Haskoin.Util.Arbitrary.Message
       Haskoin.Util.Arbitrary.Network
       Haskoin.Util.Arbitrary.Script
+      Haskoin.Util.Arbitrary.Spelling
       Haskoin.Util.Arbitrary.Transaction
       Haskoin.Util.Arbitrary.Util
       Haskoin.Util.Direct
@@ -161,6 +183,7 @@
   type: exitcode-stdio-1.0
   main-is: Spec.hs
   other-modules:
+      BitcoinCore
       Haskoin.Address.Bech32Spec
       Haskoin.Address.CashAddrSpec
       Haskoin.AddressSpec
@@ -171,12 +194,17 @@
       Haskoin.Crypto.Keys.Slip39Spec
       Haskoin.Crypto.KeysSpec
       Haskoin.Crypto.SignatureSpec
+      Haskoin.Network.Protocol.BitcoinCashNodeSpec
+      Haskoin.Network.Protocol.BitcoinCoreSpec
       Haskoin.NetworkSpec
+      Haskoin.Script.CashTokenSpec
       Haskoin.ScriptSpec
+      Haskoin.Transaction.JudgeSpec
       Haskoin.Transaction.PsbtSpec
       Haskoin.Transaction.TaprootSpec
       Haskoin.Transaction.VerdictSpec
       Haskoin.TransactionSpec
+      Haskoin.Util.Arbitrary.UtilSpec
       Haskoin.Util.DirectSpec
       Haskoin.UtilSpec
       Paths_haskoin_core
@@ -202,12 +230,13 @@
     , entropy >=0.4.1.5
     , hashable >=1.3.0.0
     , haskoin-core
-    , hspec >=2.7.1
+    , hspec >=2.10.0
     , lens >=4.18.1
     , lens-aeson >=1.1
     , mtl >=2.2.2
     , murmur3 >=1.0.3
     , network >=3.1.1.1
+    , podman-test >=0.1
     , ram >=0.22.0
     , safe >=0.3.18
     , scientific >=0.3.6.2
diff --git a/src/Haskoin/Address.hs b/src/Haskoin/Address.hs
--- a/src/Haskoin/Address.hs
+++ b/src/Haskoin/Address.hs
@@ -45,6 +45,8 @@
     witnessScriptAddress,
     script32Address,
     cashAddress,
+    tokenAwareAddress,
+    plainAddress,
     addressHash160,
     addressHash256,
     addressVersion,
@@ -108,6 +110,7 @@
 import Haskoin.Crypto.Hash
 import Haskoin.Crypto.Keys.Common
 import Haskoin.Network.Data
+import Haskoin.Script.CashToken (hasTokenPrefix, splitTokenData)
 import Haskoin.Script.Common
 import Haskoin.Script.Standard
 import Haskoin.Util
@@ -431,6 +434,50 @@
     (1, 32) -> Script32Address <$> decodeHash b
     _ -> return $ OtherCashAddress v b
 
+-- | The token-aware form of an address of Bitcoin Cash: CashAddr type 2 for
+-- a P2PKH address, type 3 for a P2SH or P2SH32 address. A token-aware
+-- address is its own token-aware form. 'Nothing' for any other address,
+-- which has no such form.
+--
+-- CashTokens added these types so that a wallet can tell a sender that it
+-- knows about tokens: software that does not would burn tokens sent to it,
+-- by spending the coins without carrying the tokens over. Both forms lock
+-- coins with the same script, so the token-aware form changes nothing on the
+-- chain, only what a sender is told it may send.
+--
+-- Use it to show the address of an output that holds tokens, or to give a
+-- token wallet an address to receive at. 'scriptToAddressBS' returns the
+-- plain form for every output, with or without tokens; see there why.
+--
+-- Bitcoin has no token-aware addresses: 'addrToText' of the result is
+-- 'Nothing' on a Bitcoin network, and on Bitcoin Cash it starts with @z@
+-- for type 2 and @r@ for type 3 with a 32-byte hash.
+tokenAwareAddress :: Address -> Maybe Address
+tokenAwareAddress = \case
+  PubKeyAddress h -> cashAddress tokenPubKeyType (hashBytes h)
+  ScriptAddress h -> cashAddress tokenScriptType (hashBytes h)
+  Script32Address h -> cashAddress tokenScriptType (hashBytes h)
+  a@(OtherCashAddress v b)
+    | isJust (cashAddressOutput v b) -> Just a
+  _ -> Nothing
+
+-- | The plain form of a token-aware address: the inverse of
+-- 'tokenAwareAddress'. Every other address is returned as it is.
+--
+-- Two addresses that lock coins with the same script are different values,
+-- so @plainAddress@ is how to put a token-aware address that a user gives
+-- next to the addresses that 'scriptToAddressBS' returns, for instance to
+-- look up its balance.
+plainAddress :: Address -> Address
+plainAddress = \case
+  a@(OtherCashAddress v b)
+    | v == tokenPubKeyType && len == 20 -> maybe a PubKeyAddress (decodeHash b)
+    | v == tokenScriptType && len == 20 -> maybe a ScriptAddress (decodeHash b)
+    | v == tokenScriptType && len == 32 -> maybe a Script32Address (decodeHash b)
+    where
+      len = B.length b
+  a -> a
+
 -- | Read a hash from bytes of the right length.
 decodeHash :: (Serial a) => ByteString -> Maybe a
 decodeHash = eitherToMaybe . runGetS deserialize
@@ -726,9 +773,19 @@
 
 -- | Decode an output script into the 'Address' it has on a network, if it
 -- has one there. See 'outputAddress'.
+--
+-- On the Bitcoin Cash networks, a script that starts with the token prefix
+-- byte 0xef, which parses as @OP_INVALIDOPCODE 0xef@, is the script field of
+-- an output that holds tokens. It is handled as 'scriptToAddressBS' handles
+-- it. Most such fields do not parse as a t'Script' at all: give their bytes to
+-- 'scriptToAddressBS'.
 scriptToAddress :: Network -> Script -> Either String Address
-scriptToAddress net =
-  maybeToEither e . outputAddress net <=< decodeOutput
+scriptToAddress net script
+  | isJust net.cashAddrPrefix,
+    OP_INVALIDOPCODE 0xef : _ <- script.ops =
+      scriptToAddressBS net (encodeSerial script)
+  | otherwise =
+      maybeToEither e . outputAddress net =<< decodeOutput script
   where
     e = "Could not decode address"
 
@@ -754,8 +811,46 @@
 -- parsed every script, and a Taproot output or a data carrier takes about a
 -- fifth. Versions 1.6.3 and 1.6.4 were as fast for the four kinds, and
 -- nearly twice as slow as 1.6.0 for every script they parsed.
+--
+-- On the Bitcoin Cash networks, the script field of an output that holds
+-- tokens (CashTokens) starts with a token prefix, which
+-- 'Haskoin.Script.CashToken.splitTokenData' takes off. The address is the
+-- one of the locking script after it, and is in its plain form: a P2PKH,
+-- P2SH or P2SH32 address of CashAddr type 0 or 1, as for an output without
+-- tokens. A field with a prefix that is not valid has no address, and gives
+-- the error of the prefix in a 'Left'. On Bitcoin the byte 0xef is no
+-- prefix, and such a script has no address.
+--
+-- The plain form is the one an output has whatever it holds. Bitcoin Cash
+-- Node shows the same, with the tokens apart. It keeps all the coins of a
+-- key or a script under one address, as an index of addresses should: a
+-- wallet receives coins with and without tokens at the same script, and the
+-- token-aware form would split its history and its balance in two. Read the
+-- tokens with 'splitTokenData', and show the token-aware form with
+-- 'tokenAwareAddress' where a user wants it.
+--
+-- So nothing in the address says that an output holds tokens. A program that
+-- serves the unspent outputs of an address must also give the tokens of each
+-- one, from 'splitTokenData'. A wallet that spent such an output as a plain
+-- coin would burn its tokens, or sign a digest without the token prefix and
+-- see the transaction refused: see 'Haskoin.Script.SigHash.txSigHashCashToken'.
+-- This is the mistake that token-aware addresses exist to prevent, and the
+-- server has to prevent it by other means.
+--
+-- Before version 3.0.0 these outputs had no address. An index of addresses
+-- built with an older version left them out, and must be built again, or have
+-- them added, before it runs with this one: otherwise it takes away from a
+-- balance an output that it never added when that output is spent.
 scriptToAddressBS :: Network -> ByteString -> Either String Address
 scriptToAddressBS net bytes
+  | isJust net.cashAddrPrefix,
+    hasTokenPrefix bytes =
+      scriptToAddressBS' net . snd =<< splitTokenData bytes
+  | otherwise = scriptToAddressBS' net bytes
+
+-- | 'scriptToAddressBS' for a script without a token prefix.
+scriptToAddressBS' :: Network -> ByteString -> Either String Address
+scriptToAddressBS' net bytes
   | Just a <- standard = Right a
   | otherwise = maybeToEither e . outputAddress net =<< decodeSerial bytes
   where
diff --git a/src/Haskoin/Address/Bech32.hs b/src/Haskoin/Address/Bech32.hs
--- a/src/Haskoin/Address/Bech32.hs
+++ b/src/Haskoin/Address/Bech32.hs
@@ -186,17 +186,26 @@
 -- | Encode string of five-bit words into 'Bech32' using a provided
 -- human-readable part. Can fail if 'HRP' is invalid or result would be longer
 -- than 90 characters.
+--
+-- The length is checked before any other work on the words, and a list that
+-- is too long is not read to its end: the cost of a refusal does not grow
+-- with the list.
 bech32Encode :: Bech32Encoding -> HRP -> [Word5] -> Maybe Bech32
 bech32Encode enc hrp dat = do
   guard $ checkHRP hrp
+  -- One word more than the room is enough to know that the list is too long
+  guard $ length (take (room + 1) dat) <= room
   -- The constructor of 'Word5' can hold any byte, and only 0 to 31 have a
   -- character.
   guard $ all (\(UnsafeWord5 w) -> w <= 31) dat
   let dat' = dat ++ bech32CreateChecksum enc (T.toLower hrp) dat
       rest = map (\(UnsafeWord5 w) -> BU.unsafeIndex charsetBytes (fromIntegral w)) dat'
-      result = T.concat [T.toLower hrp, T.pack "1", E.decodeLatin1 (B.pack rest)]
-  guard $ T.length result <= maxBech32Length
-  return result
+  return $ T.concat [T.toLower hrp, T.pack "1", E.decodeLatin1 (B.pack rest)]
+  where
+    -- The words that fit between the human-readable part with its separator
+    -- and the checksum. The part is ASCII when this is read, so its lowercase
+    -- form has as many characters.
+    room = maxBech32Length - T.length hrp - 1 - checksumLength
 
 -- | BIP-173 allows only US-ASCII characters in the range 33 to 126 anywhere
 -- in a 'Bech32' string.
diff --git a/src/Haskoin/Address/CashAddr.hs b/src/Haskoin/Address/CashAddr.hs
--- a/src/Haskoin/Address/CashAddr.hs
+++ b/src/Haskoin/Address/CashAddr.hs
@@ -137,8 +137,21 @@
 -- version byte before the 'ByteString' that encodes type and length. The
 -- string must be the canonical encoding of its payload: padding bits must be
 -- zero and there must be fewer than five of them.
+--
+-- A string with more than 'maxCashAddrDataLength' characters after its colon
+-- is refused before any other work, in a time that does not depend on its
+-- length. No such string is valid, since the largest hash that a version
+-- byte can name is 64 bytes, so the bound changes no answer. It is there for
+-- a string from outside: the conversion of the data to bytes holds hundreds
+-- of bytes for each character, which a megabyte of text would turn into
+-- hundreds of megabytes, only to be refused. The prefix has no limit, as in
+-- the specification and in Bitcoin Cash Node, and it is never converted: the
+-- time and the memory grow in proportion to its length, by about a dozen
+-- bytes for each character. A caller that knows its prefixes can compare the
+-- whole length first, as 'cashAddrDecode' does.
 cash32decodeType :: Cash32 -> Maybe (CashPrefix, CashVersion, ByteString)
 cash32decodeType ca = do
+  guard (dataPartFits ca)
   (dpfx, groups) <- cash32decodeGroups ca
   bs <- toBase256 groups
   (vb, pay) <- B.uncons bs
@@ -146,6 +159,14 @@
   guard (B.length pay == len)
   return (dpfx, ver, pay)
 
+-- | Whether the part of a 'Cash32' string after its colon has at most
+-- 'maxCashAddrDataLength' characters: whether the colon is among the last
+-- 'maxCashAddrDataLength' + 1 characters. Only those are read, whatever the
+-- length of the string. A string without a colon has no prefix, so it is no
+-- 'Cash32' string, and the answer is 'False' for it too.
+dataPartFits :: Cash32 -> Bool
+dataPartFits = T.any (== ':') . T.takeEnd (maxCashAddrDataLength + 1)
+
 -- | Mid-Level: encode 'CashAddr' string containing arbitrary prefix and
 -- 'CashVersion'. Length must be among those allowed by the standard.
 cash32encodeType :: CashPrefix -> CashVersion -> ByteString -> Maybe Cash32
@@ -164,7 +185,9 @@
 -- The prefix must be one or more letters, and the string has one colon, as
 -- in the decoder of Bitcoin Cash Node. There is no limit on the length here,
 -- since the data is arbitrary. The time and the memory grow in proportion to
--- the length.
+-- the length, by hundreds of bytes for each character of data: limit the
+-- length of a string from outside. 'cash32decodeType' has a limit, because
+-- an address has a longest form.
 cash32decode :: Cash32 -> Maybe (CashPrefix, ByteString)
 cash32decode text = do
   (pfx, groups) <- cash32decodeGroups text
diff --git a/src/Haskoin/Block/Headers.hs b/src/Haskoin/Block/Headers.hs
--- a/src/Haskoin/Block/Headers.hs
+++ b/src/Haskoin/Block/Headers.hs
@@ -361,6 +361,11 @@
 
 -- | Validate and connect single block header to the block chain. Return 'Left'
 -- if fails to be validated.
+--
+-- Prefer 'connectBlocks' for the headers of a @headers@ message. On a Bitcoin
+-- Cash network without 'asertAnchorBlock', such as regtest, each call searches
+-- the chain for the aserti3-2d anchor again; 'connectBlocks' does it once for
+-- the whole run.
 connectBlock ::
   (BlockHeaders m) =>
   Network ->
@@ -382,7 +387,9 @@
 -- when each one searched again. The anchor of a block is also the anchor of
 -- all of its descendants, since the median time past never decreases along a
 -- chain, so one search serves a whole run of headers. The cache holds the
--- hash of the block that the anchor was found for, and the anchor.
+-- hash of the block that the anchor was found for, and the anchor. On a
+-- network that knows its anchor ('asertAnchorBlock') the search is already
+-- short, and the cache saves only the walk to that block.
 type AnchorCache = Maybe (BlockHash, BlockNode)
 
 -- | The anchor for the chain that ends at the given block, from the cache when
@@ -843,16 +850,37 @@
 -- difficulty came from the previous algorithm. Returns 'Nothing' when the
 -- block's own median time past is still below the activation time, in which
 -- case the previous algorithm applies to its children.
+--
+-- Where the network knows its anchor ('asertAnchorBlock'), and the chain holds
+-- that block at that height, the anchor is that block, found with one walk
+-- down the skip pointers. Otherwise it is found with a binary search over the
+-- heights, with a median time past at each step: about 1,500 reads of the
+-- store at height 100,000, against about 80 for the walk. The constant is checked against
+-- the chain rather than trusted, so a fork from below the anchor still gets
+-- the anchor of its own chain.
 asertAnchor :: (BlockHeaders m) => Network -> BlockNode -> m (Maybe BlockNode)
 asertAnchor net tip =
   case net.asertActivationTime of
     Nothing -> return Nothing
-    Just activation -> do
-      tipMtp <- mtp tip
-      if tipMtp < activation
-        then return Nothing
-        else Just <$> search activation 0 tip.height
+    Just activation ->
+      known >>= \case
+        Just anchor -> return (Just anchor)
+        Nothing -> do
+          tipMtp <- mtp tip
+          if tipMtp < activation
+            then return Nothing
+            else Just <$> search activation 0 tip.height
   where
+    -- The constant anchor, when the chain of the tip holds it. Every block
+    -- above the anchor has a median time past at least as late, so the
+    -- activation time is reached.
+    known = case net.asertAnchorBlock of
+      Just (h, hash)
+        | h <= tip.height ->
+            getAncestor h tip >>= \case
+              Just a | headerHash a.header == hash -> return (Just a)
+              _ -> return Nothing
+      _ -> return Nothing
     -- The median time past never decreases along a chain, so a binary search
     -- over the heights finds the first block that reaches the activation
     -- time. The upper bound always satisfies it.
diff --git a/src/Haskoin/Crypto/Keys/Common.hs b/src/Haskoin/Crypto/Keys/Common.hs
--- a/src/Haskoin/Crypto/Keys/Common.hs
+++ b/src/Haskoin/Crypto/Keys/Common.hs
@@ -128,9 +128,14 @@
 -- this function, or 'decodeSerial', for those. 'deserialize' reads a key from the
 -- start of a longer stream and leaves the rest.
 --
--- A hybrid key, 65 bytes starting with 0x06 or 0x07, is refused. Consensus
--- takes that form, but the relay rules of Bitcoin Core do not, and no wallet
--- makes one.
+-- A hybrid key, 65 bytes starting with 0x06 or 0x07, is refused. On Bitcoin,
+-- consensus takes that form, but the relay rules of Bitcoin Core do not, and
+-- no wallet makes one. On Bitcoin Cash consensus refuses it too: a signature
+-- check of a key that is not compressed or uncompressed fails in every block
+-- (@SCRIPT_VERIFY_STRICTENC@, one of the @MANDATORY_SCRIPT_VERIFY_FLAGS@ of
+-- Bitcoin Cash Node). So this function reads the keys that a block of
+-- Bitcoin Cash can hold, and 'importPubKey', which takes a hybrid key, reads
+-- more.
 decodePubKey :: ByteString -> Either String PublicKey
 decodePubKey = runGetS $ do
   k <- deserialize
diff --git a/src/Haskoin/Crypto/Keys/Extended.hs b/src/Haskoin/Crypto/Keys/Extended.hs
--- a/src/Haskoin/Crypto/Keys/Extended.hs
+++ b/src/Haskoin/Crypto/Keys/Extended.hs
@@ -785,21 +785,29 @@
   Deriv == Deriv = True
   _ == _ = False
 
+-- | A shorter path sorts first. Two paths of the same length sort by the
+-- first step that differs, counted from the key down: a soft step before a
+-- hardened one, then by index. That is the order of the index lists of
+-- 'pathToList', where the hard bit is set, with the shorter list first.
+--
+-- A path holds its last step outermost, so the comparison walks both paths
+-- once from their last step and remembers the difference nearest the key. It
+-- takes time by the length of the paths, also for paths that come from
+-- outside and are of any length.
 instance Ord (DerivPathI t) where
-  -- Same hardness on each side
-  (nextA :| iA) `compare` (nextB :| iB) =
-    if nextA == nextB then iA `compare` iB else nextA `compare` nextB
-  (nextA :/ iA) `compare` (nextB :/ iB) =
-    if nextA == nextB then iA `compare` iB else nextA `compare` nextB
-  -- Different hardness: a soft path sorts before a hard one, as it does when
-  -- comparing the index lists of 'pathToList', where the hard bit is set.
-  (nextA :/ _iA) `compare` (nextB :| _iB) =
-    if nextA == nextB then LT else nextA `compare` nextB
-  (nextA :| _iA) `compare` (nextB :/ _iB) =
-    if nextA == nextB then GT else nextA `compare` nextB
-  Deriv `compare` Deriv = EQ
-  Deriv `compare` _ = LT
-  _ `compare` Deriv = GT
+  compare = go EQ
+    where
+      -- @later@ is the order of the steps seen so far, which are the later
+      -- steps of the two paths: a difference in an earlier step replaces it.
+      go later (nextA :| iA) (nextB :| iB) = sameKind later iA iB nextA nextB
+      go later (nextA :/ iA) (nextB :/ iB) = sameKind later iA iB nextA nextB
+      go _ (nextA :/ _) (nextB :| _) = go LT nextA nextB
+      go _ (nextA :| _) (nextB :/ _) = go GT nextA nextB
+      go later Deriv Deriv = later
+      go _ Deriv _ = LT
+      go _ _ Deriv = GT
+      -- Two steps of the same kind sort by their index
+      sameKind later iA iB = go $! compare iA iB <> later
 
 instance Serial DerivPath where
   deserialize = listToPath <$> getList getWord32be
@@ -868,13 +876,16 @@
       | otherwise = go is :/ i
     go [] = Deriv
 
--- | Convert a derivation path to a human-readable string.
+-- | Convert a derivation path to a human-readable string: each step as @\/@
+-- and its index, with @'@ after the index of a hardened step, and no @m@ or
+-- @M@ in front. The text is written in one pass over the steps, so it takes
+-- time by the length of the path. Every text form of a path is this one: the
+-- 'Show' and JSON instances of the path types and of 'ParsedPath'.
 pathToStr :: DerivPathI t -> String
-pathToStr p =
-  case p of
-    next :| i -> concat [pathToStr next, "/", show i, "'"]
-    next :/ i -> concat [pathToStr next, "/", show i]
-    Deriv -> ""
+pathToStr =
+  concatMap step . pathSteps
+  where
+    step (hard, i) = '/' : shows i (if hard then "'" else "")
 
 -- | Turn a derivation path into a hard derivation path. Will fail if the path
 -- contains soft derivations.
@@ -899,16 +910,16 @@
   next :| i -> toGeneric next :| i
   Deriv -> Deriv
 
--- | Append two derivation paths together. The result will be a mixed
--- derivation path.
+-- | Append two derivation paths together: the steps of the first, then the
+-- steps of the second. The result is a mixed derivation path, whatever the
+-- two paths hold. It takes time by the length of the two paths.
 (++/) :: DerivPathI t1 -> DerivPathI t2 -> DerivPath
 (++/) p1 p2 =
-  go id (toGeneric p2) $ toGeneric p1
+  foldl' step (toGeneric p1) (pathSteps p2)
   where
-    go f p = case p of
-      next :/ i -> go (f . (:/ i)) $ toGeneric next
-      next :| i -> go (f . (:| i)) $ toGeneric next
-      _ -> f
+    step p (hard, i)
+      | hard = p :| i
+      | otherwise = p :/ i
 
 -- | Derive a private key from a derivation path. Throws
 -- 'DerivationException' when the path cannot be followed, for example when it
diff --git a/src/Haskoin/Crypto/Keys/Slip39.hs b/src/Haskoin/Crypto/Keys/Slip39.hs
--- a/src/Haskoin/Crypto/Keys/Slip39.hs
+++ b/src/Haskoin/Crypto/Keys/Slip39.hs
@@ -35,7 +35,8 @@
 -- A share is a secret. The 'Show' instances of this module leave the share
 -- values out, and an error names the position of a wrong word, never the
 -- word. A mnemonic can come from an untrusted source, so its length is
--- checked before anything else: a share has at most 1023 words.
+-- checked before anything else: a share has at most 1023 words. So is the
+-- number of the shares to combine: a backup has at most 256.
 --
 -- The field arithmetic looks bytes of the secret up in tables, as the
 -- reference implementation does, so its timing depends on them. Hardware
@@ -65,6 +66,7 @@
     encryptMasterSecret,
     decryptMasterSecret,
     decryptMasterSecretBytes,
+    roundIterations,
 
     -- * Shamir's secret sharing
     splitSecret,
@@ -108,6 +110,7 @@
 import Data.List (nub, transpose)
 import Data.Map.Strict (Map)
 import Data.Map.Strict qualified as M
+import Data.Set qualified as S
 import Data.Text (Text)
 import Data.Text qualified as T
 import Data.Text.Encoding qualified as E
@@ -210,6 +213,12 @@
 maxShares :: Int
 maxShares = 16
 
+-- | The most shares that rebuild a backup: as many groups as the highest
+-- group threshold, and in each as many members as the highest member
+-- threshold, 16 times 16.
+maxCombinedShares :: Int
+maxCombinedShares = maxShares * maxShares
+
 -- | The fewest bytes of a master secret: 128 bits.
 minSecretBytes :: Int
 minSecretBytes = 16
@@ -304,6 +313,15 @@
 -- | The random values a split draws: the T - 2 random shares, each as long
 -- as the secret, and the random part of the digest share, four bytes
 -- shorter. A split with a threshold of 1 draws none.
+--
+-- The security of the split rests on these values. Each one must be
+-- uniform, drawn independently of every other from a source fit for keys,
+-- kept as secret as the shares, and used for one split only: the
+-- specification says "generated randomly, independently with uniform
+-- distribution". A random share is handed out as it is, as the share of
+-- the member of its index. So a value given to two splits, or twice to
+-- one, gives one member the share of another, and a value that somebody
+-- can guess gives that person a share.
 data SplitRandom = SplitRandom
   { randomShares :: ![ByteString],
     digestRandom :: !ByteString
@@ -333,12 +351,33 @@
 hmacSha256 :: ByteString -> ByteString -> ByteString
 hmacSha256 key msg = BA.convert (hmac key msg :: HMAC SHA256)
 
+-- | Refuses random values of which two are equal, among the splits given.
+-- Values drawn as t'SplitRandom' asks have at least 96 bits each and are
+-- never equal, so this refuses no honest caller. It catches the mistakes
+-- that give working shares: one set of values passed to every split, or a
+-- source of random bytes that is stuck. It cannot tell a value that is
+-- not random from one that is, so it replaces none of what t'SplitRandom'
+-- asks.
+--
+-- A random share has the length of the secret and a random part is four
+-- bytes shorter, so one is never taken for the other. The empty random
+-- part of a split at a threshold of 1 is no value.
+checkDrawnOnce :: [SplitRandom] -> Either String ()
+checkDrawnOnce randoms =
+  when (S.size (S.fromList values) /= length values) $
+    Left "Two of the random values are equal: each one must be drawn on its own"
+  where
+    values = [v | r <- randoms, v <- r.digestRandom : r.randomShares, not (B.null v)]
+
 -- | SplitSecret of the specification: the shares of a secret at the given
 -- threshold and count, with their indices from 0, computed from the random
 -- values given. With a threshold of 1 every share is the secret itself.
 -- Otherwise the random shares take the first indices, the digest share
 -- sits at 254 and the secret at 255, and the remaining shares are the
 -- polynomials through those points.
+--
+-- The random values must be as t'SplitRandom' says. Two random shares that
+-- are equal are refused.
 splitSecret :: Int -> Int -> ByteString -> SplitRandom -> Either String [(Word8, ByteString)]
 splitSecret threshold count secret random = do
   when (threshold < 1) $ Left "The threshold must be at least 1"
@@ -352,6 +391,7 @@
     Left "A random share must be as long as the secret"
   unless (B.length random.digestRandom == randomPartLength) $
     Left ("The random part of the digest share must have " <> show randomPartLength <> " bytes")
+  checkDrawnOnce [random]
   if threshold == 1
     then return [(i, secret) | i <- indicesUpTo count]
     else do
@@ -607,8 +647,8 @@
 -- that order: the halves L and R become (R, L xor F(i, R)) each round, and
 -- the result is R || L. The round function is PBKDF2-HMAC-SHA256 of the
 -- round number followed by the passphrase, salted with the salt prefix
--- and R, with 2500 times 2 to the exponent iterations. The passphrase is
--- given as its bytes.
+-- and R, with 'roundIterations' iterations. The passphrase is given as its
+-- bytes.
 feistel :: [Word8] -> Int -> Bool -> Int -> ByteString -> ByteString -> ByteString
 feistel rounds identifier ext iterExponent passphrase secret = right <> left
   where
@@ -617,7 +657,7 @@
     step (l, r) i = (r, B.pack (B.zipWith xor l (roundFunction i r)))
     roundFunction i r =
       fastPBKDF2_SHA256
-        Parameters {iterCounts = 2500 `shiftL` iterExponent, outputLength = half}
+        Parameters {iterCounts = roundIterations iterExponent, outputLength = half}
         (B.cons i passphrase)
         (saltPrefix <> r)
     -- Without the extendable flag the identifier salts the passphrase, so
@@ -626,6 +666,17 @@
       | ext = B.empty
       | otherwise = "shamir" <> integerToBytes 2 (toInteger identifier)
 
+-- | The PBKDF2 iterations of one round of the cipher at an iteration
+-- exponent: 2500 times 2 to its power, the @2500 << e@ of the
+-- specification. The four rounds together make the 10000 times 2 to the
+-- exponent that a share states.
+--
+-- The count has a name of its own so that a test can state it at each of
+-- the 16 exponents. A run of the cipher cannot do that for the high ones:
+-- at the exponent 15 one encryption takes minutes.
+roundIterations :: Int -> Int
+roundIterations iterExponent = 2500 `shiftL` iterExponent
+
 {- Generating shares -}
 
 -- | The shares of a master secret under a scheme, with the random values
@@ -633,6 +684,17 @@
 -- groups and one for each group's split among its members, in that order.
 -- GenerateShares of the specification, with the identifier and the
 -- extendable flag as arguments. The shares come as one list per group.
+--
+-- This function is for a caller with random values of its own, such as
+-- the values of the system with dice rolls mixed in. Every value must be
+-- as t'SplitRandom' says: uniform, secret, and drawn for one split alone.
+-- Each split needs a t'SplitRandom' of its own. With one given to several
+-- splits at a threshold of 3 or more, the first member of each group gets
+-- the same share, which is also the share of the first group: one person
+-- then holds what a threshold of members of that group are needed for. A
+-- list in which a value comes twice is refused. Nothing can refuse values
+-- that are not random, such as zeros: use 'generateShares' unless you
+-- have a reason not to.
 generateSharesWith :: Scheme -> Int -> Bool -> Int -> Text -> ByteString -> [SplitRandom] -> Either String [[Share]]
 generateSharesWith scheme identifier ext iterExponent passphrase secret randoms = do
   checkScheme scheme
@@ -646,6 +708,7 @@
           <> " groups takes "
           <> show (groupCount + 1)
           <> " sets of random values: one for the split among the groups, then one per group"
+  checkDrawnOnce randoms
   groupShares <- splitSecret scheme.groupThreshold groupCount ems.ciphertext groupRandom
   forM (zip3 scheme.groups groupShares memberRandoms) $ \((threshold, members), (gi, groupSecret), random) -> do
     memberShares <- splitSecret threshold members groupSecret random
@@ -701,6 +764,7 @@
 -- | 'generateShares' with the source of random bytes as its first
 -- argument: a function from a number of bytes to that many random bytes.
 -- Use it to draw from a generator of your own, which must be fit for keys.
+-- A source that gives the same bytes for two of the values is refused.
 -- With @getRandomBytes@ of crypton it runs in any @MonadRandom@. Mind that
 -- in 'IO' that function takes its bytes from the RDRAND instruction of the
 -- processor alone when the processor has one, and does not mix in the
@@ -708,7 +772,11 @@
 --
 -- The source is only asked for whole values, never for zero bytes, and
 -- only after the scheme, the exponent, the passphrase and the secret have
--- passed their checks.
+-- passed their checks. It is asked in the order of the reference
+-- implementation, so both give the same shares from the same stream of
+-- bytes: two bytes for the identifier, the high byte first and its top bit
+-- dropped, then the random shares and the random part of the digest share
+-- of each split, the split among the groups first and each group after it.
 generateSharesFrom ::
   (Monad m) =>
   -- | the source of random bytes
@@ -761,9 +829,14 @@
 -- the member threshold, have distinct member indices and be exactly as many
 -- as that threshold. Each group's secret is recovered from its members,
 -- then the master secret from the groups.
+--
+-- The shares are counted before anything else is done with them: 16 groups
+-- of 16 members are 256 shares, so a longer list rebuilds nothing, and it
+-- is refused in the time it takes to walk it.
 combineShares :: [Share] -> Either String EncryptedMasterSecret
 combineShares [] = Left "There are no shares to combine"
 combineShares shares@(first : _) = do
+  checkShareCount shares
   mapM_ checkShare shares
   agree "identifier" (.identifier)
   agree "extendable flag" (.extendable)
@@ -771,7 +844,10 @@
   agree "group threshold" (.groupThreshold)
   agree "group count" (.groupCount)
   agree "length of their values" (B.length . (.value))
-  let groups = M.toList (M.fromListWith (flip (++)) [(s.groupIndex, [s]) | s <- shares])
+  -- Each share goes in front of the list of its group, which takes
+  -- constant time, so the shares are taken from the last one to keep their
+  -- order
+  let groups = M.toList (M.fromListWith (++) [(s.groupIndex, [s]) | s <- reverse shares])
   unless (length groups == first.groupThreshold) $
     Left ("The shares come from " <> counted (length groups) "group" <> ", but the group threshold is " <> show first.groupThreshold)
   groupSecrets <- forM groups $ \(gi, members) -> do
@@ -801,6 +877,14 @@
         Left ("The shares do not have the same " <> what)
     duplicates xs = nub [x | (i, x) <- zip [0 :: Int ..] xs, x `elem` take i xs]
 
+-- | Refuses more shares, or more mnemonics, than a backup can have.
+checkShareCount :: [a] -> Either String ()
+checkShareCount shares =
+  when (count > maxCombinedShares) $
+    Left ("There are " <> show count <> " shares, but a backup has at most " <> show maxCombinedShares)
+  where
+    count = length shares
+
 -- | The master secret the mnemonics rebuild, decrypted with the passphrase,
 -- which must be printable ASCII (see 'decryptMasterSecret').
 --
@@ -811,8 +895,12 @@
 -- milliseconds. The specification allows it. A program that reads shares
 -- from an untrusted source should look at the @iterationExponent@ that
 -- 'decodeShare' gives before it combines them.
+--
+-- More than 256 mnemonics are refused by their number, before any of them
+-- is read.
 combineMnemonics :: Text -> [Text] -> Either String ByteString
 combineMnemonics passphrase mnemonics = do
+  checkShareCount mnemonics
   shares <- mapM decodeShare mnemonics
   ems <- combineShares shares
   decryptMasterSecret passphrase ems
diff --git a/src/Haskoin/Crypto/Signature.hs b/src/Haskoin/Crypto/Signature.hs
--- a/src/Haskoin/Crypto/Signature.hs
+++ b/src/Haskoin/Crypto/Signature.hs
@@ -25,6 +25,7 @@
 
     -- * Schnorr signatures of Bitcoin Cash
     verifyCashSchnorr,
+    isCashSchnorrLength,
   )
 where
 
@@ -58,6 +59,12 @@
 signHash k = signMsg k . hashToMsg
 
 -- | Verify an ECDSA signature for a 256-bit hash.
+--
+-- A signature with a high s verifies like its low-S form: the s is brought
+-- below half the curve order first, as libsecp256k1 asks. So 'True' does not
+-- say that the s is low. Where a high s is refused, on Bitcoin Cash in every
+-- block and on Bitcoin by the relay policy, check 'isCanonicalHalfOrder' as
+-- well.
 verifyHashSig :: Hash256 -> Sig -> PubKey -> Bool
 verifyHashSig h s p = verifySig p (normalizeSig s) (hashToMsg h)
 
@@ -105,11 +112,20 @@
         Just s -> return s
 
 -- | Is the s component at most half the curve order? This is the low-S rule
--- that Bitcoin Core applies to the transactions it relays:
--- @SCRIPT_VERIFY_LOW_S@ is one of its standard flags. It is not a consensus
--- rule, so a block may hold a signature with a high s. The decoders of this
--- module do not apply it. Check it with this function where the relay rules
--- matter. 'signHash' always makes a signature that passes.
+-- (@SCRIPT_VERIFY_LOW_S@), and the two chains give it another weight:
+--
+-- * On Bitcoin it is a rule of the relay policy, one of the standard flags
+--   of Bitcoin Core. It is not a consensus rule, so a block may hold a
+--   signature with a high s.
+-- * On Bitcoin Cash it is a consensus rule since November 2017, one of the
+--   @MANDATORY_SCRIPT_VERIFY_FLAGS@ of Bitcoin Cash Node: no block holds an
+--   ECDSA signature with a high s, and a node drops the peer that sends a
+--   transaction with one.
+--
+-- The decoders of this module do not apply the rule, and 'verifyHashSig'
+-- does not tell a high s from a low one. Check it with this function where
+-- the relay rules of Bitcoin matter, and always on Bitcoin Cash. 'signHash'
+-- always makes a signature that passes.
 isCanonicalHalfOrder :: Sig -> Bool
 isCanonicalHalfOrder = isLowS
 
@@ -122,9 +138,40 @@
 -- verify. 'importSig' applies both rules.
 --
 -- A high s is accepted, since BIP 66 allows it and such signatures are in the
--- block chain. Use 'isCanonicalHalfOrder' for the low-S relay rule.
+-- block chain of Bitcoin. Use 'isCanonicalHalfOrder' for the low-S rule: a
+-- rule of the relay policy on Bitcoin, and a consensus rule on Bitcoin Cash,
+-- where what this function reads is more than a block can hold.
+--
+-- On Bitcoin Cash the length matters too. A signature of 64 bytes is a
+-- Schnorr signature there ('verifyCashSchnorr'), also when it is the strict
+-- DER form of an ECDSA signature that verifies: this function reads it, and
+-- no block of Bitcoin Cash holds it as an ECDSA signature. Check
+-- 'isCashSchnorrLength' there. 'Haskoin.Script.SigHash.decodeTxSig' does.
 decodeStrictSig :: ByteString -> Maybe Sig
 decodeStrictSig = importSig
+
+-- | Is the DER form of this ECDSA signature 64 bytes long? On Bitcoin Cash
+-- a signature of that length is a Schnorr signature, whatever its bytes
+-- (@IsSchnorrSig@ in Bitcoin Cash Node). The node verifies it as one in
+-- @OP_CHECKSIG@, where an ECDSA signature fails, and takes no signature of
+-- that length in a multisig that has no field of bits. So no block of
+-- Bitcoin Cash holds such an ECDSA signature, and a node drops the peer
+-- that sends a transaction with one. On Bitcoin it is an ordinary
+-- signature.
+--
+-- The DER form has 6 bytes besides r and s, which mostly take 32 or 33
+-- bytes each. Here they take 58 together. The specification of the Schnorr
+-- signatures of Bitcoin Cash gives one chance in 2^49 that a signer makes
+-- such a signature, but a computer makes one on purpose in a minute, with
+-- a key of its own.
+--
+-- This is, with 'isCanonicalHalfOrder', what to check of a signature read
+-- by 'decodeStrictSig' before it is verified for Bitcoin Cash.
+-- 'Haskoin.Script.SigHash.decodeTxSig' refuses such a signature on a
+-- network with a fork id, and 'Haskoin.Transaction.Builder.Sign.makeSignature'
+-- does not hand one out there.
+isCashSchnorrLength :: Sig -> Bool
+isCashSchnorrLength = (== 64) . BS.length . exportSig
 
 -- | Verify a Schnorr signature of Bitcoin Cash: 64 bytes, @r@ then @s@,
 -- of a public key over a 32-byte digest.
diff --git a/src/Haskoin/Network/Constants.hs b/src/Haskoin/Network/Constants.hs
--- a/src/Haskoin/Network/Constants.hs
+++ b/src/Haskoin/Network/Constants.hs
@@ -21,7 +21,7 @@
     btcTest4,
     btcRegTest,
     bch,
-    bchTest,
+    bchTest3,
     bchTest4,
     bchRegTest,
     allNets,
@@ -102,47 +102,9 @@
       targetTimespan = 14 * 24 * 60 * 60,
       minimumChainWork = 0x0145ec036acc5ba740052af1a0,
       targetSpacing = 10 * 60,
-      checkpoints =
-        [ ( 11111,
-            "0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"
-          ),
-          ( 33333,
-            "000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6"
-          ),
-          ( 74000,
-            "0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20"
-          ),
-          ( 105000,
-            "00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97"
-          ),
-          ( 134444,
-            "00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe"
-          ),
-          ( 168000,
-            "000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763"
-          ),
-          ( 193000,
-            "000000000000059f452a5f7340de6682a977387c17010ff6e6c3bd83ca8b1317"
-          ),
-          ( 210000,
-            "000000000000048b95347e83192f69cf0366076336c639f9b7228e9ba171342e"
-          ),
-          ( 216116,
-            "00000000000001b4f4b433e81ee46494af945cf96014816a4e2370f11b23df4e"
-          ),
-          ( 225430,
-            "00000000000001c108384350f74090433e7fcf79a606b8e797f065b130575932"
-          ),
-          ( 250000,
-            "000000000000003887df1f29024b06fc2200b55f8af8f35453d7be294df2d214"
-          ),
-          ( 279000,
-            "0000000000000001ae8c72a0b0c301f67e3afca10e819efa9041e458e9bd7e40"
-          ),
-          ( 295000,
-            "00000000000000004d9b4ef50f0f9d686fd69db2e03af35a100370c64632a983"
-          )
-        ],
+      -- Bitcoin Core 32.1 has no checkpoints: its minimum chain work and the
+      -- low-work headers sync protect the sync instead.
+      checkpoints = [],
       seeds =
         [ "dnsseed.bluematt.me", -- Matt Corallo
           "seed.bitcoin.jonasschnelli.ch", -- Jonas Schnelli
@@ -158,6 +120,7 @@
       daaHeight = Nothing,
       asertActivationTime = Nothing,
       asertHalfLife = 0,
+      asertAnchorBlock = Nothing,
       segWit = True,
       cashAddrPrefix = Nothing,
       bech32Prefix = Just "bc",
@@ -165,7 +128,13 @@
       halvingInterval = 210000
     }
 
--- | Testnet for Bitcoin SegWit network.
+-- | Testnet3 for Bitcoin SegWit network. Deprecated: use 'btcTest4'.
+--
+-- 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. This value stays, still in 'allNets' and found by 'netByName', so
+-- that code reading old testnet3 data keeps working, and will be removed in a
+-- later major version.
 btcTest :: Network
 btcTest =
   Network
@@ -205,11 +174,9 @@
       targetTimespan = 14 * 24 * 60 * 60,
       minimumChainWork = 0x17f49f702147f10c0eb6,
       targetSpacing = 10 * 60,
-      checkpoints =
-        [ ( 546,
-            "000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"
-          )
-        ],
+      -- Bitcoin Core 32.1 has no checkpoints: its minimum chain work and the
+      -- low-work headers sync protect the sync instead.
+      checkpoints = [],
       seeds =
         [ "testnet-seed.bitcoin.jonasschnelli.ch", -- Jonas Schnelli
           "seed.tbtc.petertodd.net", -- Peter Todd
@@ -222,6 +189,7 @@
       daaHeight = Nothing,
       asertActivationTime = Nothing,
       asertHalfLife = 0,
+      asertAnchorBlock = Nothing,
       segWit = True,
       cashAddrPrefix = Nothing,
       bech32Prefix = Just "tb",
@@ -281,6 +249,7 @@
       daaHeight = Nothing,
       asertActivationTime = Nothing,
       asertHalfLife = 0,
+      asertAnchorBlock = Nothing,
       segWit = True,
       cashAddrPrefix = Nothing,
       bech32Prefix = Just "tb",
@@ -330,13 +299,15 @@
       minimumChainWork = 0,
       targetSpacing = 10 * 60,
       checkpoints = [],
-      seeds = ["localhost"],
+      -- the placeholder of Bitcoin Core, which never resolves
+      seeds = ["dummySeed.invalid"],
       bip44Coin = 1,
       sigHashForkId = Nothing,
       edaHeight = Nothing,
       daaHeight = Nothing,
       asertActivationTime = Nothing,
       asertHalfLife = 0,
+      asertAnchorBlock = Nothing,
       segWit = True,
       cashAddrPrefix = Nothing,
       bech32Prefix = Just "bcrt",
@@ -384,6 +355,7 @@
       targetTimespan = 14 * 24 * 60 * 60,
       minimumChainWork = 0x030fd678912166474fe93f14,
       targetSpacing = 10 * 60,
+      -- mapCheckpoints of Bitcoin Cash Node 29.2.0, src/chainparams.cpp
       checkpoints =
         [ ( 11111,
             "0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"
@@ -424,16 +396,75 @@
           ( 295000,
             "00000000000000004d9b4ef50f0f9d686fd69db2e03af35a100370c64632a983"
           ),
-          -- UAHF fork block.
-
           ( 478559,
             "000000000000000000651ef99cb9fcbe0dadde1d424bd9f15ff20136191a5eec"
           ),
-          -- Nov, 13 DAA activation block.
-
-          ( 504031,
-            "0000000000000000011ebf65b60d0a3de80b8175be709d653b4c1a1beeb6ab9c"
+          ( 504032,
+            "00000000000000000343e9875012f2062554c8752929892c82a0c0743ac7dcfd"
           ),
+          ( 530359,
+            "0000000000000000011ada8bd08f46074f44a8f155396f43e38acf9501c49103"
+          ),
+          ( 556767,
+            "0000000000000000004626ff6e3b936941d341c5932ece4357eeccac44e6d56c"
+          ),
+          ( 582680,
+            "000000000000000001b4b8e36aec7d4f9671a47872cb9a74dc16ca398c7dcc18"
+          ),
+          ( 609136,
+            "000000000000000000b48bb207faac5ac655c313e41ac909322eaa694f5bc5b1"
+          ),
+          ( 635259,
+            "00000000000000000033dfef1fc2d6a5d5520b078c55193a9bf498c5b27530f7"
+          ),
+          ( 661648,
+            "0000000000000000029e471c41818d24b8b74c911071c4ef0b4a0509f9b5a8ce"
+          ),
+          ( 682900,
+            "0000000000000000018b0a60a00ca53b69b213a8515e5eedbf8a207f0355fe42"
+          ),
+          ( 699484,
+            "0000000000000000030192242425926218184a609a63efee615b7586d7f3972b"
+          ),
+          ( 714881,
+            "000000000000000004cd628ee64c058183e780bc31143ff00680ea8af51fa0ff"
+          ),
+          ( 740238,
+            "000000000000000002afc6fbd302f01f8cf4533f4b45207abc61d9f4297bf969"
+          ),
+          ( 741245,
+            "000000000000000001c46d1d0f35df726bfb3e84cdc396d9edd9e2f8414191cd"
+          ),
+          ( 768220,
+            "0000000000000000012f9d67fc9304253bdf204b65782816cbbc64913398e25b"
+          ),
+          ( 773784,
+            "0000000000000000045cc0dbdd5cbbb86f7f63596e699ac5a11b2d41c65c6993"
+          ),
+          ( 792773,
+            "000000000000000002fc0cdadaef1857bbd2936d37ea94f80ba3db4a5e8353e8"
+          ),
+          ( 845891,
+            "0000000000000000017012058e7b67032926f1f20f96d1a2cd66abff9aaf8244"
+          ),
+          ( 853417,
+            "000000000000000001c97a4c91c7a85d5f56a7ecd119f21abffdc6987a1be792"
+          ),
+          ( 873239,
+            "000000000000000000e28c75f4b398b3ac410755d18ef9314b770c3d08cb130e"
+          ),
+          ( 878660,
+            "000000000000000000c166d5661c13195722ae6fbee90f0ab2407ae60b71c2e6"
+          ),
+          ( 898374,
+            "00000000000000000157a0a3dcdc80f1acd809648d238c1e893b26247091b3b4"
+          ),
+          ( 901000,
+            "000000000000000001eda4b93cfe9bc790906f2358fc5643ff335da5e7bbae5d"
+          ),
+          ( 932228,
+            "0000000000000000005a48a20e13f038be389952014373478b6a6a90d40e4680"
+          ),
           ( 951145,
             "000000000000000000f64dbed68370486f945097ba90b17e30d7bf5c43df7a60"
           ),
@@ -459,6 +490,9 @@
       daaHeight = Just 504032,
       asertActivationTime = Just 1605441600,
       asertHalfLife = 2 * 24 * 60 * 60,
+      -- Block 661647, as asertAnchorParams of Bitcoin Cash Node.
+      asertAnchorBlock =
+        Just (661647, "00000000000000000083ed4b7a780d59e3983513215518ad75654bb02deee62f"),
       segWit = False,
       cashAddrPrefix = Just "bitcoincash",
       bech32Prefix = Nothing,
@@ -506,12 +540,11 @@
       targetTimespan = 14 * 24 * 60 * 60,
       minimumChainWork = 0xbd5a1b5bda45b5da,
       targetSpacing = 10 * 60,
+      -- mapCheckpoints of Bitcoin Cash Node 29.2.0, src/chainparams.cpp
       checkpoints =
         [ ( 5000,
             "000000009f092d074574a216faec682040a853c4f079c33dfd2c3ef1fd8108c4"
           ),
-          -- Axion activation
-
           ( 16845,
             "00000000fb325b8f34fe80c96a5f708a08699a68bbab82dba4474d86bd743077"
           ),
@@ -521,6 +554,42 @@
           ( 54700,
             "00000000009af4379d87f17d0f172ee4769b48839a5a3a3e81d69da4322518b8"
           ),
+          ( 68117,
+            "0000000000a2c2fc11a3b72adbd10a3f02a1f8745da55a85321523043639829a"
+          ),
+          ( 95465,
+            "00000000a77206a2265cabc47cc2c34706ba1c5e5a5743ac6681b83d43c91a01"
+          ),
+          ( 115252,
+            "00000000ae25e85d9e22cd6c8d72c2f5d4b0222289d801b7f633aeae3f8c6367"
+          ),
+          ( 121428,
+            "00000000002cf277337c504f7ce708cce851d5d20cad2936fedf3be95a9ca5eb"
+          ),
+          ( 128070,
+            "00000000044f34642fa3d91e34678737cc10a821a4696f50c187091c3df480c2"
+          ),
+          ( 148044,
+            "0000000008d96c4423ac92aa200af82819339435251736b08babde1ecaf8a5b6"
+          ),
+          ( 200741,
+            "0000000007d8ccbb767c269551dd81c520463066bec8654a18f4106aa53dc816"
+          ),
+          ( 206379,
+            "000000001d44ca6c351af579f81703c0a175d1d4554db70ae7b7f7df2919eaf9"
+          ),
+          ( 226116,
+            "000000008416a726dd957835add86d7166ef331b74f2f2ca38928dcd56484f8e"
+          ),
+          ( 232000,
+            "0000000018ef632fc8a77dd4ff6a6e29ad2c7af405af63247c6f28a051b1b817"
+          ),
+          ( 253319,
+            "00000000004605937a919cf6f636b68e8137b5cb0226ddbc9e00f386ef02999b"
+          ),
+          ( 277407,
+            "00000000fd6af07e5c4618de0cc36796f9470620eb4610584d9011b9f41d3400"
+          ),
           ( 305848,
             "00000000601bf68f9927154cf55557b1c08245b4d415658d1cbcd1eb4502dabc"
           ),
@@ -543,6 +612,9 @@
       daaHeight = Just 3001,
       asertActivationTime = Just 1605441600,
       asertHalfLife = 60 * 60,
+      -- Block 16844, as asertAnchorParams of Bitcoin Cash Node.
+      asertAnchorBlock =
+        Just (16844, "00000000602570ee2b66c1d3f75d404c234f8aacdcc784da97e65838a2daf0fc"),
       segWit = False,
       cashAddrPrefix = Just "bchtest",
       bech32Prefix = Nothing,
@@ -550,11 +622,21 @@
       halvingInterval = 210000
     }
 
--- | Testnet for Bitcoin Cash network.
-bchTest :: Network
-bchTest =
+-- | Testnet3 for Bitcoin Cash network.
+--
+-- Bitcoin Cash Node 29.2.0 supports testnet3 without a deprecation notice,
+-- unlike Bitcoin Core, so this network is not deprecated. 'bchTest4' is the
+-- smaller test network, with blocks of 2 MB.
+--
+-- The value and its 'name', @bchtest3@, carry the number of the testnet, as
+-- those of 'bchTest4' do, so that neither looks like the default test network
+-- of Bitcoin Cash. They were @bchTest@ and @bchtest@ before 3.0.0. The
+-- CashAddr prefix stays @bchtest@: Bitcoin Cash Node gives it to every test
+-- network.
+bchTest3 :: Network
+bchTest3 =
   Network
-    { name = "bchtest",
+    { name = "bchtest3",
       addrPrefix = 111,
       scriptPrefix = 196,
       secretPrefix = 239,
@@ -590,20 +672,56 @@
       targetTimespan = 14 * 24 * 60 * 60,
       minimumChainWork = 0x011fdbbe582349040762,
       targetSpacing = 10 * 60,
+      -- mapCheckpoints of Bitcoin Cash Node 29.2.0, src/chainparams.cpp
       checkpoints =
         [ ( 546,
             "000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"
           ),
-          -- UAHF fork block.
-
           ( 1155876,
             "00000000000e38fef93ed9582a7df43815d5c2ba9fd37ef70c9a0ea4a285b8f5"
           ),
-          -- Nov, 13. DAA activation block.
-
-          ( 1188697,
-            "0000000000170ed0918077bde7b4d36cc4c91be69fa09211f748240dabe047fb"
+          ( 1188698,
+            "0000000000051b450faa75bb8e1ea30bc18c4b9736e765d2794259a53bc83f99"
           ),
+          ( 1303885,
+            "00000000000000479138892ef0e4fa478ccc938fb94df862ef5bde7e8dee23d3"
+          ),
+          ( 1341712,
+            "00000000fffc44ea2e202bd905a9fbbb9491ef9e9d5a9eed4039079229afa35b"
+          ),
+          ( 1500206,
+            "000000000000360769353e933530c40d3f00565a4e7731ff56027e23fa74a8ef"
+          ),
+          ( 1526155,
+            "0000000057fa336560212f0ff351ca6b2008c6c48032bc305e5b4663e837953f"
+          ),
+          ( 1532821,
+            "00000000000000e2e476a806171758c75e6fd4c28d1435a56701df87874ddd2f"
+          ),
+          ( 1552788,
+            "000000007bc92323648b95ea8401a2247e977b653b13adb9e40748ce06b30a5e"
+          ),
+          ( 1582896,
+            "000000000000088ef4d908ed35dc511b97fe4df78d5e37ab1e1aea4084d19506"
+          ),
+          ( 1605521,
+            "000000000000007d4c561056e9bcb3ab7591d024b18fff4bc27cca4d51d4780e"
+          ),
+          ( 1610899,
+            "00000000e2f5dde96179ea278285118ad69e5d94b9269fef63c604b3d551a5d0"
+          ),
+          ( 1630783,
+            "000000002e0058b88b1857bbf2ca3edaaade318e54bbb9226ca53b3ae5528f90"
+          ),
+          ( 1636000,
+            "0000000000001af6a0fb0ec4f079858b6add6d070381f94157be80fdb4809c65"
+          ),
+          ( 1658050,
+            "0000000015d90bbd6deeb63cf86dc1f794d76c697d2ea86a42158c8003da8c5e"
+          ),
+          ( 1689348,
+            "000000001935f758281aa60414a1218dcd09b4dc6b7ad0be2a3cddbcd38ff265"
+          ),
           ( 1710483,
             "00000000078fe0c74ffa0c5221081c34774aa7d17a3c14c36f952f829463f120"
           ),
@@ -625,6 +743,7 @@
       daaHeight = Just 1188698,
       asertActivationTime = Just 1605441600,
       asertHalfLife = 60 * 60,
+      asertAnchorBlock = Nothing,
       segWit = False,
       cashAddrPrefix = Just "bchtest",
       bech32Prefix = Nothing,
@@ -672,18 +791,24 @@
       targetTimespan = 14 * 24 * 60 * 60,
       minimumChainWork = 0,
       targetSpacing = 10 * 60,
+      -- mapCheckpoints of Bitcoin Cash Node 29.2.0, src/chainparams.cpp
       checkpoints =
         [ ( 0,
             "0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"
           )
         ],
-      seeds = ["localhost"],
+      -- Bitcoin Cash Node has no seeds on regtest.
+      seeds = [],
       bip44Coin = 1,
       sigHashForkId = Just 0,
-      edaHeight = Nothing,
-      daaHeight = Just 0,
+      -- uahfHeight and daaHeight are 0 in Bitcoin Cash Node, so both rules
+      -- apply from block 1. No-retargeting comes first on regtest, so they
+      -- change no difficulty.
+      edaHeight = Just 1,
+      daaHeight = Just 1,
       asertActivationTime = Just 1605441600,
       asertHalfLife = 2 * 24 * 60 * 60,
+      asertAnchorBlock = Nothing,
       segWit = False,
       cashAddrPrefix = Just "bchreg",
       bech32Prefix = Nothing,
@@ -691,6 +816,9 @@
       halvingInterval = 150
     }
 
--- | List of all networks supported by this library.
+{-# DEPRECATED btcTest "Testnet3 is deprecated: use btcTest4" #-}
+
+-- | List of all networks supported by this library, the deprecated 'btcTest'
+-- included.
 allNets :: [Network]
-allNets = [btc, bch, btcTest, btcTest4, bchTest4, bchTest, btcRegTest, bchRegTest]
+allNets = [btc, bch, btcTest, btcTest4, bchTest4, bchTest3, btcRegTest, bchRegTest]
diff --git a/src/Haskoin/Network/Data.hs b/src/Haskoin/Network/Data.hs
--- a/src/Haskoin/Network/Data.hs
+++ b/src/Haskoin/Network/Data.hs
@@ -86,7 +86,11 @@
     targetTimespan :: !Word32,
     -- | time between blocks
     targetSpacing :: !Word32,
-    -- | checkpoints
+    -- | blocks that the chain must hold at these heights, as the reference
+    -- node pins them. 'Haskoin.Block.Headers.connectBlocks' refuses a header
+    -- at such a height with another hash, and a fork below the last
+    -- checkpoint the chain has reached. Bitcoin Core 32.1 has none, so the
+    -- Bitcoin networks have none either; Bitcoin Cash Node keeps them.
     checkpoints :: ![(BlockHeight, BlockHash)],
     -- | work that the best chain is known to have, @nMinimumChainWork@ of the
     -- reference node. Once the best block has this much work,
@@ -95,7 +99,9 @@
     minimumChainWork :: !Integer,
     -- | BIP44 derivation path root
     bip44Coin :: !Word32,
-    -- | peer-to-peer network seeds
+    -- | DNS seeds of the network, as the reference node lists them. On
+    -- regtest they are a placeholder that does not resolve (Bitcoin Core) or
+    -- none (Bitcoin Cash Node).
     seeds :: ![String],
     -- | fork id for replay protection
     sigHashForkId :: !(Maybe Word32),
@@ -110,6 +116,25 @@
     asertActivationTime :: !(Maybe Word32),
     -- | asert3-2d algorithm halflife (not used for non-BCH networks)
     asertHalfLife :: !Integer,
+    -- | height and hash of the aserti3-2d anchor block, where it is known.
+    -- The anchor is the first block whose median time past reached the
+    -- activation time, and every later difficulty depends on it. Without this
+    -- constant 'Haskoin.Block.Headers.asertAnchor' finds the anchor with a
+    -- binary search down the chain, about 1,500 reads of the store at height
+    -- 100,000. With it, one walk to the ancestor at that height is enough,
+    -- about 80 reads, and the search is still used for a chain that does not
+    -- hold this block.
+    --
+    -- The block must be the first whose median time past reaches the
+    -- activation time. When the chain holds it, it is taken as the anchor
+    -- without looking at its median time past, so a wrong block gives every
+    -- block above it another difficulty, with no error. Set it only from a
+    -- trusted source, such as the constants of the reference node.
+    -- Bitcoin Cash Node keeps the same constant (@asertAnchorParams@). It is
+    -- 'Nothing' on regtest, where every chain has its own anchor, and on
+    -- testnet3, whose anchor block could not be checked against a second
+    -- source when it was added.
+    asertAnchorBlock :: !(Maybe (BlockHeight, BlockHash)),
     -- | segregated witness active
     segWit :: !Bool,
     -- | 'CashAddr' prefix (for Bitcoin Cash)
diff --git a/src/Haskoin/Network/Protocol.hs b/src/Haskoin/Network/Protocol.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Network/Protocol.hs
@@ -0,0 +1,125 @@
+{-# LANGUAGE DeriveAnyClass #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+
+-- |
+-- Module      : Haskoin.Network.Protocol
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- Pure state machines that model how the reference node of each supported
+-- network treats one peer: Bitcoin Core 32.1 for the Bitcoin networks, and
+-- Bitcoin Cash Node 29.2.0 for the Bitcoin Cash networks.
+--
+-- The problem they solve: the peer-to-peer protocol is defined by what these
+-- nodes do, not by a specification. The BIPs leave out most of what decides
+-- whether a connection lives: which messages are dropped before the
+-- handshake, which ones count as misbehaviour, when the node pings and how
+-- long it waits, what a whitelisted peer may do that others may not. A
+-- program that talks to these nodes, such as haskoin-node, needs that map to
+-- behave correctly, and its tests need an oracle to compare against. Each
+-- machine is a translation of the upstream source, with a t'Cite' of the file
+-- and line behind every t'Effect', so the map can be checked against the code
+-- and brought forward to a new release.
+--
+-- Pick a machine for a network with 'machine', open a 'Connection' with
+-- 'start', and feed it 'Input's with 'step':
+--
+-- > let m = machine btc
+-- >     c0 = start m setup
+-- >     (c1, effects) = step env c0 (Receive (MVersion ver))
+--
+-- The vocabulary is in "Haskoin.Network.Protocol.Types". The rules of each
+-- node, with the options it reads, are in
+-- "Haskoin.Network.Protocol.BitcoinCore" and
+-- "Haskoin.Network.Protocol.BitcoinCashNode". The report
+-- @doc\/protocol\/README.md@ of the repository describes the protocol of both
+-- nodes in prose, with the same references, and is kept in step with these
+-- modules.
+--
+-- What the machines leave out, and why:
+--
+-- * Validation of blocks and transactions, and the state of the chain and the
+--   mempool. A machine asks the t'Env' for verdicts instead. Translating
+--   consensus is a different job, and a verdict is all that the protocol
+--   needs.
+-- * Decisions that span peers, such as which peer to download a block from or
+--   which inbound peer to evict. Where one of them changes what a peer sees,
+--   it comes in as a 'Notification'.
+-- * Bytes. A machine sees whole messages, and framing errors as 'FrameError'.
+module Haskoin.Network.Protocol
+  ( -- * Machines
+    Machine (..),
+    machine,
+    upstreamOf,
+    networkOf,
+
+    -- * Connections
+    Connection (..),
+    start,
+    step,
+
+    -- * Vocabulary
+    module Haskoin.Network.Protocol.Types,
+  )
+where
+
+import Control.DeepSeq (NFData)
+import GHC.Generics (Generic)
+import Haskoin.Network.Data (Network (..))
+import Haskoin.Network.Protocol.BitcoinCashNode qualified as BCHN
+import Haskoin.Network.Protocol.BitcoinCore qualified as Core
+import Haskoin.Network.Protocol.Types
+
+-- | The rules of one node on one network, with its options.
+data Machine
+  = -- | Bitcoin Core, which serves the Bitcoin networks
+    BitcoinCore !Core.Options
+  | -- | Bitcoin Cash Node, which serves the Bitcoin Cash networks
+    BitcoinCashNode !BCHN.Options
+  deriving (Eq, Show, Generic, NFData)
+
+-- | The machine of the reference node of a network, with the options that
+-- node has when started with none. A network with a fork id is a Bitcoin Cash
+-- network.
+machine :: Network -> Machine
+machine net = case net.sigHashForkId of
+  Just _ -> BitcoinCashNode (BCHN.defaultOptions net)
+  Nothing -> BitcoinCore (Core.defaultOptions net)
+
+-- | The upstream release that a machine translates.
+upstreamOf :: Machine -> Upstream
+upstreamOf (BitcoinCore _) = Core.upstream
+upstreamOf (BitcoinCashNode _) = BCHN.upstream
+
+-- | The network of a machine.
+networkOf :: Machine -> Network
+networkOf (BitcoinCore o) = o.network
+networkOf (BitcoinCashNode o) = o.network
+
+-- | One connection as a node sees it: the rules and the state it keeps about
+-- the peer. The two travel together so that a state can never be stepped by
+-- the rules of the other node.
+data Connection
+  = CoreConnection !Core.Options !Core.State
+  | BchnConnection !BCHN.Options !BCHN.State
+  deriving (Eq, Show, Generic, NFData)
+
+-- | Open a connection.
+start :: Machine -> Setup -> Connection
+start (BitcoinCore o) s = CoreConnection o (Core.start o s)
+start (BitcoinCashNode o) s = BchnConnection o (BCHN.start o s)
+
+-- | Feed one input to a connection: the new connection and what the node did,
+-- in the order it did it.
+step :: Env -> Connection -> Input -> (Connection, [Effect])
+step env (CoreConnection o s) i =
+  let (s', es) = Core.step o env s i
+   in (CoreConnection o s', es)
+step env (BchnConnection o s) i =
+  let (s', es) = BCHN.step o env s i
+   in (BchnConnection o s', es)
diff --git a/src/Haskoin/Network/Protocol/BitcoinCashNode.hs b/src/Haskoin/Network/Protocol/BitcoinCashNode.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Network/Protocol/BitcoinCashNode.hs
@@ -0,0 +1,476 @@
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE MultiWayIf #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- |
+-- Module      : Haskoin.Network.Protocol.BitcoinCashNode
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- The protocol machine of Bitcoin Cash Node 29.2.0: how that node treats one
+-- peer on the Bitcoin Cash networks, translated from its source.
+--
+-- = What it is for
+--
+-- A program that talks to Bitcoin Cash Node, such as haskoin-node, must know
+-- what the node does with each message to behave well: which messages it
+-- drops before the handshake, which ones cost ban score and how much, when it
+-- pings and how long it waits for the answer, what a whitelisted peer may do.
+-- None of this is in a specification. This machine is that map, with the
+-- upstream file and line behind every t'Effect', so that it can be checked
+-- against the code, used as an oracle in tests, and brought forward to the
+-- next release.
+--
+-- = How it is built
+--
+-- 'step' takes the options, the t'Env' (the chain, the mempool and the rest of
+-- the node as seen at that moment), the t'State' of the connection and one
+-- 'Input', and returns the next state and the effects in the order the node
+-- produces them. It is a pure function; randomness comes from the t'Rng' in the
+-- state, seeded by the @seed@ of the t'Setup'.
+--
+-- The modules follow the upstream code:
+--
+-- * "Haskoin.Network.Protocol.BitcoinCashNode.Handshake": framing, the
+--   handshake, @ping@, the ban score, the inactivity timeouts;
+-- * "Haskoin.Network.Protocol.BitcoinCashNode.Blocks": headers, blocks,
+--   compact blocks, block announcements and download timers;
+-- * "Haskoin.Network.Protocol.BitcoinCashNode.Relay": transactions,
+--   double-spend proofs, Bloom filters, addresses, and the @inv@ trickle;
+-- * "Haskoin.Network.Protocol.BitcoinCashNode.Options",
+--   "Haskoin.Network.Protocol.BitcoinCashNode.State" and
+--   "Haskoin.Network.Protocol.BitcoinCashNode.Constants": the options, the
+--   state and the constants, each with its upstream name.
+--
+-- An input goes through the same gates as a message upstream
+-- (@PeerLogicValidation::ProcessMessages@ and @ProcessMessage@,
+-- @src\/net_processing.cpp:1999-3950@):
+--
+-- 1. Nothing is processed once the node decided to close the connection.
+-- 2. @filterload@ and @filteradd@ when the node offers no Bloom filters.
+-- 3. @reject@, accepted in any state and only logged.
+-- 4. @version@.
+-- 5. Anything else before @version@ costs 10 (\"missing-version\").
+-- 6. @extversion@, @verack@ and @sendaddrv2@.
+-- 7. Anything else before the peer's @verack@ is dropped.
+-- 8. The handler of the command; an unknown command is dropped.
+-- 9. After the message, the @reject@s of invalid blocks are sent and a crossed
+--    ban score is acted on.
+--
+-- A 'Tick' runs the inactivity check of the socket thread, then
+-- @SendMessages@ once the handshake is complete: ping, the ban score, our
+-- address, queued addresses, the first @getheaders@, block announcements,
+-- @inv@s, the download timers, the chain-sync check, @getdata@ and
+-- @feefilter@, in that order (@src\/net_processing.cpp:4143-4848@).
+--
+-- = Bitcoin Cash Node and Bitcoin Core
+--
+-- The code base is Bitcoin Core of about 0.19 with Bitcoin Cash changes. A
+-- peer sees these differences from Bitcoin Core 32.1: integer ban scores with
+-- a threshold (@-banscore@, 100), BIP 61 @reject@ messages, a bad checksum
+-- that discourages the address, the @extversion@ handshake, double-spend
+-- proofs (@dsproof-beta@), no @wtxidrelay@, @sendtxrcncl@, BIP 157 filters or
+-- encrypted transport, no block-relay-only connections in practice, compact
+-- blocks of version 1 with 32-bit positions, and messages of up to twice the
+-- block size for blocks.
+--
+-- = Permissions and connection types
+--
+-- Only inbound peers have permissions ('effectivePermissions'): a bare
+-- @-whitelist@ gives @noban@, @mempool@ and, by default, @relay@. A @noban@
+-- peer is never discouraged or disconnected for its score, is served
+-- @getheaders@ during initial block download, gets transactions announced at
+-- every pass, and may break the upload target. A manual peer is not punished
+-- for its score either, and a local address is disconnected without being
+-- discouraged. Feelers leave after @version@, address-fetch connections after
+-- the first @addr@. Outbound full-relay peers must offer the services the
+-- node wants, are checked for a chain with enough work, and get our address
+-- and a @getaddr@.
+--
+-- = The four networks
+--
+-- One machine per network is these rules with 'defaultOptions' of the
+-- network. The rules are the same on all of them; what differs:
+--
+-- * __bch__ (main): magic e3e1f3e8, genesis time 1231006505, default block size
+--   32 MB, so 112 transactions per announcement; minimum chain work of the
+--   network.
+-- * __bchTest__ (testnet3): magic f4e5f3f4, genesis time 1296688602, 32 MB
+--   blocks.
+-- * __bchTest4__ (testnet4): magic e2b7daaf, genesis time 1597811185, 2 MB
+--   blocks, so 7 transactions per announcement.
+-- * __bchRegTest__ (regtest): magic dab5bffa, genesis time 1296688602, 32 MB
+--   blocks, minimum chain work 0, so a headers chain never has too little
+--   work.
+--
+-- The magic and the size limit of block messages (twice the block size) are
+-- checked by the caller, which reports 'WrongMagic' and 'Oversized'. A
+-- @version@ older than the genesis block costs 20. All timeouts and scores
+-- are the same on every network; the target spacing is 600 seconds on all.
+--
+-- = What the machine leaves out
+--
+-- See the module headers for details. In short: decisions across peers come
+-- as 'Notification's (which block to download from whom, eviction, which
+-- peers get an address), validation comes from the t'Env', the rolling Bloom
+-- filters of known inventory are exact sets, and the parts of the protocol
+-- that need bytes the library does not parse (a short @version@, more entries
+-- than the library's parser allows) cannot be fed to it as messages: the
+-- caller gets 'BadPayload' for them, which the machine treats as a payload
+-- that does not parse.
+--
+-- The report @doc\/protocol\/bitcoin-cash-node.md@ describes the same rules
+-- in prose with links to the upstream lines, and changes with this module.
+module Haskoin.Network.Protocol.BitcoinCashNode
+  ( -- * The machine
+    upstream,
+    Options (..),
+    defaultOptions,
+    State,
+    start,
+    step,
+
+    -- * Inspecting a connection
+    handshakeComplete,
+    peerVersionOf,
+    isClosing,
+    banScoreOf,
+    permissionsOf,
+    servicesOffered,
+    negotiatedAddrV2,
+    negotiatedExtVersion,
+    prefersHeaders,
+    highBandwidthFrom,
+    highBandwidthTo,
+    relaysTransactions,
+    blocksInFlight,
+    txsInFlight,
+    pingOutstanding,
+    bestKnownBlock,
+    preferredDownloadPeer,
+
+    -- * Permissions and services
+    effectivePermissions,
+    localServices,
+  )
+where
+
+import Control.Monad (forM_, unless, void, when)
+import Control.Monad.RWS.Strict (get, gets, modify')
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as BS
+import Data.Bytes.Get (getWord64le, runGetS)
+import Data.Map.Strict qualified as Map
+import Data.Word (Word64)
+import Haskoin.Block.Common (BlockHash)
+import Haskoin.Network.Common
+  ( Addr (..),
+    AddrV2 (..),
+    GetData (..),
+    MessageCommand (..),
+    Ping (..),
+    Pong (..),
+    stringToCommand,
+    toNetworkAddressV2,
+  )
+import Haskoin.Network.Message (Message (..))
+import Haskoin.Network.Protocol.BitcoinCashNode.Blocks
+import Haskoin.Network.Protocol.BitcoinCashNode.Constants
+import Haskoin.Network.Protocol.BitcoinCashNode.Handshake
+import Haskoin.Network.Protocol.BitcoinCashNode.Options
+import Haskoin.Network.Protocol.BitcoinCashNode.Relay
+import Haskoin.Network.Protocol.BitcoinCashNode.State
+import Haskoin.Network.Protocol.Types
+import Haskoin.Transaction.Common (TxHash)
+
+-- | The release whose source this machine translates.
+upstream :: Upstream
+upstream =
+  Upstream
+    { project = "Bitcoin Cash Node",
+      release = "29.2.0",
+      tag = "v29.2.0",
+      commit = "07576013c91ff4a3a74acd85f189c69121cdad1b",
+      repository = "https://gitlab.com/bitcoin-cash-node/bitcoin-cash-node"
+    }
+
+-- | The state when a connection opens. An outbound connection sends our
+-- @version@ with the first input, which upstream sends at once
+-- (@InitializeNode@, @src\/net_processing.cpp:787-808@).
+start :: Options -> Setup -> State
+start = initialState
+
+-- | One step of the machine: the new state and what the node did, in order.
+step :: Options -> Env -> State -> Input -> (State, [Effect])
+step o e s i = runM o e s (input i)
+
+input :: Input -> M ()
+input i = do
+  closing <- gets (.closing)
+  if closing
+    then case i of
+      Receive _ -> ignore (netProcessing 3836 "message after the decision to disconnect")
+      BadFrame _ -> ignore (netProcessing 3836 "message after the decision to disconnect")
+      _ -> return ()
+    else do
+      initializeNode
+      case i of
+        Receive m -> do
+          received
+          dispatch m
+          void sendRejectsAndCheckIfShouldDiscourage
+        BadFrame (BadPayload cmd) -> do
+          received
+          badPayload cmd
+          void sendRejectsAndCheckIfShouldDiscourage
+        BadFrame f -> do
+          received
+          frameError f
+        Tick -> tick
+        Notify n -> notify n
+  where
+    received = do
+      t <- nowM
+      modify' (\s -> s {lastRecv = t})
+
+-- | Steps 2 to 8 of the gates of a message.
+dispatch :: Message -> M ()
+dispatch m = do
+  acted <- if isBloomLoad m then bloomPrologue else return False
+  unless acted $ case m of
+    MReject _ -> receiveReject
+    MVersion v -> receiveVersion v
+    _ -> do
+      pv <- gets (.peerVersion)
+      if pv == 0 then missingVersion else afterVersion
+  where
+    isBloomLoad = \case
+      MFilterLoad _ -> True
+      MFilterAdd _ -> True
+      _ -> False
+    afterVersion = case m of
+      MOther c p | c == extVersionCommand -> receiveExtVersion (Just p)
+      MVerAck -> receiveVerAck
+      MSendAddrV2 -> receiveSendAddrV2
+      _ -> do
+        done <- gets (.connected)
+        if done then handle m else priorToVerAck
+
+-- | The handlers of the commands after the handshake.
+handle :: Message -> M ()
+handle = \case
+  MAddr (Addr xs) -> receiveAddr (map toNetworkAddressV2 xs)
+  MAddrV2 (AddrV2 xs) -> receiveAddr xs
+  MSendHeaders -> receiveSendHeaders
+  MSendCompact sc -> receiveSendCmpct sc
+  MInv i -> receiveInv i
+  MGetData g -> receiveGetData g
+  MGetBlocks g -> receiveGetBlocks g
+  MGetBlockTxn g -> receiveGetBlockTxn g
+  MGetHeaders g -> receiveGetHeaders g
+  MTx tx -> receiveTx tx
+  MCompactBlock cb -> receiveCmpctBlock cb
+  MBlockTxn bt -> receiveBlockTxn bt
+  MHeaders h -> receiveHeaders h
+  MBlock b -> receiveBlock b
+  MGetAddr -> receiveGetAddr
+  MMempool -> receiveMempool
+  MPing (Ping n) -> receivePing (Just n)
+  MPong (Pong n) -> receivePong (Just n)
+  MOther "ping" p -> receivePing (nonceOf p)
+  MOther "pong" p -> receivePong (nonceOf p)
+  MFilterLoad f -> receiveFilterLoad f
+  MFilterAdd f -> receiveFilterAdd f
+  MFilterClear -> receiveFilterClear
+  MFeeFilter f -> receiveFeeFilter f
+  MNotFound n -> receiveNotFound n
+  MOther c p | c == dsProofCommand -> receiveDsProof (Just p)
+  _ -> unknownCommand
+
+-- | The nonce at the start of a raw @ping@ or @pong@ payload.
+nonceOf :: ByteString -> Maybe Word64
+nonceOf p
+  | BS.length p >= 8 = either (const Nothing) Just (runGetS getWord64le (BS.take 8 p))
+  | otherwise = Nothing
+
+-- | A payload that does not parse, through the same gates as a message: the
+-- handler that would read it throws, and the node answers with a @reject@
+-- (@src\/net_processing.cpp:3927-3934@). Commands whose handler does not read
+-- the payload are handled as if it were empty, and @pong@ and
+-- @dsproof-beta@ handle a bad payload themselves.
+badPayload :: ByteString -> M ()
+badPayload cmd = do
+  acted <-
+    if cmd `elem` ["filterload", "filteradd"]
+      then bloomPrologue
+      else return False
+  unless acted $ do
+    pv <- gets (.peerVersion)
+    done <- gets (.connected)
+    if
+      | cmd == "reject" -> receiveReject
+      | cmd == "version" ->
+          if pv /= 0 then duplicateVersion else parseError MCVersion
+      | pv == 0 -> missingVersion
+      | cmd == extVersionCommand -> receiveExtVersion Nothing
+      | cmd == "verack" -> receiveVerAck
+      | cmd == "sendaddrv2" -> receiveSendAddrV2
+      | not done -> priorToVerAck
+      | cmd == "sendheaders" -> receiveSendHeaders
+      | cmd == "getaddr" -> receiveGetAddr
+      | cmd == "mempool" -> receiveMempool
+      | cmd == "filterclear" -> receiveFilterClear
+      | cmd == "pong" -> receivePong Nothing
+      | cmd == "ping" -> receivePing Nothing
+      | cmd == dsProofCommand -> receiveDsProof Nothing
+      | otherwise -> case stringToCommand cmd of
+          MCOther _ -> unknownCommand
+          c
+            | c `elem` handled -> parseError c
+            | otherwise -> unknownCommand
+  where
+    handled =
+      [ MCAddr,
+        MCAddrV2,
+        MCInv,
+        MCGetData,
+        MCNotFound,
+        MCGetBlocks,
+        MCGetHeaders,
+        MCTx,
+        MCBlock,
+        MCHeaders,
+        MCFilterLoad,
+        MCFilterAdd,
+        MCFeeFilter,
+        MCSendCmpct,
+        MCCmpctBlock,
+        MCGetBlockTxn,
+        MCBlockTxn
+      ]
+
+-- | Time passes: the inactivity check, then @SendMessages@ once the peer's
+-- @verack@ has arrived (@src\/net_processing.cpp:4149-4151@).
+tick :: M ()
+tick = do
+  inactivityCheck
+  s <- get
+  when (s.connected && not s.closing) sendMessages
+
+-- | @SendMessages@ (@src\/net_processing.cpp:4143-4848@).
+sendMessages :: M ()
+sendMessages = do
+  sendPing
+  discouraged <- sendRejectsAndCheckIfShouldDiscourage
+  unless discouraged $ do
+    advertiseLocal
+    sendAddresses
+    initialGetHeaders
+    blockAnnouncements
+    sendInventory
+    stopped <- downloadTimers
+    unless stopped $ do
+      considerEviction
+      blocks <- blockRequests
+      proofs <- dsProofRequests
+      txs <- txRequests
+      forM_ (chunksOf maxGetDataSize (blocks <> proofs <> txs)) $ \c ->
+        send (MGetData (GetData c)) (netProcessing 4743 "GETDATA")
+      sendFeeFilter
+  where
+    chunksOf _ [] = []
+    chunksOf n xs = let (a, b) = splitAt n xs in a : chunksOf n b
+
+-- | News from the rest of the node.
+notify :: Notification -> M ()
+notify = \case
+  NewTip hs -> updatedBlockTip hs
+  TxAccepted tx -> txAccepted tx
+  RelayAddress a -> relayAddress a
+  HighBandwidth b -> highBandwidth b
+  RequestBlock h -> requestBlock h
+  RequestTx h -> requestTx h
+  OperatorDisconnect -> disconnect Resources (netCpp 2728 "DisconnectNode")
+  PingRequested -> modify' (\s -> s {pingQueued = True})
+  MarkStalling -> stalling
+  Penalty n r -> misbehaving n (netProcessing 905 r)
+  NewDoubleSpendProof h tx -> newDoubleSpendProof h tx
+  NewPoWValidBlock hdr -> newPoWValidBlock hdr
+  Evict -> disconnect Resources (netCpp 1018 "AttemptToEvictConnection")
+
+-- | The peer's @verack@ has arrived (@fSuccessfullyConnected@).
+handshakeComplete :: State -> Bool
+handshakeComplete s = s.connected
+
+-- | The protocol version of the peer, once its @version@ has arrived.
+peerVersionOf :: State -> Maybe Int
+peerVersionOf s = if s.peerVersion == 0 then Nothing else Just s.peerVersion
+
+-- | The node decided to close the connection (@fDisconnect@).
+isClosing :: State -> Bool
+isClosing s = s.closing
+
+-- | The ban score of the peer (@nMisbehavior@).
+banScoreOf :: State -> Int
+banScoreOf s = s.misbehavior
+
+-- | The permissions of the peer, after the node expanded them.
+permissionsOf :: State -> Permissions
+permissionsOf s = s.perms
+
+-- | The services the node offers this peer.
+servicesOffered :: State -> Word64
+servicesOffered s = s.ourServices
+
+-- | The peer sent @sendaddrv2@ in time.
+negotiatedAddrV2 :: State -> Bool
+negotiatedAddrV2 s = s.wantsAddrV2
+
+-- | The peer's @extversion@ was accepted.
+negotiatedExtVersion :: State -> Bool
+negotiatedExtVersion s = s.extVersionEnabled
+
+-- | The peer sent @sendheaders@.
+prefersHeaders :: State -> Bool
+prefersHeaders s = s.blocks.preferHeaders
+
+-- | The peer asked for high-bandwidth compact blocks.
+highBandwidthFrom :: State -> Bool
+highBandwidthFrom s = s.blocks.preferHeaderAndIds
+
+-- | The node asked the peer for high-bandwidth compact blocks.
+highBandwidthTo :: State -> Bool
+highBandwidthTo s = s.blocks.highBandwidthTo
+
+-- | The node announces transactions to the peer (@fRelayTxes@).
+relaysTransactions :: State -> Bool
+relaysTransactions s = s.relay.relayTxes
+
+-- | Blocks requested from the peer, oldest first.
+blocksInFlight :: State -> [BlockHash]
+blocksInFlight s = map (.inFlightHash) s.blocks.inFlight
+
+-- | Transactions requested from the peer and not answered yet.
+txsInFlight :: State -> [TxHash]
+txsInFlight s =
+  [h | (h, TxAnnouncement _ (TxRequested _)) <- Map.toList s.relay.announcements]
+
+-- | The nonce of the ping that waits for its @pong@.
+pingOutstanding :: State -> Maybe Word64
+pingOutstanding s = if s.pingNonceSent == 0 then Nothing else Just s.pingNonceSent
+
+-- | The best block the peer is known to have.
+bestKnownBlock :: State -> Maybe BlockInfo
+bestKnownBlock s = s.blocks.bestKnown
+
+-- | The peer is a preferred source of downloads (@fPreferredDownload@).
+preferredDownloadPeer :: State -> Bool
+preferredDownloadPeer s = s.preferredDownload
diff --git a/src/Haskoin/Network/Protocol/BitcoinCashNode/Blocks.hs b/src/Haskoin/Network/Protocol/BitcoinCashNode/Blocks.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Network/Protocol/BitcoinCashNode/Blocks.hs
@@ -0,0 +1,1044 @@
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE MultiWayIf #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- |
+-- Module      : Haskoin.Network.Protocol.BitcoinCashNode.Blocks
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- How Bitcoin Cash Node 29.2.0 moves headers and blocks with one peer:
+-- @getheaders@, @headers@, @getblocks@, the block part of @getdata@,
+-- @block@, @sendheaders@, @sendcmpct@, @cmpctblock@, @getblocktxn@,
+-- @blocktxn@, the announcements of new blocks, and the timers of block
+-- download.
+--
+-- The code base of Bitcoin Cash Node is close to Bitcoin Core 0.19 here:
+-- there is no anti-DoS headers pre-sync, headers of low work are stored as
+-- soon as they validate, compact blocks are of version 1 only with 32-bit
+-- positions, and an invalid block costs the score that validation gives,
+-- unless it came from a compact block.
+--
+-- What the machine simplifies, and why:
+--
+-- * Which blocks to download, and from whom, is decided across peers
+--   (@FindNextBlocksToDownload@). The rest of the node says it with
+--   'RequestBlock', and the machine requests the block at the next pass of
+--   @SendMessages@. The direct fetch after a @headers@ message is local to
+--   the peer and is modelled.
+-- * The block index is the t'Env'. After a @headers@ or @cmpctblock@ that
+--   validation accepts, the machine looks the header up in 'lookupBlock'; a
+--   caller should answer for headers that its 'checkHeaders' accepts. When it
+--   does not, the machine assumes the header has one unit of work per block
+--   of height above the tip.
+-- * A header's ancestry is found by walking 'headerOf' back, at most 2016
+--   steps; blocks of the active chain are found by height.
+-- * The count of outbound peers protected from the chain-sync check (at most
+--   4) is global, and the machine assumes there is room.
+module Haskoin.Network.Protocol.BitcoinCashNode.Blocks
+  ( -- * Messages
+    receiveSendHeaders,
+    receiveSendCmpct,
+    receiveBlockInv,
+    afterInv,
+    receiveGetHeaders,
+    receiveHeaders,
+    receiveGetBlocks,
+    receiveGetBlockTxn,
+    receiveBlock,
+    receiveCmpctBlock,
+    receiveBlockTxn,
+    getBlockData,
+
+    -- * Notifications
+    updatedBlockTip,
+    newPoWValidBlock,
+    highBandwidth,
+    requestBlock,
+    stalling,
+
+    -- * SendMessages
+    initialGetHeaders,
+    blockAnnouncements,
+    downloadTimers,
+    considerEviction,
+    blockRequests,
+
+    -- * Chain helpers
+    locatorOf,
+    blockInfoOf,
+  )
+where
+
+import Control.Monad (forM_, unless, when)
+import Control.Monad.RWS.Strict (get, gets, modify')
+import Data.Bits ((.&.))
+import Data.Int (Int64)
+import Data.Maybe (fromMaybe, isJust, isNothing, mapMaybe)
+import Haskoin.Block.Common
+  ( Block (..),
+    BlockHash (..),
+    BlockHeader (..),
+    BlockHeight,
+    GetBlocks (..),
+    GetHeaders (..),
+    Headers (..),
+    headerHash,
+  )
+import Haskoin.Block.Merkle (MerkleBlock (..), buildPartialMerkle)
+import Haskoin.Network.Bloom (bloomRelevantUpdate)
+import Haskoin.Network.Common
+  ( GetData (..),
+    Inv (..),
+    InvType (..),
+    InvVector (..),
+    MessageCommand (..),
+    VarInt (..),
+  )
+import Haskoin.Network.CompactBlock
+  ( BlockTxn (..),
+    CompactBlock (..),
+    GetBlockTxn (..),
+    SendCompact (..),
+  )
+import Haskoin.Network.Data (Network (..))
+import Haskoin.Network.Message (Message (..))
+import Haskoin.Network.Protocol.BitcoinCashNode.Constants
+import Haskoin.Network.Protocol.BitcoinCashNode.Options (Options (..))
+import Haskoin.Network.Protocol.BitcoinCashNode.State
+import Haskoin.Network.Protocol.Types
+import Haskoin.Transaction.Common (txHash)
+
+-- * Chain helpers
+
+-- | What the node knows of a block, or what it assumes of a header that
+-- validation accepted but the t'Env' does not know: the height given, and one
+-- unit of work per block above the tip.
+blockInfoOf :: Env -> BlockHeader -> BlockHeight -> BlockInfo
+blockInfoOf e h height =
+  fromMaybe synth (e.lookupBlock hash)
+  where
+    hash = headerHash h
+    synth =
+      BlockInfo
+        { hash = hash,
+          height = height,
+          status = HeaderOnly,
+          inActiveChain = False,
+          work = e.tip.work + fromIntegral height - fromIntegral e.tip.height,
+          time = h.timestamp
+        }
+
+-- | The parent of a block, if the node knows it.
+parentOf :: Env -> BlockInfo -> Maybe BlockInfo
+parentOf e b
+  | b.inActiveChain && b.height > 0 = e.blockAtHeight (b.height - 1)
+  | otherwise = e.headerOf b.hash >>= e.lookupBlock . (.prev)
+
+-- | The ancestor of a block at a height (@CBlockIndex::GetAncestor@), found
+-- by height on the active chain and by walking parents elsewhere.
+ancestorAt :: Env -> BlockHeight -> BlockInfo -> Maybe BlockInfo
+ancestorAt e h b
+  | h > b.height = Nothing
+  | b.inActiveChain = e.blockAtHeight h
+  | otherwise = go (2016 :: Int) b
+  where
+    go 0 _ = Nothing
+    go n x
+      | x.height == h = Just x
+      | x.inActiveChain = e.blockAtHeight h
+      | otherwise = parentOf e x >>= go (n - 1)
+
+-- | Is the first block an ancestor of the second, or the same?
+isAncestorOf :: Env -> BlockInfo -> BlockInfo -> Bool
+isAncestorOf e a b = ((.hash) <$> ancestorAt e a.height b) == Just a.hash
+
+-- | The locator of a block (@CChain::GetLocator@): ten steps back one at a
+-- time, then steps that double, and the genesis block.
+locatorOf :: Env -> BlockInfo -> [BlockHash]
+locatorOf e b = go b.height (1 :: BlockHeight) (0 :: Int)
+  where
+    go h stp n =
+      case ancestorAt e h b of
+        Nothing -> genesis
+        Just x
+          | h == 0 -> [x.hash]
+          | otherwise ->
+              let stp' = if n + 1 > 10 then stp * 2 else stp
+                  h' = if stp' >= h then 0 else h - stp'
+               in x.hash : go h' stp' (n + 1)
+    genesis = maybe [] (\g -> [g.hash]) (e.blockAtHeight 0)
+
+-- | The block of the active chain after the fork with a locator
+-- (@FindForkInGlobalIndex@, @src\/validation.cpp:311-328@, then
+-- @ChainActive().Next@): the first locator hash on the active chain, the
+-- tip when a hash descends from it, else the genesis block.
+startAfterFork :: Env -> [BlockHash] -> Maybe BlockInfo
+startAfterFork e locator = e.blockAtHeight (fork.height + 1)
+  where
+    fork = case mapMaybe pick locator of
+      (x : _) -> x
+      [] -> fromMaybe e.tip (e.blockAtHeight 0)
+    pick h = do
+      b <- e.lookupBlock h
+      if
+        | b.inActiveChain -> Just b
+        | isAncestorOf e e.tip b -> Just e.tip
+        | otherwise -> Nothing
+
+-- | The tip is recent enough to fetch blocks as they are announced
+-- (@CanDirectFetch@, @src\/net_processing.cpp:623-627@): younger than 20
+-- block intervals.
+canDirectFetch :: Env -> Bool
+canDirectFetch e =
+  fromIntegral e.tip.time > e.now `div` 1000000 - targetSpacing * 20
+
+-- | The block may be served (@BlockRequestAllowed@,
+-- @src\/net_processing.cpp:936-950@): on the active chain, or validated and
+-- less than 30 days older than the best header. The proof-equivalent time
+-- of upstream is left out.
+blockRequestAllowed :: Env -> BlockInfo -> Bool
+blockRequestAllowed e b =
+  b.inActiveChain
+    || ( b.status == HaveData
+           && fromIntegral e.bestHeader.time - fromIntegral b.time < staleRelayAge
+       )
+
+-- | @ProcessBlockAvailability@ (@src\/net_processing.cpp:514-529@): promote
+-- the last unknown hash once the node knows it.
+processBlockAvailability :: M ()
+processBlockAvailability = do
+  e <- env
+  bs <- gets (.blocks)
+  forM_ bs.lastUnknown $ \h ->
+    forM_ (e.lookupBlock h) $ \b ->
+      when (b.work > 0) $
+        modifyBlocks $ \x ->
+          x
+            { bestKnown = better x.bestKnown b,
+              lastUnknown = Nothing
+            }
+  where
+    better Nothing b = Just b
+    better (Just a) b = if b.work >= a.work then Just b else Just a
+
+-- | @UpdateBlockAvailability@ (@src\/net_processing.cpp:532-552@): the peer
+-- has this block, so the best block it has may move.
+updateBlockAvailability :: BlockHash -> Maybe BlockInfo -> M ()
+updateBlockAvailability h known = do
+  processBlockAvailability
+  e <- env
+  case maybe (e.lookupBlock h) Just known of
+    Just b | b.work > 0 ->
+      modifyBlocks $ \x ->
+        x
+          { bestKnown = case x.bestKnown of
+              Just a | a.work > b.work -> Just a
+              _ -> Just b
+          }
+    _ -> modifyBlocks (\x -> x {lastUnknown = Just h})
+
+-- | @PeerHasHeader@ (@src\/net_processing.cpp:628-639@): the block is an
+-- ancestor of the best block the peer has, or of the best header sent to it.
+peerHasHeader :: BlockInfo -> M Bool
+peerHasHeader b = do
+  e <- env
+  bs <- gets (.blocks)
+  let under = maybe False (isAncestorOf e b)
+  return (under bs.bestKnown || under bs.bestHeaderSent)
+
+-- | @MarkBlockAsInFlight@ (@src\/net_processing.cpp:462-506@). Returns false
+-- when the block is in flight from this peer already.
+markInFlight :: BlockHash -> Bool -> Maybe CompactBlock -> M Bool
+markInFlight h validated partialBlock = do
+  bs <- gets (.blocks)
+  if any ((== h) . (.inFlightHash)) bs.inFlight
+    then return False
+    else do
+      t <- nowM
+      modifyBlocks $ \x ->
+        x
+          { inFlight = x.inFlight <> [InFlight h validated partialBlock],
+            downloadingSince = if null x.inFlight then t else x.downloadingSince
+          }
+      return True
+
+-- | @MarkBlockAsReceived@ for this peer (@src\/net_processing.cpp:413-457@).
+-- Returns whether the block was in flight from it.
+markReceived :: BlockHash -> M Bool
+markReceived h = do
+  bs <- gets (.blocks)
+  t <- nowM
+  case break ((== h) . (.inFlightHash)) bs.inFlight of
+    (_, []) -> return False
+    (before, _ : after) -> do
+      modifyBlocks $ \x ->
+        x
+          { inFlight = before <> after,
+            downloadingSince =
+              if null before then max x.downloadingSince t else x.downloadingSince,
+            stallingSince = 0
+          }
+      return True
+
+-- | A @getheaders@ with the locator of the best header and no stop.
+getHeadersFrom :: BlockInfo -> Cite -> M ()
+getHeadersFrom b c = do
+  e <- env
+  send (MGetHeaders (GetHeaders (fromIntegral protocolVersion) (locatorOf e b) zeroHash)) c
+
+-- | The null hash, for a @getheaders@ with no stop.
+zeroHash :: BlockHash
+zeroHash = "0000000000000000000000000000000000000000000000000000000000000000"
+
+-- | A @getdata@ for one block.
+getDataBlock :: InvType -> BlockHash -> Cite -> M ()
+getDataBlock t h = send (MGetData (GetData [InvVector t h.get]))
+
+-- * Messages
+
+-- | @sendheaders@ (@src\/net_processing.cpp:2513-2517@): announce new blocks
+-- with @headers@. The payload is not read, and there is no way back.
+receiveSendHeaders :: M ()
+receiveSendHeaders = modifyBlocks (\b -> b {preferHeaders = True})
+
+-- | @sendcmpct@ (@src\/net_processing.cpp:2520-2535@): only version 1 is
+-- known; a later message overrides the high-bandwidth flag.
+receiveSendCmpct :: SendCompact -> M ()
+receiveSendCmpct sc
+  | sc.version == 1 =
+      modifyBlocks $ \b ->
+        b {providesHeaderAndIds = True, preferHeaderAndIds = sc.announce}
+  | otherwise = ignore (netProcessing 2523 "sendcmpct of a version other than 1")
+
+-- | One @MSG_BLOCK@ entry of an @inv@ (@src\/net_processing.cpp:2573-2579@):
+-- the peer has the block; an unknown block not in flight anywhere is a
+-- candidate for the @getheaders@ that follows the loop. Returns the
+-- candidate.
+receiveBlockInv :: BlockHash -> M (Maybe BlockHash)
+receiveBlockInv h = do
+  e <- env
+  updateBlockAvailability h Nothing
+  bs <- gets (.blocks)
+  let known = isJust (e.lookupBlock h)
+      requested = e.inFlightElsewhere h > 0 || any ((== h) . (.inFlightHash)) bs.inFlight
+  return (if not known && not requested then Just h else Nothing)
+
+-- | After the entries of an @inv@: one @getheaders@ up to the last unknown
+-- block (@src\/net_processing.cpp:2616-2619@). No @getdata@ goes out for a
+-- block @inv@; the download follows the headers.
+afterInv :: Maybe BlockHash -> M ()
+afterInv = mapM_ $ \h -> do
+  e <- env
+  send (MGetHeaders (GetHeaders (fromIntegral protocolVersion) (locatorOf e e.bestHeader) h)) $
+    netProcessing 2617 "getheaders after a block inv"
+
+-- | @getheaders@ (@src\/net_processing.cpp:2777-2853@).
+receiveGetHeaders :: GetHeaders -> M ()
+receiveGetHeaders gh = do
+  e <- env
+  noban <- hasPerm PermNoBan
+  if
+    | length gh.locator > maxLocatorSize ->
+        disconnect ProtocolViolation (netProcessing 2786 "getheaders locator size")
+    | e.initialBlockDownload && not noban ->
+        ignore (netProcessing 2793 "Ignoring getheaders: initial block download")
+    | null gh.locator ->
+        case e.lookupBlock gh.stop of
+          Nothing -> ignore (netProcessing 2804 "getheaders for an unknown block")
+          Just b
+            | not (blockRequestAllowed e b) ->
+                ignore (netProcessing 2810 "old block header that isn't in the main chain")
+            | otherwise -> reply e (Just b)
+    | otherwise -> reply e (startAfterFork e gh.locator)
+  where
+    reply e start = do
+      let blocksFrom = case start of
+            Nothing -> []
+            Just b
+              | b.inActiveChain -> walk e b.height maxHeadersResults
+              | otherwise -> [b]
+          sent = blocksFrom
+          headers = mapMaybe (e.headerOf . (.hash)) sent
+      modifyBlocks $ \x ->
+        x {bestHeaderSent = Just (if null sent then e.tip else last sent)}
+      send (MHeaders (Headers [(h, VarInt 0) | h <- headers])) $
+        netProcessing 2852 "headers in reply to getheaders"
+    walk e h n
+      | n <= 0 = []
+      | otherwise = case e.blockAtHeight h of
+          Nothing -> []
+          Just b
+            | b.hash == gh.stop -> [b]
+            | otherwise -> b : walk e (h + 1) (n - 1)
+
+-- | @headers@ (@src\/net_processing.cpp:3393-3425@): more than 2000 is
+-- misbehaviour; headers from an outbound peer that is not manual are
+-- punished more for a known invalid block.
+receiveHeaders :: Headers -> M ()
+receiveHeaders (Headers hs)
+  | length hs > maxHeadersResults =
+      misbehaving 20 (netProcessing 3409 "too-many-headers")
+  | otherwise = do
+      ct <- connType
+      processHeaders (map fst hs) (ct /= Inbound && ct /= Manual)
+
+-- | @ProcessHeadersMessage@ (@src\/net_processing.cpp:1606-1865@).
+processHeaders :: [BlockHeader] -> Bool -> M ()
+processHeaders [] _ = ignore (netProcessing 1615 "empty headers")
+processHeaders hs@(first : rest) punishDuplicateInvalid = do
+  e <- env
+  let lastH = last hs
+      lastHash = headerHash lastH
+      count = length hs
+      continuous = and (zipWith (\a b -> b.prev == headerHash a) hs rest)
+  if isNothing (e.lookupBlock first.prev) && count < maxBlocksToAnnounce
+    then do
+      modifyBlocks (\b -> b {unconnecting = b.unconnecting + 1})
+      getHeadersFrom e.bestHeader (netProcessing 1635 "headers that do not connect")
+      updateBlockAvailability lastHash Nothing
+      n <- gets (.blocks.unconnecting)
+      when (n `mod` maxUnconnectingHeaders == 0) $
+        misbehaving 20 (netProcessing 1655 "too-many-unconnected-headers")
+    else
+      if not continuous
+        then misbehaving 20 (netProcessing 1665 "disconnected-header")
+        else do
+          let receivedNew = isNothing (e.lookupBlock lastHash)
+          case e.checkHeaders hs of
+            HeadersRejected dos r -> invalid e dos r
+            HeadersInvalid r -> invalid e 100 r
+            HeadersUnconnected -> invalid e 10 "prev-blk-not-found"
+            HeadersNonContinuous -> misbehaving 20 (netProcessing 1665 "disconnected-header")
+            HeadersLowWork -> accepted e receivedNew count (blockInfoOf e lastH e.tip.height)
+            HeadersAccepted height -> accepted e receivedNew count (blockInfoOf e lastH height)
+  where
+    invalid e dos r = do
+      misbehaving dos (netProcessing 1686 r)
+      let knownInvalid =
+            any
+              (\h -> maybe False ((== Invalid) . (.status)) (e.lookupBlock (headerHash h)))
+              hs
+      when (punishDuplicateInvalid && knownInvalid) $
+        disconnect Misbehaviour (netProcessing 1721 "known invalid header from an outbound peer")
+    accepted e receivedNew count lastInfo = do
+      t <- nowM
+      modifyBlocks (\b -> b {unconnecting = 0})
+      updateBlockAvailability lastInfo.hash (Just lastInfo)
+      when (receivedNew && lastInfo.work > e.tip.work) $
+        modifyBlocks (\b -> b {lastBlockAnnouncement = t `div` 1000000})
+      when (count == maxHeadersResults) $
+        getHeadersFrom lastInfo (netProcessing 1759 "getheaders after 2000 headers")
+      directFetch e lastInfo
+      ibdCheck e count
+      protectCheck e
+    directFetch e lastInfo =
+      when (canDirectFetch e && lastInfo.status /= Invalid && e.tip.work <= lastInfo.work) $ do
+        bs <- gets (.blocks)
+        let candidates = reverse hs
+            inActive h = maybe False (.inActiveChain) (e.lookupBlock (headerHash h))
+            outside = takeWhile (not . inActive) candidates
+            reachesChain = length outside < length candidates || parentInChain
+            parentInChain = maybe False (.inActiveChain) (e.lookupBlock first.prev)
+            wanted h =
+              let hh = headerHash h
+               in maybe True ((/= HaveData) . (.status)) (e.lookupBlock hh)
+                    && e.inFlightElsewhere hh == 0
+                    && not (any ((== hh) . (.inFlightHash)) bs.inFlight)
+            toFetch = take (maxBlocksInTransitPerPeer + 1) (filter wanted outside)
+        if not reachesChain
+          then ignore (netProcessing 1789 "Large reorg, won't direct fetch")
+          else do
+            requested <- fetchEarliestFirst (map headerHash (reverse toFetch))
+            unless (null requested) $ do
+              nInFlight <- gets (length . (.blocks.inFlight))
+              let compact =
+                    bs.providesHeaderAndIds
+                      && length requested == 1
+                      && e.otherBlocksInFlight + nInFlight == 1
+                  ty = if compact then InvCompactBlock else InvBlock
+              send (MGetData (GetData [InvVector ty h.get | h <- requested])) $
+                netProcessing 1822 "direct fetch"
+    fetchEarliestFirst [] = return []
+    fetchEarliestFirst (h : more) = do
+      n <- gets (length . (.blocks.inFlight))
+      if n >= maxBlocksInTransitPerPeer
+        then return []
+        else do
+          _ <- markInFlight h True Nothing
+          (h :) <$> fetchEarliestFirst more
+    ibdCheck e count = do
+      o <- options
+      ct <- connType
+      bk <- gets (.blocks.bestKnown)
+      let lowWork = maybe False (\b -> b.work < o.network.minimumChainWork) bk
+      when
+        ( e.initialBlockDownload
+            && count /= maxHeadersResults
+            && lowWork
+            && ct `elem` [OutboundFullRelay, BlockRelayOnly]
+        )
+        $ disconnect Unsuitable (netProcessing 1846 "headers chain has insufficient work")
+    protectCheck e = do
+      s <- get
+      case s.blocks.bestKnown of
+        Just bk
+          | not s.closing
+              && s.conn.connectionType == OutboundFullRelay
+              && not s.blocks.chainSync.protect
+              && bk.work >= e.tip.work ->
+              modifyBlocks $ \b -> b {chainSync = b.chainSync {protect = True}}
+        _ -> return ()
+
+-- | @getblocks@ (@src\/net_processing.cpp:2649-2727@): up to 500 block
+-- hashes after the fork, announced by @inv@ at the next pass, excluding the
+-- stop hash; a pruned node stops at blocks it may not have.
+receiveGetBlocks :: GetBlocks -> M ()
+receiveGetBlocks gb
+  | length gb.locator > maxLocatorSize =
+      disconnect ProtocolViolation (netProcessing 2656 "getblocks locator size")
+  | otherwise = do
+      e <- env
+      o <- options
+      let pruneLimit = fromIntegral e.tip.height - (288 - 3600 `div` targetSpacing)
+          go _ Nothing = []
+          go n (Just b)
+            | b.hash == gb.stop = []
+            | o.prune && (b.status /= HaveData || fromIntegral b.height <= pruneLimit) = []
+            | n <= 1 = [(b, True)]
+            | otherwise = (b, False) : go (n - 1 :: Int) (e.blockAtHeight (b.height + 1))
+          found = go 500 (startAfterFork e gb.locator)
+      forM_ found $ \(b, isLast) -> do
+        modifyBlocks (\x -> x {blockInvs = x.blockInvs <> [b.hash]})
+        when isLast $ modifyBlocks (\x -> x {hashContinue = Just b.hash})
+      if null found
+        then ignore (netProcessing 2717 "getblocks: nothing after the fork")
+        else process "block hashes queued for inv" (netProcessing 2717 "PushInventory(MSG_BLOCK)")
+
+-- | @getblocktxn@ (@src\/net_processing.cpp:2730-2775@). Bitcoin Cash Node
+-- disconnects a peer that asks for no transaction. For the most recent block
+-- it answers at once; for any other block it has, it sends the whole block.
+receiveGetBlockTxn :: GetBlockTxn -> M ()
+receiveGetBlockTxn g
+  | null g.indexes = disconnect ProtocolViolation (netProcessing 2738 "getblocktxn with no indexes")
+  | otherwise = do
+      e <- env
+      case e.recentBlock of
+        Just b
+          | headerHash b.header == g.hash -> sendBlockTransactions b
+        _ -> case e.lookupBlock g.hash of
+          Just bi
+            | bi.status == HaveData -> getBlockData (InvVector InvBlock g.hash.get)
+          _ -> ignore (netProcessing 2761 "getblocktxn for a block we don't have")
+  where
+    sendBlockTransactions b
+      | any (\i -> fromIntegral i >= length b.txs) g.indexes =
+          misbehaving 100 (netProcessing 1592 "out-of-bound-tx-index")
+      | otherwise =
+          send (MBlockTxn (BlockTxn g.hash [b.txs !! fromIntegral i | i <- g.indexes])) $
+            netProcessing 1603 "BLOCKTXN"
+
+-- | One block entry of a @getdata@ (@ProcessGetBlockData@,
+-- @src\/net_processing.cpp:1235-1476@).
+getBlockData :: InvVector -> M ()
+getBlockData inv = do
+  e <- env
+  s <- get
+  noban <- hasPerm PermNoBan
+  let h = BlockHash inv.invHash
+      pruned = s.ourServices .&. nodeNetworkLimited /= 0 && s.ourServices .&. nodeNetwork == 0
+  case e.lookupBlock h of
+    Nothing -> ignore (netProcessing 1272 "getdata for an unknown block")
+    Just b
+      | not (blockRequestAllowed e b) ->
+          ignore (netProcessing 1274 "old block that isn't in the main chain")
+      | e.historicalUploadTargetReached
+          && ( fromIntegral e.bestHeader.time - fromIntegral b.time > historicalBlockAge
+                 || inv.invType == InvMerkleBlock
+             )
+          && not noban ->
+          disconnect Resources (netProcessing 1297 "historical block serving limit reached")
+      | not noban
+          && pruned
+          && e.tip.height > b.height
+          && e.tip.height - b.height > nodeNetworkLimitedMinBlocks + 2 ->
+          disconnect Resources (netProcessing 1316 "block beyond the depth a pruned node serves")
+      | otherwise -> case (b.status, e.blockData h) of
+          (HaveData, Just blk) -> serve e b blk
+          _ -> ignore (netProcessing 1321 "block data not on disk")
+  where
+    serve e b blk = do
+      case inv.invType of
+        InvMerkleBlock -> filtered blk
+        InvCompactBlock
+          | canDirectFetch e && b.height + maxCmpctBlockDepth >= e.tip.height,
+            Just cb <- e.compactBlockOf b.hash ->
+              send (MCompactBlock cb) (netProcessing 1445 "CMPCTBLOCK in reply to getdata")
+        _ -> send (MBlock blk) (netProcessing 1379 "BLOCK in reply to getdata")
+      hc <- gets (.blocks.hashContinue)
+      when (hc == Just b.hash) $ do
+        send (MInv (Inv [InvVector InvBlock e.tip.hash.get])) $
+          netProcessing 1472 "inv of the tip after hashContinue"
+        modifyBlocks (\x -> x {hashContinue = Nothing})
+    filtered blk = do
+      f0 <- gets (.relay.bloom)
+      let step (f, acc) tx = case bloomRelevantUpdate f tx of
+            Just f' -> (f', acc <> [(tx, True)])
+            Nothing -> (f, acc <> [(tx, False)])
+          (f1, marked) = foldl' step (f0, []) blk.txs
+          (flags, hashes) = buildPartialMerkle [(txHash tx, m) | (tx, m) <- marked]
+          mb =
+            MerkleBlock
+              { header = blk.header,
+                txn = fromIntegral (length blk.txs),
+                hashes = hashes,
+                flags = flags
+              }
+      modifyRelay (\r -> r {bloom = f1})
+      send (MMerkleBlock mb) (netProcessing 1414 "MERKLEBLOCK")
+      forM_ [tx | (tx, True) <- marked] $ \tx ->
+        send (MTx tx) (netProcessing 1426 "matched transaction of a merkle block")
+
+-- | @block@ (@src\/net_processing.cpp:3427-3461@): processed with force when
+-- requested from this peer, or from a @noban@ peer out of initial block
+-- download; any peer that sent it can be punished for it.
+receiveBlock :: Block -> M ()
+receiveBlock b = do
+  e <- env
+  noban <- hasPerm PermNoBan
+  let h = headerHash b.header
+  wasInFlight <- markReceived h
+  let force = (noban && not e.initialBlockDownload) || wasInFlight
+  processNewBlock b True force
+
+-- | @ProcessBlockFromNode@ and @BlockChecked@ (@src\/net_processing.cpp:1983-1998@,
+-- @src\/net_processing.cpp:1094-1130@): validation, then a queued @reject@
+-- and misbehaviour for an invalid block when the source can be punished,
+-- or the choice of the peer for high-bandwidth compact blocks when the block
+-- was the only one in flight.
+processNewBlock :: Block -> Bool -> Bool -> M ()
+processNewBlock b punish force = do
+  e <- env
+  let h = headerHash b.header
+  process (if force then "ProcessNewBlock, forced" else "ProcessNewBlock") $
+    netProcessing 1986 "ProcessNewBlock"
+  case e.checkBlock b of
+    BlockAccepted -> do
+      _ <- markReceived h
+      nInFlight <- gets (length . (.blocks.inFlight))
+      when (not e.initialBlockDownload && e.otherBlocksInFlight == 0 && nInFlight == 0) $
+        selectHighBandwidth
+    BlockDuplicate -> ignore (netProcessing 1996 "block already known")
+    BlockMissingParent -> ignore (netProcessing 1105 "prev-blk-not-found: no reject")
+    BlockInvalid blame r -> rejected h 0x10 (if blame then 100 else 0) r
+    BlockRejected code dos r -> rejected h code dos r
+  where
+    rejected h code dos r =
+      when (code > 0) $ do
+        o <- options
+        let msg = rejectMessage MCBlock code r (Just h.get)
+        when o.enableBip61 $
+          forM_ msg $
+            \m -> modify' (\s -> s {blockRejects = s.blockRejects <> [m]})
+        when (dos > 0 && punish) $ misbehaving dos (netProcessing 1114 r)
+
+-- | @MaybeSetPeerAsAnnouncingHeaderAndIDs@ (@src\/net_processing.cpp:560-610@)
+-- for this peer: ask it for high-bandwidth compact blocks if it offers
+-- them. Which peer it replaces among the three is decided across peers.
+selectHighBandwidth :: M ()
+selectHighBandwidth = do
+  bs <- gets (.blocks)
+  when (bs.providesHeaderAndIds && not bs.highBandwidthTo) $ do
+    send (MSendCompact (SendCompact True 1)) (netProcessing 601 "SENDCMPCT high-bandwidth")
+    modifyBlocks (\x -> x {highBandwidthTo = True})
+
+-- | @cmpctblock@ (@src\/net_processing.cpp:3022-3298@).
+receiveCmpctBlock :: CompactBlock -> M ()
+receiveCmpctBlock cb = do
+  e <- env
+  let hdr = cb.header
+      h = headerHash hdr
+  if isNothing (e.lookupBlock hdr.prev)
+    then
+      if e.initialBlockDownload
+        then ignore (netProcessing 3049 "cmpctblock that does not connect, in IBD")
+        else getHeadersFrom e.bestHeader (netProcessing 3043 "cmpctblock that does not connect")
+    else do
+      let receivedNew = isNothing (e.lookupBlock h)
+          parentHeight = maybe 0 (.height) (e.lookupBlock hdr.prev)
+      case e.checkHeaders [hdr] of
+        HeadersRejected dos r -> headerInvalid dos r
+        HeadersInvalid r -> headerInvalid 100 r
+        HeadersUnconnected -> headerInvalid 10 "prev-blk-not-found"
+        HeadersNonContinuous -> headerInvalid 20 "disconnected-header"
+        _ -> withHeader e h receivedNew (blockInfoOf e hdr (parentHeight + 1))
+  where
+    headerInvalid dos r
+      | dos > 0 = misbehaving dos (netProcessing 3067 r)
+      | otherwise = ignore (netProcessing 3069 r)
+    withHeader e h receivedNew info = do
+      t <- nowM
+      updateBlockAvailability h (Just info)
+      when (receivedNew && info.work > e.tip.work) $
+        modifyBlocks (\b -> b {lastBlockAnnouncement = t `div` 1000000})
+      bs <- gets (.blocks)
+      inbound <- isInbound
+      let mine = filter ((== h) . (.inFlightHash)) bs.inFlight
+          requested = not (null mine)
+          elsewhere = e.inFlightElsewhere h
+          alreadyInFlight = elsewhere + (if requested then 1 else 0)
+          firstInFlight = requested && elsewhere == 0
+      if
+        | info.status == HaveData -> ignore (netProcessing 3111 "block already stored")
+        | info.work <= e.tip.work ->
+            if requested
+              then getDataBlock InvBlock h (netProcessing 3129 "cmpctblock of less work, requested")
+              else ignore (netProcessing 3131 "cmpctblock of less work")
+        | alreadyInFlight == 0 && not (canDirectFetch e) ->
+            ignore (netProcessing 3137 "cmpctblock while the tip is old")
+        | info.height <= e.tip.height + 2 ->
+            if (alreadyInFlight < maxCmpctBlocksInflightPerBlock && length bs.inFlight < maxBlocksInTransitPerPeer)
+              || requested
+              then
+                if any (isJust . (.partial)) mine
+                  then ignore (netProcessing 3161 "already syncing this compact block")
+                  else do
+                    if requested
+                      then modifyBlocks $ \b ->
+                        b {inFlight = [if f.inFlightHash == h then f {partial = Just cb} else f | f <- b.inFlight]}
+                      else () <$ markInFlight h True (Just cb)
+                    initData e h firstInFlight inbound alreadyInFlight
+              else reconstruct e
+        | requested -> getDataBlock InvBlock h (netProcessing 3243 "cmpctblock too far ahead, requested")
+        | otherwise -> processHeaders [cb.header] False
+    initData e h firstInFlight inbound alreadyInFlight = do
+      bs <- gets (.blocks)
+      case e.initCompact cb of
+        CompactInvalid -> do
+          _ <- markReceived h
+          misbehaving 100 (netProcessing 3170 "invalid-cmpctblk")
+        CompactFailed
+          | firstInFlight -> getDataBlock InvBlock h (netProcessing 3179 "compact block collision")
+          | otherwise -> () <$ markReceived h
+        -- Nothing is missing: upstream completes the block as if an empty
+        -- @blocktxn@ had come (@src\/net_processing.cpp:3193-3199@).
+        CompactComplete _ -> receiveBlockTxn (BlockTxn h [])
+        CompactMissing [] -> receiveBlockTxn (BlockTxn h [])
+        CompactMissing ixs
+          | firstInFlight
+              || (bs.highBandwidthTo && (not inbound || alreadyInFlight < maxCmpctBlocksInflightPerBlock - 1)) ->
+              send (MGetBlockTxn (GetBlockTxn h ixs)) (netProcessing 3213 "GETBLOCKTXN")
+          | otherwise -> () <$ markReceived h
+    reconstruct e =
+      case e.initCompact cb of
+        CompactComplete blk -> processNewBlock blk False True
+        CompactMissing [] -> case e.fillCompact cb [] of
+          CompactComplete blk -> processNewBlock blk False True
+          _ -> ignore (netProcessing 3227 "compact block not rebuilt from the mempool")
+        _ -> ignore (netProcessing 3227 "compact block not rebuilt from the mempool")
+
+-- | @blocktxn@ (@src\/net_processing.cpp:3300-3391@): completes the compact
+-- block in flight from this peer. An invalid block rebuilt this way is never
+-- punished (BIP 152), but its @reject@ is still sent.
+receiveBlockTxn :: BlockTxn -> M ()
+receiveBlockTxn bt = do
+  e <- env
+  bs <- gets (.blocks)
+  let h = bt.hash
+  case [cb | f <- bs.inFlight, f.inFlightHash == h, Just cb <- [f.partial]] of
+    [] -> ignore (netProcessing 3320 "blocktxn for a block not requested")
+    (cb : _) -> case e.fillCompact cb bt.transactions of
+      CompactInvalid -> do
+        _ <- markReceived h
+        misbehaving 100 (netProcessing 3332 "invalid-cmpctblk-txns")
+      -- A fill that reports missing transactions cannot happen upstream;
+      -- it is taken as a failed fill.
+      CompactMissing _
+        | e.inFlightElsewhere h == 0 ->
+            getDataBlock InvBlock h (netProcessing 3342 "compact block reconstruction failed")
+        | otherwise -> () <$ markReceived h
+      CompactFailed
+        | e.inFlightElsewhere h == 0 ->
+            getDataBlock InvBlock h (netProcessing 3342 "compact block reconstruction failed")
+        | otherwise -> () <$ markReceived h
+      CompactComplete blk -> do
+        _ <- markReceived h
+        processNewBlock blk False True
+
+-- * Notifications
+
+-- | @UpdatedBlockTip@ (@src\/net_processing.cpp:1051-1088@): out of initial
+-- block download, queue up to 8 new blocks for announcement to a peer whose
+-- start height is not far above the new tip.
+updatedBlockTip :: [BlockHeader] -> M ()
+updatedBlockTip hs = do
+  e <- env
+  s <- get
+  unless (e.initialBlockDownload || null hs) $ do
+    let newHeight = maybe e.tip.height (.height) (e.lookupBlock (headerHash (last hs)))
+        floorHeight
+          | s.peerStartHeight /= -1 = fromIntegral s.peerStartHeight - 2000
+          | otherwise = 0 :: Int64
+        hashes = reverse (take maxBlocksToAnnounce (reverse (map headerHash hs)))
+    when (fromIntegral newHeight > floorHeight) $
+      modifyBlocks (\b -> b {toAnnounce = b.toAnnounce <> hashes})
+
+-- | @NewPoWValidBlock@ (@src\/net_processing.cpp:1002-1045@): a new block
+-- that passed the header checks goes as @cmpctblock@ at once to a
+-- high-bandwidth peer of version 70015 or later that has its parent.
+newPoWValidBlock :: BlockHeader -> M ()
+newPoWValidBlock hdr = do
+  e <- env
+  s <- get
+  when (s.peerVersion >= invalidCbNoBanVersion && not s.closing) $ do
+    processBlockAvailability
+    let h = headerHash hdr
+    case (e.lookupBlock h, e.lookupBlock hdr.prev) of
+      (Just b, Just parent) -> do
+        has <- peerHasHeader b
+        hasParent <- peerHasHeader parent
+        when (s.blocks.preferHeaderAndIds && not has && hasParent) $
+          forM_ (e.compactBlockOf h) $ \cb -> do
+            send (MCompactBlock cb) (netProcessing 1041 "fast CMPCTBLOCK announcement")
+            modifyBlocks (\x -> x {bestHeaderSent = Just b})
+      _ -> return ()
+
+-- | The node chose this peer for high-bandwidth compact blocks, or dropped it
+-- for another (@MaybeSetPeerAsAnnouncingHeaderAndIDs@,
+-- @src\/net_processing.cpp:560-610@).
+highBandwidth :: Bool -> M ()
+highBandwidth True = selectHighBandwidth
+highBandwidth False = do
+  bs <- gets (.blocks)
+  when bs.highBandwidthTo $ do
+    send (MSendCompact (SendCompact False 1)) (netProcessing 590 "SENDCMPCT low-bandwidth")
+    modifyBlocks (\x -> x {highBandwidthTo = False})
+
+-- | The rest of the node wants this block from this peer; it is requested at
+-- the next pass of @SendMessages@, where @FindNextBlocksToDownload@ would
+-- have picked it.
+requestBlock :: BlockHash -> M ()
+requestBlock h = modifyBlocks (\b -> b {toRequest = b.toRequest <> [h]})
+
+-- | Another peer's download pass found this peer holding back the window
+-- (@src\/net_processing.cpp:4768-4771@).
+stalling :: M ()
+stalling = do
+  t <- nowM
+  modifyBlocks (\b -> b {stallingSince = if b.stallingSince == 0 then t else b.stallingSince})
+
+-- * SendMessages
+
+-- | Download from this peer if it is preferred, or if no peer is and it
+-- serves blocks (@fFetch@, @src\/net_processing.cpp:4256-4257@).
+fetchFrom :: M Bool
+fetchFrom = do
+  e <- env
+  s <- get
+  return $
+    s.preferredDownload
+      || (e.otherPreferredDownload == 0 && not s.client && s.conn.connectionType /= AddrFetch)
+
+-- | The first @getheaders@ (@src\/net_processing.cpp:4259-4293@): from one
+-- peer during initial block download, from every peer that serves blocks
+-- once the best header is less than a day old.
+initialGetHeaders :: M ()
+initialGetHeaders = do
+  e <- env
+  s <- get
+  fetch <- fetchFrom
+  let t = e.now
+      bestTime = fromIntegral e.bestHeader.time :: Int64
+  when (not s.blocks.syncStarted && not s.client) $
+    when ((e.otherSyncStarted == 0 && fetch) || bestTime > t `div` 1000000 - 24 * 60 * 60) $ do
+      let timeout =
+            t
+              + headersDownloadTimeoutBase
+              + headersDownloadTimeoutPerHeader * (t `div` 1000000 - bestTime) `div` targetSpacing
+          start = fromMaybe e.bestHeader (parentOf e e.bestHeader)
+      modifyBlocks (\b -> b {syncStarted = True, headersSyncTimeout = timeout})
+      getHeadersFrom start (netProcessing 4288 "initial getheaders")
+
+-- | The announcements of new blocks (@src\/net_processing.cpp:4307-4458@):
+-- @headers@ to a peer that sent @sendheaders@, @cmpctblock@ to a
+-- high-bandwidth peer for one block, and otherwise an @inv@ of the last new
+-- block, which goes out with the other @inv@s of the pass.
+blockAnnouncements :: M ()
+blockAnnouncements = do
+  e <- env
+  bs <- gets (.blocks)
+  let q = bs.toAnnounce
+      revert0 =
+        (not bs.preferHeaders && (not bs.preferHeaderAndIds || length q > 1))
+          || length q > maxBlocksToAnnounce
+  processBlockAvailability
+  (revert, best, headers) <-
+    if revert0
+      then return (True, Nothing, [])
+      else collect e q Nothing False []
+  revert' <-
+    if not revert && not (null headers)
+      then do
+        bs' <- gets (.blocks)
+        if
+          | length headers == 1 && bs'.preferHeaderAndIds,
+            Just b <- best,
+            Just cb <- e.compactBlockOf b.hash -> do
+              send (MCompactBlock cb) (netProcessing 4393 "header-and-ids announcement")
+              modifyBlocks (\x -> x {bestHeaderSent = best})
+              return False
+          | bs'.preferHeaders -> do
+              send (MHeaders (Headers [(h, VarInt 0) | h <- headers])) $
+                netProcessing 4423 "headers announcement"
+              modifyBlocks (\x -> x {bestHeaderSent = best})
+              return False
+          | otherwise -> return True
+      else return revert
+  when (revert' && not (null q)) $ do
+    let h = last q
+    case e.lookupBlock h of
+      Just b -> do
+        has <- peerHasHeader b
+        unless has $ modifyBlocks (\x -> x {blockInvs = x.blockInvs <> [h]})
+      Nothing -> return ()
+  modifyBlocks (\x -> x {toAnnounce = []})
+  where
+    collect _ [] best _ acc = return (False, best, reverse acc)
+    collect e (h : rest) best found acc =
+      case e.lookupBlock h of
+        Nothing -> return (True, best, [])
+        Just b
+          | not b.inActiveChain -> return (True, best, [])
+          | Just p <- best,
+            fmap (.prev) (e.headerOf h) /= Just p.hash ->
+              return (True, best, [])
+          | otherwise -> do
+              let hdr = e.headerOf h
+              if found
+                then collect e rest (Just b) True (maybe acc (: acc) hdr)
+                else do
+                  has <- peerHasHeader b
+                  if has
+                    then collect e rest (Just b) False acc
+                    else do
+                      parentKnown <- case parentOf e b of
+                        Nothing -> return (b.height == 0)
+                        Just p -> peerHasHeader p
+                      if parentKnown
+                        then collect e rest (Just b) True (maybe acc (: acc) hdr)
+                        else return (True, best, [])
+
+-- | The timers of block download, in upstream order
+-- (@src\/net_processing.cpp:4656-4730@): stalling, the download timeout and
+-- the headers sync timeout. Returns whether the peer was disconnected,
+-- which ends the pass.
+downloadTimers :: M Bool
+downloadTimers = do
+  e <- env
+  bs <- gets (.blocks)
+  noban <- hasPerm PermNoBan
+  pref <- gets (.preferredDownload)
+  let t = e.now
+      perPeer = 1000000 + 500000 * fromIntegral e.otherValidatedDownloads
+      deadline = bs.downloadingSince + targetSpacing * perPeer
+      bestTime = fromIntegral e.bestHeader.time :: Int64
+  if
+    | bs.stallingSince /= 0 && bs.stallingSince < t - blockStallingTimeout -> do
+        disconnect Timeout (netProcessing 4665 "is stalling block download")
+        return True
+    | not (null bs.inFlight) && t > deadline -> do
+        disconnect Timeout (netProcessing 4688 "Timeout downloading block")
+        return True
+    | bs.syncStarted && bs.headersSyncTimeout < maxBound ->
+        if bestTime <= t `div` 1000000 - 24 * 60 * 60
+          then
+            if t > bs.headersSyncTimeout && e.otherSyncStarted == 0 && e.otherPreferredDownload >= 1
+              then
+                if not noban
+                  then do
+                    disconnect Timeout (netProcessing 4710 "Timeout downloading headers")
+                    return True
+                  else do
+                    _ <- return pref
+                    modifyBlocks (\b -> b {syncStarted = False, headersSyncTimeout = 0})
+                    process "headers sync restarts with another peer" $
+                      netProcessing 4720 "Timeout downloading headers from whitelisted peer"
+                    return False
+              else return False
+          else do
+            modifyBlocks (\b -> b {headersSyncTimeout = maxBound})
+            return False
+    | otherwise -> return False
+
+-- | The chain-sync check of outbound peers (@ConsiderEviction@,
+-- @src\/net_processing.cpp:3951-4035@): an outbound full-relay peer whose best
+-- block has less work than our tip gets 20 minutes to catch up, then one
+-- @getheaders@ and two more minutes, then is disconnected. Manual, feeler,
+-- address-fetch and inbound peers are exempt, and so are up to four
+-- protected peers.
+considerEviction :: M ()
+considerEviction = do
+  e <- env
+  s <- get
+  let cs = s.blocks.chainSync
+      t = e.now `div` 1000000
+      ct = s.conn.connectionType
+      bk = s.blocks.bestKnown
+      caughtUp = maybe False (\b -> b.work >= e.tip.work) bk
+  when (not cs.protect && ct `elem` [OutboundFullRelay, BlockRelayOnly] && s.blocks.syncStarted) $
+    if
+      | caughtUp ->
+          when (cs.syncTimeout /= 0) $
+            setCs (ChainSync 0 Nothing False cs.protect)
+      | cs.syncTimeout == 0
+          || ( case (cs.workHeader, bk) of
+                 (Just w, Just b) -> b.work >= w.work
+                 _ -> False
+             ) ->
+          setCs (ChainSync (t + chainSyncTimeout) (Just e.tip) False cs.protect)
+      | cs.syncTimeout > 0 && t > cs.syncTimeout ->
+          if cs.sentGetHeaders
+            then disconnect Timeout (netProcessing 4001 "chain sync timeout: for old chain")
+            else do
+              let w = fromMaybe e.tip cs.workHeader
+                  from = fromMaybe w (parentOf e w)
+              getHeadersFrom from (netProcessing 4015 "getheaders for the chain-sync check")
+              setCs (ChainSync (t + headersResponseTime) cs.workHeader True cs.protect)
+      | otherwise -> return ()
+  where
+    setCs c = modifyBlocks (\b -> b {chainSync = c})
+
+-- | The blocks to request in this pass (@src\/net_processing.cpp:4753-4774@):
+-- those the rest of the node asked for, while the peer serves blocks and
+-- has fewer than 16 in flight. Returns the entries of the @getdata@.
+blockRequests :: M [InvVector]
+blockRequests = do
+  e <- env
+  s <- get
+  fetch <- fetchFrom
+  let ok =
+        not s.client
+          && ((fetch && not s.limitedNode) || not e.initialBlockDownload)
+  if not ok
+    then return []
+    else do
+      let q = s.blocks.toRequest
+      modifyBlocks (\b -> b {toRequest = []})
+      concat <$> mapM one q
+  where
+    one h = do
+      n <- gets (length . (.blocks.inFlight))
+      if n >= maxBlocksInTransitPerPeer
+        then return []
+        else do
+          e <- env
+          new <- markInFlight h (isJust (e.lookupBlock h)) Nothing
+          return [InvVector InvBlock h.get | new]
diff --git a/src/Haskoin/Network/Protocol/BitcoinCashNode/Constants.hs b/src/Haskoin/Network/Protocol/BitcoinCashNode/Constants.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Network/Protocol/BitcoinCashNode/Constants.hs
@@ -0,0 +1,366 @@
+{-# LANGUAGE OverloadedStrings #-}
+
+-- |
+-- Module      : Haskoin.Network.Protocol.BitcoinCashNode.Constants
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- The constants of Bitcoin Cash Node 29.2.0 that decide what a peer sees,
+-- each with the file and line of the upstream source that defines it, and the
+-- helpers that build a 'Cite' into that source.
+--
+-- The values are copied, not computed, so that a reader can check each one
+-- against the upstream line named next to it. When a new upstream release
+-- changes one, the line moves too: the report @doc\/protocol\/bitcoin-cash-node.md@
+-- says how to bring both forward together.
+module Haskoin.Network.Protocol.BitcoinCashNode.Constants
+  ( -- * Citing the source
+    netProcessing,
+    netCpp,
+    netH,
+    protocolCpp,
+
+    -- * Protocol versions (@src\/version.h@)
+    protocolVersion,
+    minPeerProtoVersion,
+    bip0031Version,
+    noBloomVersion,
+    sendHeadersVersion,
+    feeFilterVersion,
+    shortIdsBlocksVersion,
+    invalidCbNoBanVersion,
+    featureNegotiationVersion,
+
+    -- * Service bits (@src\/protocol.h@)
+    nodeNetwork,
+    nodeBloom,
+    nodeBitcoinCash,
+    nodeNetworkLimited,
+    nodeExtVersion,
+
+    -- * Limits
+    maxInvSize,
+    maxAddrToSend,
+    maxLocatorSize,
+    maxHeadersResults,
+    maxBlocksToAnnounce,
+    maxUnconnectingHeaders,
+    maxBlocksInTransitPerPeer,
+    maxCmpctBlocksInflightPerBlock,
+    maxCmpctBlockDepth,
+    nodeNetworkLimitedMinBlocks,
+    maxRejectMessageLength,
+    maxBloomFilterSize,
+    maxHashFuncs,
+    maxScriptElementSize,
+    maxPeerTxAnnouncements,
+    maxPeerTxRequestInFlight,
+    maxDsProofGetDatas,
+    maxGetDataSize,
+    maxMoney,
+    extVersionMaxSize,
+    extVersionMaxKeys,
+    maxOutboundPeersToProtect,
+
+    -- * Times
+    pingInterval,
+    timeoutInterval,
+    oldPeerReceiveTimeout,
+    blockStallingTimeout,
+    headersDownloadTimeoutBase,
+    headersDownloadTimeoutPerHeader,
+    chainSyncTimeout,
+    headersResponseTime,
+    staleRelayAge,
+    historicalBlockAge,
+    nonPrefPeerTxDelay,
+    overloadedPeerTxDelay,
+    getDataTxInterval,
+    avgAddressBroadcastInterval,
+    avgLocalAddressBroadcastInterval,
+    avgFeeFilterBroadcastInterval,
+    maxFeeFilterChangeDelay,
+    targetSpacing,
+
+    -- * Address relay
+    maxAddrRatePerSecond,
+    maxAddrProcessingTokenBucket,
+
+    -- * Inventory types (@src\/protocol.h@)
+    msgDoubleSpendProof,
+
+    -- * Commands that the library does not know
+    extVersionCommand,
+    dsProofCommand,
+  )
+where
+
+import Data.ByteString (ByteString)
+import Data.Int (Int64)
+import Data.Text (Text)
+import Data.Word (Word32, Word64)
+import Haskoin.Network.Protocol.Types (Cite, Micros, cite, seconds)
+
+-- | A place in @src\/net_processing.cpp@, where most decisions are made.
+netProcessing :: Int -> Text -> Cite
+netProcessing = cite "src/net_processing.cpp"
+
+-- | A place in @src\/net.cpp@: sockets, timeouts, connections.
+netCpp :: Int -> Text -> Cite
+netCpp = cite "src/net.cpp"
+
+-- | A place in @src\/net.h@.
+netH :: Int -> Text -> Cite
+netH = cite "src/net.h"
+
+-- | A place in @src\/protocol.cpp@: message headers and service flags.
+protocolCpp :: Int -> Text -> Cite
+protocolCpp = cite "src/protocol.cpp"
+
+-- | @PROTOCOL_VERSION@, @src\/version.h:11@.
+protocolVersion :: Int
+protocolVersion = 70016
+
+-- | @MIN_PEER_PROTO_VERSION@, @src\/version.h:17@: older peers are
+-- disconnected.
+minPeerProtoVersion :: Int
+minPeerProtoVersion = 31800
+
+-- | @BIP0031_VERSION@, @src\/version.h:20@: peers above it get pings with a
+-- nonce and answer them.
+bip0031Version :: Int
+bip0031Version = 60000
+
+-- | @NO_BLOOM_VERSION@, @src\/version.h:24@: from this version, Bloom
+-- messages to a node that does not offer them are misbehaviour.
+noBloomVersion :: Int
+noBloomVersion = 70011
+
+-- | @SENDHEADERS_VERSION@, @src\/version.h:28@.
+sendHeadersVersion :: Int
+sendHeadersVersion = 70012
+
+-- | @FEEFILTER_VERSION@, @src\/version.h:32@.
+feeFilterVersion :: Int
+feeFilterVersion = 70013
+
+-- | @SHORT_IDS_BLOCKS_VERSION@, @src\/version.h:35@.
+shortIdsBlocksVersion :: Int
+shortIdsBlocksVersion = 70014
+
+-- | @INVALID_CB_NO_BAN_VERSION@, @src\/version.h:38@: fast compact block
+-- announcements go only to peers of this version or later.
+invalidCbNoBanVersion :: Int
+invalidCbNoBanVersion = 70015
+
+-- | @FEATURE_NEGOTIATION_BEFORE_VERACK_VERSION@, @src\/version.h:47@: the
+-- node sends @sendaddrv2@ before its @verack@ to peers of this version.
+featureNegotiationVersion :: Int
+featureNegotiationVersion = 70016
+
+-- | @NODE_NETWORK@, @src\/protocol.h@.
+nodeNetwork :: Word64
+nodeNetwork = 1
+
+-- | @NODE_BLOOM@, @src\/protocol.h@.
+nodeBloom :: Word64
+nodeBloom = 4
+
+-- | @NODE_BITCOIN_CASH@, @src\/protocol.h@.
+nodeBitcoinCash :: Word64
+nodeBitcoinCash = 32
+
+-- | @NODE_NETWORK_LIMITED@, @src\/protocol.h@.
+nodeNetworkLimited :: Word64
+nodeNetworkLimited = 1024
+
+-- | @NODE_EXTVERSION@, @src\/protocol.h@.
+nodeExtVersion :: Word64
+nodeExtVersion = 2048
+
+-- | @MAX_INV_SZ@, @src\/net.h:68@.
+maxInvSize :: Int
+maxInvSize = 50000
+
+-- | @MAX_ADDR_TO_SEND@, @src\/net.h:75@.
+maxAddrToSend :: Int
+maxAddrToSend = 1000
+
+-- | @MAX_LOCATOR_SZ@, @src\/net.h:73@.
+maxLocatorSize :: Int
+maxLocatorSize = 101
+
+-- | @MAX_HEADERS_RESULTS@, @src\/validation.h:111@.
+maxHeadersResults :: Int
+maxHeadersResults = 2000
+
+-- | @MAX_BLOCKS_TO_ANNOUNCE@, @src\/validation.h:161@.
+maxBlocksToAnnounce :: Int
+maxBlocksToAnnounce = 8
+
+-- | @MAX_UNCONNECTING_HEADERS@, @src\/validation.h:164@.
+maxUnconnectingHeaders :: Int
+maxUnconnectingHeaders = 10
+
+-- | @MAX_BLOCKS_IN_TRANSIT_PER_PEER@, @src\/validation.h:100@.
+maxBlocksInTransitPerPeer :: Int
+maxBlocksInTransitPerPeer = 16
+
+-- | @MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK@, @src\/net_processing.h:61@.
+maxCmpctBlocksInflightPerBlock :: Int
+maxCmpctBlocksInflightPerBlock = 3
+
+-- | @MAX_CMPCTBLOCK_DEPTH@, @src\/validation.h:116@.
+maxCmpctBlockDepth :: Word32
+maxCmpctBlockDepth = 5
+
+-- | @NODE_NETWORK_LIMITED_MIN_BLOCKS@, @src\/validation.h:241@.
+nodeNetworkLimitedMinBlocks :: Word32
+nodeNetworkLimitedMinBlocks = 288
+
+-- | @MAX_REJECT_MESSAGE_LENGTH@, @src\/validation.h:130@.
+maxRejectMessageLength :: Int
+maxRejectMessageLength = 111
+
+-- | @MAX_BLOOM_FILTER_SIZE@, @src\/bloom.h:18@.
+maxBloomFilterSize :: Int
+maxBloomFilterSize = 36000
+
+-- | @MAX_HASH_FUNCS@, @src\/bloom.h:19@.
+maxHashFuncs :: Word32
+maxHashFuncs = 50
+
+-- | @MAX_SCRIPT_ELEMENT_SIZE_LEGACY@, @src\/script\/vm_limits.h:10@: the
+-- largest item of a @filteradd@.
+maxScriptElementSize :: Int
+maxScriptElementSize = 520
+
+-- | @MAX_PEER_TX_ANNOUNCEMENTS@, @src\/net_processing.cpp:104@.
+maxPeerTxAnnouncements :: Int
+maxPeerTxAnnouncements = 100000
+
+-- | @MAX_PEER_TX_REQUEST_IN_FLIGHT@, @src\/net_processing.cpp:102@.
+maxPeerTxRequestInFlight :: Int
+maxPeerTxRequestInFlight = 100
+
+-- | @MAX_DSPROOF_GET_DATAS_TO_BATCH@, @src\/net_processing.cpp:146@.
+maxDsProofGetDatas :: Int
+maxDsProofGetDatas = 5000
+
+-- | @MAX_GETDATA_SZ@, @src\/net_processing.cpp:115@.
+maxGetDataSize :: Int
+maxGetDataSize = 1000
+
+-- | @MAX_MONEY@ in satoshi, the bound of @MoneyRange@ (@src\/amount.h@).
+maxMoney :: Word64
+maxMoney = 21000000 * 100000000
+
+-- | @extversion::Message::MaxSize()@, @src\/extversion.h:117@.
+extVersionMaxSize :: Int
+extVersionMaxSize = 100000
+
+-- | @extversion::Message::MaxNumKeys()@, @src\/extversion.h:120@.
+extVersionMaxKeys :: Word64
+extVersionMaxKeys = 8192
+
+-- | @MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT@,
+-- @src\/net_processing.cpp:73@.
+maxOutboundPeersToProtect :: Int
+maxOutboundPeersToProtect = 4
+
+-- | @PING_INTERVAL@, @src\/net.h:59@.
+pingInterval :: Micros
+pingInterval = seconds 120
+
+-- | @TIMEOUT_INTERVAL@, @src\/net.h:64@.
+timeoutInterval :: Micros
+timeoutInterval = seconds 1200
+
+-- | The receive timeout of peers of version 60000 or less,
+-- @src\/net.cpp:1287@.
+oldPeerReceiveTimeout :: Micros
+oldPeerReceiveTimeout = seconds (90 * 60)
+
+-- | @BLOCK_STALLING_TIMEOUT@, @src\/validation.h:105@.
+blockStallingTimeout :: Micros
+blockStallingTimeout = seconds 2
+
+-- | @HEADERS_DOWNLOAD_TIMEOUT_BASE@, @src\/net_processing.cpp:66@.
+headersDownloadTimeoutBase :: Micros
+headersDownloadTimeoutBase = seconds (15 * 60)
+
+-- | @HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER@, @src\/net_processing.cpp:68@.
+headersDownloadTimeoutPerHeader :: Micros
+headersDownloadTimeoutPerHeader = 1000
+
+-- | @CHAIN_SYNC_TIMEOUT@ in seconds, @src\/net_processing.cpp:79@.
+chainSyncTimeout :: Int64
+chainSyncTimeout = 20 * 60
+
+-- | @HEADERS_RESPONSE_TIME@ in seconds, @src\/net_processing.cpp:4023@.
+headersResponseTime :: Int64
+headersResponseTime = 120
+
+-- | @STALE_RELAY_AGE_LIMIT@ in seconds, @src\/net_processing.cpp:96@.
+staleRelayAge :: Int64
+staleRelayAge = 30 * 24 * 60 * 60
+
+-- | @HISTORICAL_BLOCK_AGE@ in seconds, @src\/net_processing.cpp:99@.
+historicalBlockAge :: Int64
+historicalBlockAge = 7 * 24 * 60 * 60
+
+-- | @NONPREF_PEER_TX_DELAY@, @src\/net_processing.cpp:106@.
+nonPrefPeerTxDelay :: Micros
+nonPrefPeerTxDelay = seconds 2
+
+-- | @OVERLOADED_PEER_TX_DELAY@, @src\/net_processing.cpp:108@.
+overloadedPeerTxDelay :: Micros
+overloadedPeerTxDelay = seconds 2
+
+-- | @GETDATA_TX_INTERVAL@, @src\/net_processing.cpp:110@.
+getDataTxInterval :: Micros
+getDataTxInterval = seconds 60
+
+-- | @AVG_ADDRESS_BROADCAST_INTERVAL@, @src\/net_processing.cpp:127@.
+avgAddressBroadcastInterval :: Micros
+avgAddressBroadcastInterval = seconds 30
+
+-- | @AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL@, @src\/net_processing.cpp:123@.
+avgLocalAddressBroadcastInterval :: Micros
+avgLocalAddressBroadcastInterval = seconds (24 * 60 * 60)
+
+-- | @AVG_FEEFILTER_BROADCAST_INTERVAL@, @src\/net_processing.cpp:131@.
+avgFeeFilterBroadcastInterval :: Micros
+avgFeeFilterBroadcastInterval = seconds (10 * 60)
+
+-- | @MAX_FEEFILTER_CHANGE_DELAY@, @src\/net_processing.cpp:135@.
+maxFeeFilterChangeDelay :: Micros
+maxFeeFilterChangeDelay = seconds (5 * 60)
+
+-- | @nPowTargetSpacing@ in seconds: 600 on every chain of Bitcoin Cash Node
+-- (@src\/chainparams.cpp@), which the timers of block download use.
+targetSpacing :: Int64
+targetSpacing = 600
+
+-- | @MAX_ADDR_RATE_PER_SECOND@, @src\/net.h:80@.
+maxAddrRatePerSecond :: Double
+maxAddrRatePerSecond = 0.1
+
+-- | @MAX_ADDR_PROCESSING_TOKEN_BUCKET@, @src\/net.h:86@.
+maxAddrProcessingTokenBucket :: Double
+maxAddrProcessingTokenBucket = 1000
+
+-- | @MSG_DOUBLESPENDPROOF@, @src\/protocol.h:453@.
+msgDoubleSpendProof :: Word32
+msgDoubleSpendProof = 0x94a0
+
+-- | The command of the @extversion@ message, @src\/protocol.cpp:51@.
+extVersionCommand :: ByteString
+extVersionCommand = "extversion"
+
+-- | The command of the double-spend proof message, @src\/protocol.cpp:52@.
+dsProofCommand :: ByteString
+dsProofCommand = "dsproof-beta"
diff --git a/src/Haskoin/Network/Protocol/BitcoinCashNode/Handshake.hs b/src/Haskoin/Network/Protocol/BitcoinCashNode/Handshake.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Network/Protocol/BitcoinCashNode/Handshake.hs
@@ -0,0 +1,558 @@
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE MultiWayIf #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- |
+-- Module      : Haskoin.Network.Protocol.BitcoinCashNode.Handshake
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- The life of a connection in Bitcoin Cash Node 29.2.0: framing errors, the
+-- handshake (@version@, @extversion@, @verack@, @sendaddrv2@), @reject@,
+-- @ping@ and @pong@, the ban score and what the node does when it crosses
+-- @-banscore@, and the inactivity timeouts.
+--
+-- Each handler translates one upstream block of code, named in its
+-- documentation with the file and lines. The order of the checks inside a
+-- handler is the upstream order, because it decides what a peer sees when a
+-- message breaks more than one rule: a @version@ from a peer that is both
+-- too old and lacks the required services gets the @reject@ about services,
+-- which upstream checks first.
+--
+-- The handshake differs from Bitcoin Core in three ways a peer can see:
+--
+-- * Bitcoin Cash Node still sends BIP 61 @reject@ messages by default.
+-- * It has its own @extversion@ handshake, used when both sides offer
+--   @NODE_EXTVERSION@; then @extversion@ takes the place of @sendaddrv2@ and
+--   @verack@ in the answer to @version@.
+-- * It scores misbehaviour with integers, and acts on the score only when it
+--   crosses @-banscore@.
+module Haskoin.Network.Protocol.BitcoinCashNode.Handshake
+  ( initializeNode,
+    frameError,
+    bloomPrologue,
+    receiveReject,
+    receiveVersion,
+    duplicateVersion,
+    missingVersion,
+    receiveExtVersion,
+    receiveVerAck,
+    receiveSendAddrV2,
+    priorToVerAck,
+    receivePing,
+    receivePong,
+    unknownCommand,
+    parseError,
+    sendRejectsAndCheckIfShouldDiscourage,
+    inactivityCheck,
+    sendPing,
+    sanitizeString,
+    hasAllDesirableServices,
+  )
+where
+
+import Control.Monad (forM_, replicateM, unless, when)
+import Control.Monad.RWS.Strict (get, gets, modify')
+import Data.Bits ((.&.))
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as BS
+import Data.ByteString.Char8 qualified as C
+import Data.Bytes.Get (getByteString, runGetS)
+import Data.Bytes.Serial (deserialize)
+import Data.Int (Int64)
+import Data.Text qualified as T
+import Data.Text.Encoding qualified as TE
+import Data.Word (Word64)
+import Haskoin.Network.Common
+  ( MessageCommand (..),
+    NetworkAddress (..),
+    Ping (..),
+    Pong (..),
+    VarInt (..),
+    VarString (..),
+    Version (..),
+    sockToHostAddress,
+  )
+import Haskoin.Network.CompactBlock (SendCompact (..))
+import Haskoin.Network.Message (Message (..))
+import Haskoin.Network.Protocol.BitcoinCashNode.Constants
+import Haskoin.Network.Protocol.BitcoinCashNode.Options
+import Haskoin.Network.Protocol.BitcoinCashNode.State
+import Haskoin.Network.Protocol.Types
+import Network.Socket (SockAddr (..))
+import Numeric (showHex)
+
+-- | Send our @version@ to a peer that the node connected to, which upstream
+-- does as soon as the connection opens (@InitializeNode@,
+-- @src\/net_processing.cpp:799-801@). The machine has no effect at @start@,
+-- so it sends the @version@ before whatever the first input does.
+initializeNode :: M ()
+initializeNode = do
+  s <- get
+  when (isOutbound s.conn.connectionType && not s.versionSent) $
+    pushNodeVersion (netProcessing 800 "InitializeNode: version to an outbound peer")
+
+-- | Our @version@ (@PushNodeVersion@, @src\/net_processing.cpp:761-785@):
+-- protocol 70016, the services offered to this peer, the time, the peer's
+-- address (unknown to the machine, so the null address), a null address of
+-- ours with our services, our nonce, our user agent, our height and the relay
+-- flag, false in blocks-only mode.
+pushNodeVersion :: Cite -> M ()
+pushNodeVersion c = do
+  o <- options
+  e <- env
+  s <- get
+  let none = sockToHostAddress (SockAddrInet6 0 0 (0, 0, 0, 0) 0)
+      v =
+        Version
+          { version = fromIntegral protocolVersion,
+            services = s.ourServices,
+            timestamp = e.now `div` 1000000,
+            addrRecv = NetworkAddress 0 none,
+            addrSend = NetworkAddress s.ourServices none,
+            nonce = s.localNonce,
+            userAgent = VarString (subVersion o),
+            startHeight = fromIntegral e.tip.height,
+            relay = not o.blocksOnly
+          }
+  modify' (\st -> st {versionSent = True})
+  send (MVersion v) c
+
+-- | What a framing error does (@CNode::ReceiveMsgBytes@ and
+-- @PeerLogicValidation::ProcessMessages@):
+--
+-- * a header of a message that is too large closes the connection as soon as
+--   it arrives, without misbehaviour (@src\/net.cpp:689@);
+-- * the magic of another network discourages the address and closes every
+--   connection from it, whatever the permissions of the peer
+--   (@src\/net_processing.cpp:3876-3888@);
+-- * a bad command drops the message (@src\/net_processing.cpp:3892-3896@);
+-- * a bad checksum discourages the address and closes its connections, whatever
+--   the permissions (@src\/net_processing.cpp:3902-3914@).
+--
+-- A payload that does not parse is not a framing error upstream: it reaches
+-- the handler of its command, which throws. The top module routes
+-- 'BadPayload' there.
+frameError :: FrameError -> M ()
+frameError = \case
+  WrongMagic _ -> do
+    emit Discourage (netProcessing 3882 "PROCESSMESSAGE: INVALID MESSAGESTART")
+    disconnect ProtocolViolation (netProcessing 3884 "DisconnectNode(pfrom->addr)")
+  BadCommand _ ->
+    ignore (netProcessing 3893 "PROCESSMESSAGE: ERRORS IN HEADER")
+  Oversized _ _ ->
+    disconnect ProtocolViolation (netCpp 689 "Oversized header detected")
+  BadChecksum _ -> do
+    emit Discourage (netProcessing 3910 "CHECKSUM ERROR")
+    disconnect ProtocolViolation (netProcessing 3912 "DisconnectNode(pfrom->addr)")
+  BadPayload _ ->
+    -- routed by the top module; never reached
+    return ()
+
+-- | @filterload@ and @filteradd@ when the node does not offer @NODE_BLOOM@ to
+-- this peer, checked before anything else, even before @version@
+-- (@src\/net_processing.cpp:2012-2023@): misbehaviour of 100 from a peer of
+-- version 70011 or later, else a plain disconnect. Returns whether it acted.
+bloomPrologue :: M Bool
+bloomPrologue = do
+  o <- options
+  s <- get
+  if offersBloom o s.perms
+    then return False
+    else do
+      if s.peerVersion >= noBloomVersion
+        then misbehaving 100 (netProcessing 2017 "no-bloom-version")
+        else disconnect ProtocolViolation (netProcessing 2020 "bloom message without NODE_BLOOM")
+      return True
+
+-- | A @reject@ is only logged, in any state, even before @version@
+-- (@src\/net_processing.cpp:2025-2051@). A @reject@ that does not parse is
+-- caught there too, so that it never draws a @reject@ back.
+receiveReject :: M ()
+receiveReject = ignore (netProcessing 2050 "Reject")
+
+-- | Any message but @version@, @reject@ and the Bloom case before @version@
+-- (@src\/net_processing.cpp:2308-2313@).
+missingVersion :: M ()
+missingVersion = misbehaving 10 (netProcessing 2311 "missing-version")
+
+-- | The checks of @version@ in upstream order (@src\/net_processing.cpp:2053-2306@).
+receiveVersion :: Version -> M ()
+receiveVersion v = do
+  o <- options
+  e <- env
+  s <- get
+  inbound <- isInbound
+  noban <- hasPerm PermNoBan
+  let ver = fromIntegral v.version :: Int
+      nTime = max 0 v.timestamp
+      ct = s.conn.connectionType
+      subver = sanitizeString v.userAgent
+      beforeParen = fst (BS.break (== 0x28) subver)
+      rejected =
+        [ r
+        | r <- o.rejectSubVersions,
+          not (BS.null r),
+          r `BS.isInfixOf` beforeParen
+        ]
+  if s.peerVersion /= 0
+    then duplicateVersion
+    else do
+      unless inbound $
+        process "record the services of the peer in addrman" $
+          netProcessing 2087 "SetServices"
+      let desirable = desirableServices e v.services
+      if expectServices ct && not (hasAllDesirableServices e v.services)
+        then do
+          sendReject MCVersion 0x40 (T.pack ("Expected to offer services " <> hex8 desirable)) Nothing $
+            netProcessing 2100 "does not offer the expected services"
+          disconnect Unsuitable (netProcessing 2104 "does not offer the expected services")
+        else
+          if ver < minPeerProtoVersion
+            then do
+              sendReject MCVersion 0x11 "Version must be 31800 or greater" Nothing $
+                netProcessing 2117 "using obsolete version"
+              disconnect Unsuitable (netProcessing 2121 "using obsolete version")
+            else
+              if not (null rejected) && ct /= Manual && not noban
+                then disconnect Unsuitable (netProcessing 2148 "-rejectsubversion")
+                else
+                  if inbound && e.ownNonce v.nonce
+                    then disconnect ProtocolViolation (netProcessing 2165 "connected to self")
+                    else accept o e inbound v nTime subver
+  where
+    hex8 w = let h = showHex w "" in replicate (8 - length h) '0' <> h
+
+-- | A second @version@ (@src\/net_processing.cpp:2054-2066@): a @reject@
+-- and a score of 1, checked before the payload is read.
+duplicateVersion :: M ()
+duplicateVersion = do
+  sendReject MCVersion 0x12 "Duplicate version message" Nothing $
+    netProcessing 2060 "Duplicate version message"
+  misbehaving 1 (netProcessing 2064 "multiple-version")
+
+-- | The part of @version@ after the checks that can refuse it
+-- (@src\/net_processing.cpp:2169-2305@).
+accept :: Options -> Env -> Bool -> Version -> Int64 -> ByteString -> M ()
+accept o e inbound v nTime subver = do
+  s0 <- get
+  let ct = s0.conn.connectionType
+      ver = fromIntegral v.version :: Int
+      vServices = v.services
+  when inbound $
+    pushNodeVersion (netProcessing 2175 "PushNodeVersion to an inbound peer")
+  modify' (\s -> s {peerServices = vServices})
+  if vServices .&. nodeExtVersion /= 0 && o.useExtVersion
+    then do
+      send (MOther extVersionCommand ourExtVersion) $
+        netProcessing 2193 "extversion instead of verack"
+      modify' (\s -> s {extVersionExpected = True})
+    else pushVerAck ver (netProcessing 2197 "PushVerACK")
+  noban <- hasPerm PermNoBan
+  let isClient = vServices .&. nodeNetwork == 0 && vServices .&. nodeNetworkLimited == 0
+      isLimited = vServices .&. nodeNetwork == 0 && vServices .&. nodeNetworkLimited /= 0
+  modify' $ \s ->
+    s
+      { peerSubVer = TE.decodeLatin1 subver,
+        peerStartHeight = v.startHeight,
+        client = isClient,
+        limitedNode = isLimited,
+        peerVersion = ver,
+        preferredDownload = (not inbound || noban) && ct /= AddrFetch && not isClient
+      }
+  modifyRelay (\r -> r {relayTxes = v.relay})
+  when (not inbound && ct /= BlockRelayOnly) $ do
+    when (o.listen && not e.initialBlockDownload) $
+      forM_ e.localAddress $ \a -> do
+        pushAddress a
+        process "advertise our address" (netProcessing 2257 "advertising address")
+    pushGetAddrOnce (netProcessing 2267 "PushGetAddrOnceIfAfterVerAck")
+    process "mark the address good in addrman" (netProcessing 2271 "MarkAddressGood")
+  let offset = nTime - e.now `div` 1000000
+  modify' (\s -> s {timeOffset = offset})
+  if nTime < genesisTime o
+    then
+      misbehaving 20 $
+        netProcessing 2293 "Ignoring invalid timestamp in version message"
+    else
+      unless inbound $
+        process "sample the clock of the peer" (netProcessing 2298 "AddTimeData")
+  when (ct == Feeler) $
+    disconnect Done (netProcessing 2303 "feeler connection done")
+
+-- | Our @extversion@: a map with the key 0 (version) set to 100, which is
+-- version 0.1.0 (@src\/extversion.h:50-52,75@).
+ourExtVersion :: ByteString
+ourExtVersion = BS.pack [0x01, 0x00, 0x01, 0x64]
+
+-- | The services the node wants from an outbound peer
+-- (@GetDesirableServiceFlags@, @src\/protocol.cpp:184-190@):
+-- @NODE_NETWORK_LIMITED@ suffices out of initial block download, if the peer
+-- offers it.
+desirableServices :: Env -> Word64 -> Word64
+desirableServices e srv
+  | srv .&. nodeNetworkLimited /= 0 && not e.initialBlockDownload = nodeNetworkLimited
+  | otherwise = nodeNetwork
+
+-- | The peer offers all the services the node wants
+-- (@HasAllDesirableServiceFlags@, @src\/protocol.h@).
+hasAllDesirableServices :: Env -> Word64 -> Bool
+hasAllDesirableServices e srv =
+  let d = desirableServices e srv in srv .&. d == d
+
+-- | Connections that must offer the desirable services
+-- (@ExpectServicesFromConn@, @src\/net.h:1078-1091@).
+expectServices :: ConnectionType -> Bool
+expectServices = \case
+  OutboundFullRelay -> True
+  BlockRelayOnly -> True
+  AddrFetch -> True
+  _ -> False
+
+-- | @sendaddrv2@ to peers of version 70016 or later, then @verack@
+-- (@PushVerACK@, @src\/net_processing.cpp:1890-1902@). A version of 0 means
+-- the peer's.
+pushVerAck :: Int -> Cite -> M ()
+pushVerAck ver0 _ = do
+  pv <- gets (.peerVersion)
+  let ver = if ver0 == 0 then pv else ver0
+  when (ver >= featureNegotiationVersion) $
+    send MSendAddrV2 (netProcessing 1897 "PushVerACK: SENDADDRV2")
+  send MVerAck (netProcessing 1901 "PushVerACK: VERACK")
+  modify' (\s -> s {verAckSent = True})
+
+-- | @getaddr@ once to a peer the node connected to, after our @verack@
+-- (@PushGetAddrOnceIfAfterVerAck@, @src\/net_processing.cpp:1870-1883@). It
+-- opens the address token bucket by 1000 for the reply.
+pushGetAddrOnce :: Cite -> M ()
+pushGetAddrOnce _ = do
+  s <- get
+  inbound <- isInbound
+  when (not inbound && s.verAckSent && not s.getAddrSent) $ do
+    send MGetAddr (netProcessing 1875 "PushGetAddrOnceIfAfterVerAck: GETADDR")
+    modify' (\st -> st {getAddrSent = True})
+    modifyRelay $ \r ->
+      r
+        { getAddrPending = True,
+          addrTokens = r.addrTokens + fromIntegral maxAddrToSend
+        }
+
+-- | @extversion@ after @version@ (@src\/net_processing.cpp:2315-2341@). The
+-- expectation flag is cleared before any check, so a peer whose
+-- @extversion@ does not parse never gets our @verack@ when its own arrives.
+receiveExtVersion :: Maybe ByteString -> M ()
+receiveExtVersion mpayload = do
+  modify' (\s -> s {extVersionExpected = False})
+  done <- gets (.connected)
+  if done
+    then disconnect ProtocolViolation (netProcessing 2319 "extversion message after verack")
+    else case mpayload >>= parseExtVersion of
+      Nothing -> parseError (MCOther extVersionCommand)
+      Just () -> do
+        modify' (\s -> s {extVersionEnabled = True})
+        pushVerAck 0 (netProcessing 2336 "PushVerACK after extversion")
+        pushGetAddrOnce (netProcessing 2338 "GETADDR after extversion")
+
+-- | Parse an @extversion@ payload as @extversion::Message::Unserialize@
+-- does (@src\/extversion.h:155-176@): at most 100000 bytes, at most 8192
+-- keys, each a compact size and a byte vector, and the value of key 0 a
+-- compact size.
+parseExtVersion :: ByteString -> Maybe ()
+parseExtVersion bs
+  | BS.length bs > extVersionMaxSize = Nothing
+  | otherwise = either (const Nothing) Just (runGetS parser bs)
+  where
+    parser = do
+      VarInt n <- deserialize
+      when (n > extVersionMaxKeys) $ fail "too many keys"
+      _ <- replicateM (fromIntegral n) entry
+      return ()
+    entry = do
+      VarInt key <- deserialize
+      VarInt len <- deserialize
+      value <- getByteString (fromIntegral len)
+      when (key == 0) $
+        case runGetS deserialize value :: Either String VarInt of
+          Left err -> fail err
+          Right _ -> return ()
+      return ()
+
+-- | @verack@ (@src\/net_processing.cpp:2346-2391@). Duplicates are not
+-- checked: each one sends @sendheaders@ and @sendcmpct@ again.
+receiveVerAck :: M ()
+receiveVerAck = do
+  s <- get
+  when s.extVersionExpected $ do
+    pushVerAck 0 (netProcessing 2366 "PushVerACK: peer answered extversion with verack")
+    pushGetAddrOnce (netProcessing 2368 "GETADDR after verack")
+  when (s.peerVersion >= sendHeadersVersion) $
+    send MSendHeaders (netProcessing 2376 "SENDHEADERS")
+  when (s.peerVersion >= shortIdsBlocksVersion) $
+    send (MSendCompact (SendCompact False 1)) (netProcessing 2385 "SENDCMPCT")
+  modify' (\st -> st {connected = True})
+
+-- | @sendaddrv2@ (@src\/net_processing.cpp:2393-2402@): allowed only before
+-- the peer's @verack@.
+receiveSendAddrV2 :: M ()
+receiveSendAddrV2 = do
+  done <- gets (.connected)
+  if done
+    then disconnect ProtocolViolation (netProcessing 2397 "SENDADDRV2 after VERACK")
+    else modify' (\s -> s {wantsAddrV2 = True})
+
+-- | Any other message between @version@ and the peer's @verack@: dropped
+-- without misbehaviour (@src\/net_processing.cpp:2404-2408@).
+priorToVerAck :: M ()
+priorToVerAck = ignore (netProcessing 2405 "Unsupported message prior to verack")
+
+-- | @ping@ (@src\/net_processing.cpp:3530-3551@): a @pong@ with the same
+-- nonce from peers above version 60000; a short payload throws ('Nothing').
+receivePing :: Maybe Word64 -> M ()
+receivePing mnonce = do
+  pv <- gets (.peerVersion)
+  if pv > bip0031Version
+    then case mnonce of
+      Nothing -> parseError MCPing
+      Just n -> send (MPong (Pong n)) (netProcessing 3548 "PONG")
+    else ignore (netProcessing 3531 "ping of a peer of version 60000 or less")
+
+-- | @pong@ (@src\/net_processing.cpp:3553-3610@). It never draws misbehaviour;
+-- it ends the outstanding ping when the nonce matches, when it is zero, or
+-- when the payload is short ('Nothing').
+receivePong :: Maybe Word64 -> M ()
+receivePong mnonce = do
+  s <- get
+  t <- nowM
+  case mnonce of
+    Nothing -> finish (netProcessing 3596 "Short payload")
+    Just n
+      | s.pingNonceSent == 0 ->
+          ignore (netProcessing 3591 "Unsolicited pong without ping")
+      | n == s.pingNonceSent -> do
+          let rtt = t - s.pingStart
+          when (rtt > 0) $
+            modify' $ \st ->
+              st
+                { pingTime = Just rtt,
+                  minPingTime = Just (maybe rtt (min rtt) st.minPingTime)
+                }
+          finish (netProcessing 3607 "ping finished")
+      | n == 0 -> finish (netProcessing 3587 "Nonce zero")
+      | otherwise -> ignore (netProcessing 3582 "Nonce mismatch")
+  where
+    finish c = do
+      modify' (\st -> st {pingNonceSent = 0})
+      ignore c
+
+-- | A command that no handler takes, after the handshake
+-- (@src\/net_processing.cpp:3765-3768@).
+unknownCommand :: M ()
+unknownCommand = ignore (netProcessing 3766 "Unknown command")
+
+-- | A payload that throws while its handler reads it: a @reject@ with code
+-- @REJECT_MALFORMED@, no misbehaviour (@src\/net_processing.cpp:3927-3934@).
+parseError :: MessageCommand -> M ()
+parseError cmd =
+  sendReject cmd 0x01 "error parsing message" Nothing $
+    netProcessing 3929 "error parsing message"
+
+-- | Run after each message and at each pass of @SendMessages@
+-- (@SendRejectsAndCheckIfShouldDiscourage@, @src\/net_processing.cpp:3771-3810@):
+-- send the @reject@s of invalid blocks, then act on a crossed ban score:
+-- nothing for a @noban@ or manual peer, a plain disconnect for a local
+-- address, and otherwise discouragement of the address and the end of every
+-- connection from it. Returns whether the score was acted on.
+sendRejectsAndCheckIfShouldDiscourage :: M Bool
+sendRejectsAndCheckIfShouldDiscourage = do
+  o <- options
+  rs <- gets (.blockRejects)
+  when o.enableBip61 $
+    forM_ rs (`send` netProcessing 3777 "reject of an invalid block")
+  modify' (\s -> s {blockRejects = []})
+  s <- get
+  if not s.shouldDiscourage
+    then return False
+    else do
+      modify' (\st -> st {shouldDiscourage = False})
+      noban <- hasPerm PermNoBan
+      if
+        | noban -> return ()
+        | s.conn.connectionType == Manual -> return ()
+        | s.conn.peerIsLocal ->
+            disconnect Misbehaviour $
+              netProcessing 3799 "disconnecting but not discouraging local peer"
+        | otherwise -> do
+            emit Discourage (netProcessing 3803 "Discourage")
+            disconnect Misbehaviour (netProcessing 3805 "DisconnectNode(pnode->addr)")
+      return True
+
+-- | The inactivity check of the socket thread (@CConnman::InactivityCheck@,
+-- @src\/net.cpp:1272-1303@). Nothing is checked until the connection is
+-- older than @-peertimeout@; then the first rule that holds closes it. Times
+-- are compared in whole seconds, as upstream does but for the ping.
+inactivityCheck :: M ()
+inactivityCheck = do
+  o <- options
+  s <- get
+  t <- nowM
+  let secs x = x `div` 1000000
+      nowS = secs t
+      recvLimit
+        | s.peerVersion > bip0031Version = secs timeoutInterval
+        | otherwise = secs oldPeerReceiveTimeout
+  when (nowS - secs s.conn.openedAt > o.peerTimeout) $
+    if
+      | s.lastRecv == 0 || s.lastSend == 0 ->
+          disconnect Timeout (netCpp 1280 "socket no message in first seconds")
+      | nowS - secs s.lastSend > secs timeoutInterval ->
+          disconnect Timeout (netCpp 1284 "socket sending timeout")
+      | nowS - secs s.lastRecv > recvLimit ->
+          disconnect Timeout (netCpp 1290 "socket receive timeout")
+      | s.pingNonceSent /= 0 && s.pingStart + timeoutInterval < t ->
+          disconnect Timeout (netCpp 1296 "ping timeout")
+      | not s.connected ->
+          disconnect Timeout (netCpp 1300 "version handshake timeout")
+      | otherwise -> return ()
+
+-- | The ping of @SendMessages@ (@src\/net_processing.cpp:4161-4190@): when an
+-- operator asked for one, or when none is outstanding and the last one is
+-- older than two minutes. The first ping goes out on the first pass after
+-- the handshake. Peers of version 60000 or less get a @ping@ without a nonce
+-- and are not expected to answer.
+sendPing :: M ()
+sendPing = do
+  s <- get
+  t <- nowM
+  when (s.pingQueued || (s.pingNonceSent == 0 && s.pingStart + pingInterval < t)) $ do
+    nonce <- nonZero
+    modify' (\st -> st {pingQueued = False, pingStart = t})
+    if s.peerVersion > bip0031Version
+      then do
+        modify' (\st -> st {pingNonceSent = nonce})
+        send (MPing (Ping nonce)) (netProcessing 4183 "PING")
+      else do
+        modify' (\st -> st {pingNonceSent = 0})
+        send (MOther "ping" BS.empty) (netProcessing 4188 "PING without nonce")
+  where
+    nonZero = do
+      w <- randomWord
+      if w == 0 then nonZero else return w
+
+-- | Keep the characters of a user agent that @SanitizeString@ keeps by
+-- default: letters, digits and @ .,;-_\/:?\@()@
+-- (@src\/util\/strencodings.cpp:32-34@).
+sanitizeString :: VarString -> ByteString
+sanitizeString (VarString bs) = BS.filter safe bs
+  where
+    safe w = C.elem (toEnum (fromIntegral w)) allowed
+    allowed =
+      C.pack
+        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,;-_/:?@()"
diff --git a/src/Haskoin/Network/Protocol/BitcoinCashNode/Options.hs b/src/Haskoin/Network/Protocol/BitcoinCashNode/Options.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Network/Protocol/BitcoinCashNode/Options.hs
@@ -0,0 +1,235 @@
+{-# LANGUAGE DeriveAnyClass #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- |
+-- Module      : Haskoin.Network.Protocol.BitcoinCashNode.Options
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- The command-line options of Bitcoin Cash Node 29.2.0 that change what a
+-- peer sees, with their upstream defaults, and the derived settings of one
+-- connection: the permissions as the node expands them, and the services it
+-- offers the peer.
+--
+-- Only options that change the protocol of one connection are here. Options
+-- that change validation, such as @-maxreorgdepth@ or @-finalizeheaders@,
+-- reach the machine through the verdicts of the t'Env', and options that
+-- change decisions across peers, such as @-maxconnections@, through
+-- 'Notification's. The rate limiter of @-peerratelimit@ and the random drops
+-- of @-dropmessagestest@ have no default and are left out.
+--
+-- The defaults are the same on the four networks of Bitcoin Cash Node that
+-- this library knows, with one exception: the default block size of the
+-- chain, which scales the number of transactions announced at a time. That
+-- comes from the t'Network' in 'defaultOptions'.
+module Haskoin.Network.Protocol.BitcoinCashNode.Options
+  ( Options (..),
+    defaultOptions,
+    effectivePermissions,
+    localServices,
+    offersBloom,
+    whitelistRelayEffective,
+    subVersion,
+    genesisTime,
+  )
+where
+
+import Control.DeepSeq (NFData)
+import Data.Bits ((.|.))
+import Data.ByteString (ByteString)
+import Data.ByteString.Char8 qualified as C
+import Data.Int (Int64)
+import Data.Set qualified as Set
+import Data.Word (Word64)
+import GHC.Generics (Generic)
+import Haskoin.Block.Common (BlockHeader (..))
+import Haskoin.Network.Data (Network (..))
+import Haskoin.Network.Protocol.BitcoinCashNode.Constants
+import Haskoin.Network.Protocol.Types
+
+-- | The options of a node that change the protocol of a connection. Each
+-- field names its upstream option and where it is read.
+data Options = Options
+  { -- | the network; one machine per network is these rules with the
+    -- defaults of 'defaultOptions'
+    network :: !Network,
+    -- | @-enablebip61@, default true (@src\/net_processing.h:58@): send
+    -- @reject@ messages
+    enableBip61 :: !Bool,
+    -- | @-banscore@, default 100 (@src\/validation.h:150@): the score at which
+    -- a peer is discouraged, read at each call of @Misbehaving@
+    -- (@src\/net_processing.cpp:906@)
+    banScore :: !Int,
+    -- | @-peertimeout@ in seconds, default 60 (@src\/net.h:104@): no
+    -- inactivity check until a connection is this old, and the handshake must
+    -- end within it
+    peerTimeout :: !Int64,
+    -- | @-blocksonly@, default false (@src\/net.h:102@): the node does not
+    -- relay transactions, says so in its @version@, and drops those it gets
+    blocksOnly :: !Bool,
+    -- | @-peerbloomfilters@, default true (@src\/validation.h:166@): offer
+    -- @NODE_BLOOM@
+    peerBloomFilters :: !Bool,
+    -- | @-useextversion@, default false (@src\/extversion.h:24@): offer
+    -- @NODE_EXTVERSION@ and use the @extversion@ handshake with peers that
+    -- offer it too
+    useExtVersion :: !Bool,
+    -- | @-whitelistrelay@: 'Nothing' for the upstream default, which is true
+    -- unless @-blocksonly@ soft-sets it false and @-whitelistforcerelay@
+    -- soft-sets it true again (@src\/init.cpp:1504-1520@)
+    whitelistRelay :: !(Maybe Bool),
+    -- | @-whitelistforcerelay@, default false (@src\/net.h:53@)
+    whitelistForceRelay :: !Bool,
+    -- | @-rejectsubversion@, none by default: peers whose user agent contains
+    -- one of these, before its first parenthesis, are disconnected
+    -- (@src\/net_processing.cpp:2133-2153@)
+    rejectSubVersions :: ![ByteString],
+    -- | @-uacomment@, none by default: comments in our user agent
+    uaComments :: ![ByteString],
+    -- | @-listen@, default true (@src\/net.h:94@): the node advertises its own
+    -- address only when it listens
+    listen :: !Bool,
+    -- | @-feefilter@, default true (@src\/validation.h:155@): send @feefilter@
+    feeFilter :: !Bool,
+    -- | @-minrelaytxfee@ in satoshi per 1000 bytes, default 1000
+    -- (@src\/validation.h:68@): the floor of the @feefilter@ we send
+    minRelayTxFee :: !Word64,
+    -- | @-txbroadcastinterval@ in milliseconds, default 500
+    -- (@src\/net_processing.h:32@): the mean time between announcements of
+    -- transactions; 0 announces at every pass
+    txBroadcastInterval :: !Int64,
+    -- | @-txbroadcastrate@ in transactions per second per MB of block size,
+    -- default 7 (@src\/net_processing.h:38@)
+    txBroadcastRate :: !Double,
+    -- | @-doublespendproof@, default true (@src\/dsproof\/dsproof.cpp:17@)
+    doubleSpendProof :: !Bool,
+    -- | @-prune@ other than 0, default off: the node does not offer
+    -- @NODE_NETWORK@ (@src\/init.cpp:2806-2807@)
+    prune :: !Bool,
+    -- | the default block size of the chain in bytes
+    -- (@nDefaultConsensusBlockSize@, @src\/chainparams.cpp@), the size
+    -- limit of the next block when the t'Env' gives none
+    defaultBlockSize :: !Word64
+  }
+  deriving (Eq, Show, Generic, NFData)
+
+-- | The options of a node started with none on a network. They are the same
+-- on all networks but for 'defaultBlockSize', which is 32 MB on main,
+-- testnet3 and regtest, and 2 MB on testnet4
+-- (@src\/chainparams.cpp:158,417,642,1181@).
+defaultOptions :: Network -> Options
+defaultOptions net =
+  Options
+    { network = net,
+      enableBip61 = True,
+      banScore = 100,
+      peerTimeout = 60,
+      blocksOnly = False,
+      peerBloomFilters = True,
+      useExtVersion = False,
+      whitelistRelay = Nothing,
+      whitelistForceRelay = False,
+      rejectSubVersions = [],
+      uaComments = [],
+      listen = True,
+      feeFilter = True,
+      minRelayTxFee = 1000,
+      txBroadcastInterval = 500,
+      txBroadcastRate = 7,
+      doubleSpendProof = True,
+      prune = False,
+      defaultBlockSize = fromIntegral net.maxBlockSize
+    }
+
+-- | The value of @-whitelistrelay@ after the soft settings of
+-- @src\/init.cpp:1504-1520@: @-blocksonly@ turns it off, and
+-- @-whitelistforcerelay@ turns it on again.
+whitelistRelayEffective :: Options -> Bool
+whitelistRelayEffective o = case o.whitelistRelay of
+  Just b -> b
+  Nothing
+    | o.whitelistForceRelay -> True
+    | otherwise -> not o.blocksOnly
+
+-- | The permissions of a peer as @CConnman::AcceptConnection@ sets them
+-- (@src\/net.cpp:1036-1052@, @src\/net.cpp:1130@).
+--
+-- * Only inbound peers have permissions: the node consults @-whitelist@ and
+--   @-whitebind@ only when it accepts a connection, so an outbound peer,
+--   manual ones included, has none.
+-- * An entry without flags ('PermImplicit') becomes @noban@ and @mempool@,
+--   with @relay@ if @-whitelistrelay@ and @forcerelay@ if
+--   @-whitelistforcerelay@.
+-- * @forcerelay@ implies @relay@: its bits include those of @relay@
+--   (@src\/net_permissions.h@).
+-- * There is no @download@ permission in Bitcoin Cash Node, so
+--   'PermDownload' is dropped.
+effectivePermissions :: Options -> Setup -> Permissions
+effectivePermissions o s
+  | isOutbound s.connectionType = Set.empty
+  | otherwise = forceImpliesRelay (Set.delete PermDownload implicit)
+  where
+    given = s.permissions
+    implicit
+      | PermImplicit `Set.member` given =
+          Set.unions
+            [ Set.delete PermImplicit given,
+              Set.fromList [PermNoBan, PermMempool],
+              if whitelistRelayEffective o then Set.singleton PermRelay else Set.empty,
+              if o.whitelistForceRelay then Set.singleton PermForceRelay else Set.empty
+            ]
+      | otherwise = given
+    forceImpliesRelay ps
+      | PermForceRelay `Set.member` ps = Set.insert PermRelay ps
+      | otherwise = ps
+
+-- | The services the node offers this peer (@nLocalServices@):
+-- @NODE_NETWORK | NODE_NETWORK_LIMITED@ (@src\/init.cpp:1568@), without
+-- @NODE_NETWORK@ when pruned (@src\/init.cpp:2806-2807@), @NODE_BLOOM@ with
+-- @-peerbloomfilters@ (@src\/init.cpp:2005-2007@), always
+-- @NODE_BITCOIN_CASH@ (@src\/init.cpp:2012@), @NODE_EXTVERSION@ with
+-- @-useextversion@ (@src\/init.cpp:2016-2018@), and @NODE_BLOOM@ for an
+-- inbound peer with the @bloomfilter@ permission (@src\/net.cpp:1123-1126@).
+localServices :: Options -> Permissions -> Word64
+localServices o perms =
+  foldr
+    (.|.)
+    nodeBitcoinCash
+    [ if o.prune then 0 else nodeNetwork,
+      nodeNetworkLimited,
+      if offersBloom o perms then nodeBloom else 0,
+      if o.useExtVersion then nodeExtVersion else 0
+    ]
+
+-- | The node offers @NODE_BLOOM@ to this peer (@pfrom->GetLocalServices() &
+-- NODE_BLOOM@).
+offersBloom :: Options -> Permissions -> Bool
+offersBloom o perms = o.peerBloomFilters || PermBloomFilter `Set.member` perms
+
+-- | The sub-version string that the node puts in its @version@, built as
+-- @FormatSubVersion@ does (@src\/clientversion.cpp:103-118@): the client
+-- name and release between slashes, with the @-uacomment@ values in
+-- parentheses.
+subVersion :: Options -> ByteString
+subVersion o =
+  mconcat
+    [ "/Bitcoin Cash Node:29.2.0",
+      case o.uaComments of
+        [] -> ""
+        cs -> "(" <> C.intercalate "; " cs <> ")",
+      "/"
+    ]
+
+-- | The time of the genesis block of the network, in seconds: a @version@
+-- with an earlier time is misbehaviour (@src\/net_processing.cpp:2289@).
+genesisTime :: Options -> Int64
+genesisTime o = fromIntegral o.network.genesisHeader.timestamp
diff --git a/src/Haskoin/Network/Protocol/BitcoinCashNode/Relay.hs b/src/Haskoin/Network/Protocol/BitcoinCashNode/Relay.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Network/Protocol/BitcoinCashNode/Relay.hs
@@ -0,0 +1,744 @@
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE MultiWayIf #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- |
+-- Module      : Haskoin.Network.Protocol.BitcoinCashNode.Relay
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- How Bitcoin Cash Node 29.2.0 relays transactions, double-spend proofs and
+-- addresses with one peer: @inv@, @getdata@, @tx@, @notfound@,
+-- @dsproof-beta@, @mempool@, @feefilter@, the BIP 37 filters, @addr@,
+-- @addrv2@ and @getaddr@, and the parts of @SendMessages@ that announce
+-- inventory, send addresses, request transactions and proofs, and send
+-- @feefilter@.
+--
+-- @inv@ and @getdata@ are here although they carry blocks too: the handlers
+-- walk the entries in order and hand the block entries to
+-- "Haskoin.Network.Protocol.BitcoinCashNode.Blocks", as upstream does in one
+-- loop.
+--
+-- What the machine simplifies, and why:
+--
+-- * The @TxRequestTracker@ is global: it asks for a transaction from the best
+--   of the peers that announced it. The machine keeps this peer's
+--   announcements and requests them as if this peer were the only one;
+--   'RequestTx' lets the rest of the node force a request.
+-- * Transactions to announce are kept in order of arrival; upstream sorts
+--   them by their order in the mempool.
+-- * @mapRelay@, the transactions announced to any peer in the last 15
+--   minutes, is global and comes from 'relayedTx'.
+-- * The random shuffle of a large @addr@ under rate limiting, the choice of
+--   the peers an address is relayed to, and the bans are global or random
+--   and are left out: relayed and stored addresses are 'Process' effects.
+-- * Addresses are routable when their bytes are not all zero.
+-- * The shared timer of announcements to inbound peers
+--   (@PoissonNextSendInbound@) is a timer of this peer with the same mean.
+module Haskoin.Network.Protocol.BitcoinCashNode.Relay
+  ( -- * Messages
+    receiveInv,
+    receiveGetData,
+    receiveTx,
+    receiveNotFound,
+    receiveDsProof,
+    receiveMempool,
+    receiveFeeFilter,
+    receiveFilterLoad,
+    receiveFilterAdd,
+    receiveFilterClear,
+    receiveAddr,
+    receiveGetAddr,
+
+    -- * Notifications
+    txAccepted,
+    relayAddress,
+    newDoubleSpendProof,
+    requestTx,
+
+    -- * SendMessages
+    advertiseLocal,
+    sendAddresses,
+    sendInventory,
+    dsProofRequests,
+    txRequests,
+    sendFeeFilter,
+  )
+where
+
+import Control.Monad (foldM, forM_, unless, when)
+import Control.Monad.RWS.Strict (get, gets)
+import Data.Bits ((.&.), (.|.))
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as BS
+import Data.List (sortOn)
+import Data.Map.Strict qualified as Map
+import Data.Maybe (fromMaybe, mapMaybe)
+import Data.Set qualified as Set
+import Data.Word (Word64)
+import Haskoin.Block.Common (BlockHash (..))
+import Haskoin.Crypto.Hash (Hash256)
+import Haskoin.Network.Bloom
+  ( BloomFilter (..),
+    FilterAdd (..),
+    FilterLoad (..),
+    bloomInsert,
+    bloomRelevantUpdate,
+  )
+import Haskoin.Network.Common
+  ( Addr (..),
+    AddrV2 (..),
+    FeeFilter (..),
+    GetData (..),
+    Inv (..),
+    InvType (..),
+    InvVector (..),
+    MessageCommand (..),
+    NetworkAddressV2 (..),
+    NotFound (..),
+    fromNetworkAddressV2,
+  )
+import Haskoin.Network.Message (Message (..))
+import Haskoin.Network.Protocol.BitcoinCashNode.Blocks (afterInv, getBlockData, receiveBlockInv)
+import Haskoin.Network.Protocol.BitcoinCashNode.Constants
+import Haskoin.Network.Protocol.BitcoinCashNode.Handshake (hasAllDesirableServices)
+import Haskoin.Network.Protocol.BitcoinCashNode.Options
+import Haskoin.Network.Protocol.BitcoinCashNode.State
+import Haskoin.Network.Protocol.Types
+import Haskoin.Transaction.Common (OutPoint (..), Tx (..), TxHash (..), TxIn (..), txHash)
+
+-- * Helpers
+
+-- | The inventory type of a double-spend proof.
+dsProofType :: InvType
+dsProofType = InvType msgDoubleSpendProof
+
+-- | Remember that the peer knows a hash (@AddInventoryKnown@,
+-- @src\/net.h:1012-1015@).
+addKnown :: Hash256 -> M ()
+addKnown h = modifyRelay (\r -> r {knownInv = Set.insert h r.knownInv})
+
+-- | Transactions are taken from this peer: the node relays them, or the peer
+-- has the @relay@ permission (@src\/net_processing.cpp:2550-2556@).
+acceptsTxs :: M Bool
+acceptsTxs = do
+  o <- options
+  relayPerm <- hasPerm PermRelay
+  return (not o.blocksOnly || relayPerm)
+
+-- | @AddTxAnnouncement@ (@src\/net_processing.cpp:1958-1980@): track a
+-- transaction the peer has. Non-preferred peers wait 2 seconds more, and so
+-- do peers with 100 requests in flight; a peer without @relay@ may have at
+-- most 100000 announcements.
+addTxAnnouncement :: TxHash -> M ()
+addTxAnnouncement h = do
+  s <- get
+  t <- nowM
+  relayPerm <- hasPerm PermRelay
+  let anns = s.relay.announcements
+      inFlightCount = length [() | TxAnnouncement _ (TxRequested _) <- Map.elems anns]
+      delay =
+        (if s.preferredDownload then 0 else nonPrefPeerTxDelay)
+          + (if not relayPerm && inFlightCount >= maxPeerTxRequestInFlight then overloadedPeerTxDelay else 0)
+  unless ((not relayPerm && Map.size anns >= maxPeerTxAnnouncements) || Map.member h anns) $
+    modifyRelay $ \r ->
+      r {announcements = Map.insert h (TxAnnouncement (t + delay) TxCandidate) anns}
+
+-- | The filter of the peer matches the transaction, and is updated as
+-- @IsRelevantAndUpdate@ does.
+filterMatches :: Tx -> M Bool
+filterMatches tx = do
+  f <- gets (.relay.bloom)
+  case bloomRelevantUpdate f tx of
+    Nothing -> return False
+    Just f' -> do
+      modifyRelay (\r -> r {bloom = f'})
+      return True
+
+-- | An address the node can use: its bytes are not all zero.
+routable :: NetworkAddressV2 -> Bool
+routable a = BS.any (/= 0) a.address
+
+-- * Messages
+
+-- | @inv@ (@src\/net_processing.cpp:2537-2622@).
+receiveInv :: Inv -> M ()
+receiveInv (Inv xs)
+  | length xs > maxInvSize = misbehaving 20 (netProcessing 2546 "oversized-inv")
+  | otherwise = do
+      best <- foldM entry Nothing xs
+      afterInv best
+  where
+    entry best iv
+      | iv.invType == InvBlock = do
+          c <- receiveBlockInv (BlockHash iv.invHash)
+          return (maybe best Just c)
+      | otherwise = best <$ otherEntry iv
+
+-- | An entry of an @inv@ that is not a block
+-- (@src\/net_processing.cpp:2583-2613@).
+otherEntry :: InvVector -> M ()
+otherEntry iv = do
+  o <- options
+  e <- env
+  ok <- acceptsTxs
+  addKnown iv.invHash
+  let have = case iv.invType of
+        InvTx -> e.knownTx (TxHash iv.invHash)
+        t | t == dsProofType -> e.knownDsProof iv.invHash
+        _ -> True
+  if
+    | not ok -> ignore (netProcessing 2587 "transaction inv sent in violation of protocol")
+    | have || e.initialBlockDownload -> return ()
+    | iv.invType == dsProofType ->
+        if o.doubleSpendProof
+          then do
+            q <- gets (.relay.dsProofsToRequest)
+            if length q < maxDsProofGetDatas
+              then modifyRelay (\r -> r {dsProofsToRequest = q <> [iv.invHash]})
+              else ignore (netProcessing 2600 "DSProof batch queue full")
+          else ignore (netProcessing 2605 "DSProof INV ignored, -doublespendproof=0")
+    | otherwise -> addTxAnnouncement (TxHash iv.invHash)
+
+-- | @getdata@ (@src\/net_processing.cpp:2624-2645@ and @ProcessGetData@,
+-- @src\/net_processing.cpp:1478-1585@). Upstream answers a run of
+-- transactions and proofs, then one block, then sends @notfound@ for the run,
+-- and does not read the peer's next message until the queue is empty. The
+-- machine answers the whole queue in one step, in that order.
+receiveGetData :: GetData -> M ()
+receiveGetData (GetData xs)
+  | length xs > maxInvSize = misbehaving 20 (netProcessing 2629 "too-many-inv")
+  | otherwise = processGetData xs
+
+processGetData :: [InvVector] -> M ()
+processGetData [] = return ()
+processGetData q = do
+  let (run, rest) = span txOrProof q
+  missing <- concat <$> mapM serveTx run
+  rest' <- case rest of
+    [] -> return []
+    (x : more) -> do
+      if x.invType `elem` [InvBlock, InvMerkleBlock, InvCompactBlock]
+        then getBlockData x
+        else ignore (netProcessing 1543 "getdata of an unknown type")
+      return more
+  unless (null missing) $
+    send (MNotFound (NotFound missing)) (netProcessing 1583 "NOTFOUND")
+  closing <- gets (.closing)
+  unless closing $ processGetData rest'
+  where
+    txOrProof iv = iv.invType == InvTx || iv.invType == dsProofType
+
+-- | One transaction or proof of a @getdata@
+-- (@src\/net_processing.cpp:1500-1533@): a transaction announced to any
+-- peer in the last 15 minutes, or one from the mempool that was there when
+-- this peer last got an answer to @mempool@; a stored proof, orphans
+-- included. Returns the entry when it is not found.
+serveTx :: InvVector -> M [InvVector]
+serveTx iv = do
+  o <- options
+  e <- env
+  s <- get
+  if iv.invType == InvTx
+    then do
+      let h = TxHash iv.invHash
+          fromMempool = do
+            tx <- e.mempoolTx h
+            t <- e.mempoolTime h
+            if s.relay.lastMempoolReq /= 0 && t <= s.relay.lastMempoolReq
+              then Just tx
+              else Nothing
+      case e.relayedTx h of
+        Just tx -> [] <$ send (MTx tx) (netProcessing 1504 "TX from mapRelay")
+        Nothing -> case fromMempool of
+          Just tx -> [] <$ send (MTx tx) (netProcessing 1512 "TX from the mempool")
+          Nothing -> return [iv]
+    else case (o.doubleSpendProof, e.dsProof iv.invHash) of
+      (True, Just p) -> [] <$ send (MOther dsProofCommand p) (netProcessing 1521 "DSPROOF")
+      _ -> return [iv]
+
+-- | @tx@ (@src\/net_processing.cpp:2856-3020@).
+receiveTx :: Tx -> M ()
+receiveTx tx = do
+  ok <- acceptsTxs
+  if not ok
+    then ignore (netProcessing 2862 "transaction sent in violation of protocol")
+    else do
+      e <- env
+      let h = txHash tx
+      addKnown h.get
+      modifyRelay (\r -> r {announcements = Map.delete h r.announcements})
+      if e.knownTx h
+        then rejectedPath 0
+        else case e.checkTx tx of
+          TxAcceptedToMempool ->
+            process "relay the transaction and reconsider orphans" $
+              netProcessing 2891 "AcceptToMemoryPool: accepted"
+          TxAlreadyKnown -> rejectedPath 0
+          TxOrphan -> orphan e
+          TxPolicyReject r -> invalid h 0x40 0 r
+          TxConsensusInvalid r -> invalid h 0x10 100 r
+          TxRejected code dos r -> invalid h code dos r
+  where
+    orphan e
+      | any (e.recentlyRejected . (.outpoint.hash)) tx.inputs =
+          process "not keeping orphan with rejected parents" $
+            netProcessing 2942 "not keeping orphan with rejected parents"
+      | otherwise = do
+          forM_ tx.inputs $ \i -> do
+            let p = i.outpoint.hash
+            addKnown p.get
+            unless (e.knownTx p) $ addTxAnnouncement p
+          process "keep the transaction as an orphan" (netProcessing 2928 "AddTx to the orphanage")
+    rejectedPath :: Int -> M ()
+    rejectedPath dos = do
+      force <- hasPerm PermForceRelay
+      when force $
+        if dos == 0
+          then process "force relay" (netProcessing 2970 "Force relaying tx from whitelisted peer")
+          else process "not relayed" (netProcessing 2974 "Not relaying invalid transaction")
+    invalid h code dos r = do
+      rejectedPath dos
+      when (code > 0) $
+        sendReject MCTx code r (Just h.get) (netProcessing 3009 "reject of a transaction")
+      when (dos > 0) $ misbehaving dos (netProcessing 3016 r)
+
+-- | @notfound@ (@src\/net_processing.cpp:3750-3763@): the requests of the
+-- transactions named end; block entries are ignored, and so is a message of
+-- more than 100016 entries.
+receiveNotFound :: NotFound -> M ()
+receiveNotFound (NotFound xs)
+  | length xs > maxPeerTxAnnouncements + maxBlocksInTransitPerPeer =
+      ignore (netProcessing 3753 "notfound too large")
+  | otherwise =
+      forM_ [TxHash iv.invHash | iv <- xs, iv.invType == InvTx] $ \h ->
+        modifyRelay (\r -> r {announcements = Map.delete h r.announcements})
+
+-- | @dsproof-beta@ (@src\/net_processing.cpp:3680-3748@). Unsolicited proofs
+-- are processed in full, even in blocks-only mode. An invalid proof, or one
+-- that does not parse ('Nothing'), costs 10 unless the peer has @noban@;
+-- upstream charges it through a signal (@src\/net_processing.cpp:4865-4872@).
+receiveDsProof :: Maybe ByteString -> M ()
+receiveDsProof mp = do
+  o <- options
+  e <- env
+  noban <- hasPerm PermNoBan
+  let verdict = maybe (DsProofInvalid "does not parse") e.checkDsProof mp
+  if not o.doubleSpendProof
+    then ignore (netProcessing 3682 "dsproof received while disabled")
+    else case verdict of
+      DsProofDuplicate -> ignore (netProcessing 3698 "proof for an outpoint that has one")
+      DsProofValid -> process "store and announce the proof" (netProcessing 3744 "TransactionDoubleSpent")
+      DsProofOrphan -> process "keep the proof as an orphan" (netProcessing 3720 "addOrphan")
+      DsProofInvalid r -> do
+        process "mark the proof rejected" (netProcessing 3732 r)
+        unless noban $ misbehaving 10 (netProcessing 4870 "bad-dsproof")
+
+-- | @mempool@ (@src\/net_processing.cpp:3500-3528@): allowed when the node
+-- offers Bloom filters or the peer has the @mempool@ permission, and the
+-- upload target is not reached; otherwise a disconnect, or nothing for a
+-- @noban@ peer. The answer goes out with the next announcement of
+-- transactions.
+receiveMempool :: M ()
+receiveMempool = do
+  o <- options
+  e <- env
+  s <- get
+  mempoolPerm <- hasPerm PermMempool
+  noban <- hasPerm PermNoBan
+  if
+    | not (offersBloom o s.perms) && not mempoolPerm ->
+        if noban
+          then ignore (netProcessing 3510 "mempool request with bloom filters disabled")
+          else disconnect Unsuitable (netProcessing 3508 "mempool request with bloom filters disabled")
+    | e.uploadTargetReached && not mempoolPerm ->
+        if noban
+          then ignore (netProcessing 3522 "mempool request with bandwidth limit reached")
+          else disconnect Resources (netProcessing 3520 "mempool request with bandwidth limit reached")
+    | otherwise -> modifyRelay (\r -> r {sendMempool = True})
+
+-- | @feefilter@ (@src\/net_processing.cpp:3666-3678@): kept when it is a
+-- valid amount, ignored otherwise.
+receiveFeeFilter :: FeeFilter -> M ()
+receiveFeeFilter (FeeFilter r)
+  | r <= maxMoney = modifyRelay (\x -> x {minFeeFilter = r})
+  | otherwise = ignore (netProcessing 3669 "feefilter out of the money range")
+
+-- | @filterload@ (@src\/net_processing.cpp:3612-3626@), after the check of
+-- @NODE_BLOOM@ that comes first: a filter over the size limits costs 100,
+-- a good one replaces the filter and turns on the relay of transactions.
+receiveFilterLoad :: FilterLoad -> M ()
+receiveFilterLoad (FilterLoad f)
+  | length f.array > maxBloomFilterSize || f.functions > maxHashFuncs =
+      misbehaving 100 (netProcessing 3619 "oversized-bloom-filter")
+  | otherwise = modifyRelay (\r -> r {bloom = f, relayTxes = True})
+
+-- | @filteradd@ (@src\/net_processing.cpp:3628-3655@): an item over 520
+-- bytes costs 100. There is always a filter upstream, so a @filteradd@
+-- without @filterload@ adds to the empty filter, which still matches
+-- everything.
+receiveFilterAdd :: FilterAdd -> M ()
+receiveFilterAdd (FilterAdd bs)
+  | BS.length bs > maxScriptElementSize =
+      misbehaving 100 (netProcessing 3652 "invalid-filteradd")
+  | otherwise = modifyRelay (\r -> r {bloom = bloomInsert r.bloom bs})
+
+-- | @filterclear@ (@src\/net_processing.cpp:3657-3664@): no check of
+-- @NODE_BLOOM@; the filter is reset only when the node offers Bloom filters,
+-- and the relay of transactions turns on in any case.
+receiveFilterClear :: M ()
+receiveFilterClear = do
+  o <- options
+  s <- get
+  modifyRelay $ \r ->
+    r
+      { bloom = if offersBloom o s.perms then BloomFilter mempty 0 0 r.bloom.flags else r.bloom,
+        relayTxes = True
+      }
+
+-- | @addr@ and @addrv2@ (@src\/net_processing.cpp:2410-2511@): more than
+-- 1000 costs 20; then the token bucket limits how many are taken, unless the
+-- peer has the @addr@ permission. An address-fetch connection ends after
+-- the first one.
+receiveAddr :: [NetworkAddressV2] -> M ()
+receiveAddr xs
+  | length xs > maxAddrToSend = misbehaving 20 (netProcessing 2425 "oversized-addr")
+  | otherwise = do
+      e <- env
+      t <- nowM
+      addrPerm <- hasPerm PermAddr
+      r0 <- gets (.relay)
+      let refill
+            | r0.addrTokens < maxAddrProcessingTokenBucket =
+                min
+                  maxAddrProcessingTokenBucket
+                  (r0.addrTokens + fromIntegral (max 0 (t - r0.addrTokenTime)) / 1e6 * maxAddrRatePerSecond)
+            | otherwise = r0.addrTokens
+          nowS = fromIntegral (t `div` 1000000) :: Word64
+      modifyRelay (\r -> r {addrTokens = refill, addrTokenTime = t})
+      kept <- concat <$> mapM (one e addrPerm nowS) xs
+      pending <- gets (.relay.getAddrPending)
+      let relayable =
+            [ a
+            | a <- kept,
+              fromIntegral a.time > nowS - 600,
+              not pending,
+              length xs <= 10,
+              routable a
+            ]
+      unless (null relayable) $
+        process "relay the addresses to two peers" (netProcessing 2491 "RelayAddress")
+      unless (null kept) $
+        process "add the addresses to addrman" (netProcessing 2503 "AddNewAddresses")
+      when (length xs < maxAddrToSend) $
+        modifyRelay (\r -> r {getAddrPending = False})
+      ct <- connType
+      when (ct == AddrFetch) $
+        disconnect Done (netProcessing 2508 "address fetch done")
+  where
+    one e addrPerm nowS a = do
+      tokens <- gets (.relay.addrTokens)
+      if tokens < 1 && not addrPerm
+        then return []
+        else do
+          when (tokens >= 1) $ modifyRelay (\r -> r {addrTokens = r.addrTokens - 1})
+          let useful = a.services .&. (nodeNetwork .|. nodeNetworkLimited) /= 0
+          if not useful && not (hasAllDesirableServices e a.services)
+            then return []
+            else do
+              let fixed
+                    | a.time <= 100000000 || fromIntegral a.time > nowS + 600 =
+                        NetworkAddressV2
+                          { time = fromIntegral (nowS - 5 * 24 * 60 * 60),
+                            services = a.services,
+                            network = a.network,
+                            address = a.address,
+                            port = a.port
+                          }
+                    | otherwise = a
+              modifyRelay (\r -> r {addrKnown = Set.insert (addrKey fixed) r.addrKnown})
+              return [fixed]
+
+-- | @getaddr@ (@src\/net_processing.cpp:3463-3498@): answered once, and only
+-- to an inbound peer, with a fresh sample for the @addr@ permission and the
+-- cached answer otherwise; the addresses go out with the next @addr@.
+receiveGetAddr :: M ()
+receiveGetAddr = do
+  e <- env
+  inbound <- isInbound
+  sent <- gets (.relay.sentAddr)
+  addrPerm <- hasPerm PermAddr
+  if
+    | not inbound -> ignore (netProcessing 3471 "Ignoring getaddr from an outbound connection")
+    | sent -> ignore (netProcessing 3479 "Ignoring repeated getaddr")
+    | otherwise -> do
+        modifyRelay (\r -> r {sentAddr = True, addrToSend = []})
+        mapM_ pushAddress (e.addressesForPeer addrPerm)
+
+-- * Notifications
+
+-- | A transaction entered the mempool (@RelayTransaction@,
+-- @src\/net_processing.cpp:1188-1197@): queued for a peer past its
+-- handshake that does not know it.
+txAccepted :: Tx -> M ()
+txAccepted tx = do
+  s <- get
+  let h = txHash tx
+  when (s.connected && not (h.get `Set.member` s.relay.knownInv)) $
+    modifyRelay (\r -> r {txsToSend = r.txsToSend <> [h | h `notElem` r.txsToSend]})
+
+-- | The node relays an address to this peer (@RelayAddress@,
+-- @src\/net_processing.cpp:1199-1233@, which picks the peers).
+relayAddress :: NetworkAddressV2 -> M ()
+relayAddress = pushAddress
+
+-- | A double-spend proof to announce (@TransactionDoubleSpent@,
+-- @src\/net_processing.cpp:4850-4863@): to a peer that wants transactions
+-- and whose filter matches the transaction.
+newDoubleSpendProof :: Hash256 -> Tx -> M ()
+newDoubleSpendProof h tx = do
+  s <- get
+  when (s.connected && s.relay.relayTxes) $ do
+    m <- filterMatches tx
+    known <- gets (Set.member h . (.relay.knownInv))
+    when (m && not known) $
+      modifyRelay (\r -> r {otherInvs = r.otherInvs <> [h]})
+
+-- | The rest of the node wants this transaction from this peer: an
+-- announcement that may be requested at once.
+requestTx :: TxHash -> M ()
+requestTx h = do
+  t <- nowM
+  modifyRelay $ \r ->
+    r {announcements = Map.insertWith (\_ old -> old) h (TxAnnouncement t TxCandidate) r.announcements}
+
+-- * SendMessages
+
+-- | Advertise our address once a day on average, from the first pass after
+-- the handshake, out of initial block download
+-- (@src\/net_processing.cpp:4203-4207@, @AdvertiseLocal@,
+-- @src\/net.cpp:183-209@).
+advertiseLocal :: M ()
+advertiseLocal = do
+  o <- options
+  e <- env
+  r <- gets (.relay)
+  when (not e.initialBlockDownload && r.nextLocalAddrSend < e.now) $ do
+    when o.listen $ mapM_ pushAddress e.localAddress
+    d <- randomDelay avgLocalAddressBroadcastInterval
+    modifyRelay (\x -> x {nextLocalAddrSend = e.now + d})
+
+-- | Send the queued addresses every 30 seconds on average
+-- (@src\/net_processing.cpp:4212-4247@), as @addrv2@ to a peer that sent
+-- @sendaddrv2@ and as @addr@ otherwise, at most 1000 to a message.
+sendAddresses :: M ()
+sendAddresses = do
+  t <- nowM
+  r <- gets (.relay)
+  v2 <- gets (.wantsAddrV2)
+  when (r.nextAddrSend < t) $ do
+    d <- randomDelay avgAddressBroadcastInterval
+    let fresh = dedupe r.addrKnown r.addrToSend
+    modifyRelay $ \x ->
+      x
+        { nextAddrSend = t + d,
+          addrToSend = [],
+          addrKnown = foldr (Set.insert . addrKey) x.addrKnown fresh
+        }
+    forM_ (chunks maxAddrToSend fresh) $ \c ->
+      if v2
+        then send (MAddrV2 (AddrV2 c)) (netProcessing 4240 "ADDRV2")
+        else send (MAddr (Addr (mapMaybe fromNetworkAddressV2 c))) (netProcessing 4240 "ADDR")
+  where
+    dedupe _ [] = []
+    dedupe known (a : as)
+      | addrKey a `Set.member` known = dedupe known as
+      | otherwise = a : dedupe (Set.insert (addrKey a) known) as
+
+-- | Split a list into pieces of at most this length.
+chunks :: Int -> [a] -> [[a]]
+chunks _ [] = []
+chunks n xs = let (a, b) = splitAt n xs in a : chunks n b
+
+-- | The @inv@ messages of a pass (@src\/net_processing.cpp:4461-4654@):
+-- block hashes and proofs at once, and transactions when the trickle timer
+-- fires (at every pass for a @noban@ peer), with the answer to @mempool@
+-- first. Transactions go at most @nMaxBroadcasts@ at a time, only if the
+-- peer wants them, they are still in the mempool, they pay the peer's
+-- @feefilter@ and match its filter.
+sendInventory :: M ()
+sendInventory = do
+  o <- options
+  e <- env
+  s <- get
+  noban <- hasPerm PermNoBan
+  inbound <- isInbound
+  let t = e.now
+      blockLimit = maybe o.defaultBlockSize id e.nextBlockSizeLimit
+      interval = o.txBroadcastInterval
+      maxBroadcasts =
+        ceiling
+          ( o.txBroadcastRate
+              * (fromIntegral blockLimit / 1000000)
+              * (fromIntegral (max interval 1) / 1000)
+          ) ::
+          Int
+      blockInvs = [InvVector InvBlock h.get | h <- s.blocks.blockInvs]
+      proofInvs = [InvVector dsProofType h | h <- s.relay.otherInvs]
+  modifyBlocks (\b -> b {blockInvs = []})
+  modifyRelay (\r -> r {otherInvs = []})
+  timerFired <-
+    if interval == 0 || s.relay.nextInvSend < t
+      then do
+        d <- randomDelay (millis (if inbound then interval else interval `div` 2))
+        modifyRelay (\r -> r {nextInvSend = t + d})
+        return True
+      else return False
+  let trickle = noban || timerFired
+  when (trickle && not s.relay.relayTxes) $
+    modifyRelay (\r -> r {txsToSend = []})
+  mempoolInvs <-
+    if trickle && s.relay.sendMempool
+      then do
+        modifyRelay (\r -> r {sendMempool = False})
+        xs <- concat <$> mapM (mempoolEntry e) e.mempoolTxs
+        modifyRelay (\r -> r {lastMempoolReq = t `div` 1000000})
+        return xs
+      else return []
+  txInvs <-
+    if trickle
+      then announce e maxBroadcasts
+      else return []
+  let invs = blockInvs <> proofInvs <> mempoolInvs <> txInvs
+  unless (null txInvs) $
+    process "keep the announced transactions for 15 minutes" $
+      netProcessing 4638 "mapRelay"
+  forM_ (chunks maxInvSize invs) $ \c ->
+    send (MInv (Inv c)) (netProcessing 4652 "INV")
+  where
+    passesFee e h = do
+      f <- gets (.relay.minFeeFilter)
+      return (f == 0 || fromMaybe 0 (e.txFeeRate h) >= f)
+    mempoolEntry e tx = do
+      let h = txHash tx
+      modifyRelay (\r -> r {txsToSend = filter (/= h) r.txsToSend})
+      fee <- passesFee e h
+      if not fee
+        then return []
+        else do
+          m <- filterMatches tx
+          if not m
+            then return []
+            else do
+              addKnown h.get
+              return [InvVector InvTx h.get]
+    announce e n
+      | n <= 0 = return []
+      | otherwise = do
+          q <- gets (.relay.txsToSend)
+          case q of
+            [] -> return []
+            (h : rest) -> do
+              modifyRelay (\r -> r {txsToSend = rest})
+              known <- gets (Set.member h.get . (.relay.knownInv))
+              fee <- passesFee e h
+              case e.mempoolTx h of
+                Just tx | not known && fee -> do
+                  m <- filterMatches tx
+                  if m
+                    then do
+                      addKnown h.get
+                      (InvVector InvTx h.get :) <$> announce e (n - 1)
+                    else announce e n
+                _ -> announce e n
+
+-- | The proofs to request in this pass (@src\/net_processing.cpp:4776-4785@):
+-- every queued one the node does not have yet.
+dsProofRequests :: M [InvVector]
+dsProofRequests = do
+  e <- env
+  q <- gets (.relay.dsProofsToRequest)
+  modifyRelay (\r -> r {dsProofsToRequest = []})
+  return [InvVector dsProofType h | h <- q, not (e.knownDsProof h)]
+
+-- | The transactions to request in this pass
+-- (@src\/net_processing.cpp:4787-4809@): requests older than a minute
+-- expire without penalty, then each announcement whose time has come is
+-- requested, unless the node got the transaction meanwhile.
+txRequests :: M [InvVector]
+txRequests = do
+  e <- env
+  anns <- gets (.relay.announcements)
+  let t = e.now
+      live = Map.filter (not . expired t) anns
+      ready =
+        sortOn
+          (\(h, a) -> (a.reqTime, h))
+          [(h, a) | (h, a@(TxAnnouncement _ TxCandidate)) <- Map.toList live, a.reqTime <= t]
+      want = [h | (h, _) <- ready, not (e.knownTx h)]
+      forget = [h | (h, _) <- ready, e.knownTx h]
+      requested = TxAnnouncement t (TxRequested (t + getDataTxInterval))
+      anns' =
+        foldr Map.delete (foldr (`Map.insert` requested) live want) forget
+  modifyRelay (\r -> r {announcements = anns'})
+  return [InvVector InvTx h.get | h <- want]
+  where
+    expired t (TxAnnouncement _ (TxRequested x)) = x <= t
+    expired _ _ = False
+
+-- | @feefilter@ (@src\/net_processing.cpp:4815-4846@): to peers of version
+-- 70013 or later without @forcerelay@, every 10 minutes on average and
+-- sooner after a large change, when the rounded minimum fee of the mempool
+-- differs from the last one sent.
+sendFeeFilter :: M ()
+sendFeeFilter = do
+  o <- options
+  e <- env
+  s <- get
+  force <- hasPerm PermForceRelay
+  let t = e.now
+      current = e.mempoolMinFee
+      lastSent = s.relay.lastSentFeeFilter
+  when (s.peerVersion >= feeFilterVersion && o.feeFilter && not force) $
+    if t > s.relay.nextFeeFilter
+      then do
+        rounded <- roundFee current
+        let toSend = max rounded o.minRelayTxFee
+        when (toSend /= lastSent) $ do
+          send (MFeeFilter (FeeFilter toSend)) (netProcessing 4829 "FEEFILTER")
+          modifyRelay (\r -> r {lastSentFeeFilter = toSend})
+        d <- randomDelay avgFeeFilterBroadcastInterval
+        modifyRelay (\r -> r {nextFeeFilter = t + d})
+      else when
+        ( t + maxFeeFilterChangeDelay < s.relay.nextFeeFilter
+            && (current < 3 * lastSent `div` 4 || current > 4 * lastSent `div` 3)
+        )
+        $ do
+          w <- randomWord
+          let secs = fromIntegral (w `mod` 300)
+          modifyRelay (\r -> r {nextFeeFilter = t + seconds secs})
+
+-- | @FeeFilterRounder::round@ (@src\/policy\/fees.cpp:21-29@): the bucket at
+-- or above the fee, moved one bucket down two times in three. The buckets
+-- are 0 and 500 times powers of 1.1 up to 1e7 satoshi per 1000 bytes.
+roundFee :: Word64 -> M Word64
+roundFee fee = do
+  w <- randomWord
+  let (below, above) = span (< fee) feeSet
+      pick = case (below, above) of
+        ([], x : _) -> x
+        (_, []) -> last below
+        (_, x : _)
+          | w `mod` 3 /= 0 -> last below
+          | otherwise -> x
+  return pick
+  where
+    feeSet = 0 : takeWhile (<= 10000000) (map floor (iterate (* 1.1) (500 :: Double)))
diff --git a/src/Haskoin/Network/Protocol/BitcoinCashNode/State.hs b/src/Haskoin/Network/Protocol/BitcoinCashNode/State.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Network/Protocol/BitcoinCashNode/State.hs
@@ -0,0 +1,588 @@
+{-# LANGUAGE DeriveAnyClass #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- |
+-- Module      : Haskoin.Network.Protocol.BitcoinCashNode.State
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- What Bitcoin Cash Node 29.2.0 keeps about one peer, and the small language
+-- in which the handlers of the machine are written.
+--
+-- Upstream splits this state between @CNode@ (@src\/net.h@), which the
+-- socket thread and the message thread share, and @CNodeState@
+-- (@src\/net_processing.cpp:269-385@), which @cs_main@ guards. The split is
+-- about locks, not meaning, so the machine keeps one record with three parts:
+-- the connection and handshake in t'State', the blocks in t'BlockState', and
+-- the relay of transactions, proofs and addresses in t'RelayState'. Each field
+-- names the upstream field it stands for.
+--
+-- Two kinds of upstream state are modelled more simply, and say so where they
+-- are kept: the rolling Bloom filters that remember what a peer knows
+-- (@filterInventoryKnown@, @addrKnown@) are exact sets here, and the
+-- per-peer part of the global @TxRequestTracker@ is a map of this peer's
+-- announcements.
+--
+-- Handlers run in 'M', a reader of the options and the environment, a writer
+-- of t'Effect's in the order the node produces them, and a state. The helpers
+-- 'send', 'misbehaving' and 'disconnect' keep the bookkeeping that every
+-- handler needs in one place: the time of the last send for the inactivity
+-- check, the ban score and its threshold, and the flag that stops all
+-- processing once the node has decided to close the connection.
+module Haskoin.Network.Protocol.BitcoinCashNode.State
+  ( -- * State
+    State (..),
+    BlockState (..),
+    RelayState (..),
+    InFlight (..),
+    TxAnnouncement (..),
+    TxRequestState (..),
+    ChainSync (..),
+    AddrKey,
+    addrKey,
+    initialState,
+
+    -- * Handlers
+    M,
+    runM,
+    options,
+    env,
+    nowM,
+    emit,
+    send,
+    ignore,
+    process,
+    misbehaving,
+    disconnect,
+    modifyBlocks,
+    modifyRelay,
+    randomWord,
+    randomDelay,
+    hasPerm,
+    isInbound,
+    connType,
+    inIBD,
+    pushAddress,
+    rejectMessage,
+    sendReject,
+  )
+where
+
+import Control.DeepSeq (NFData)
+import Control.Monad (when)
+import Control.Monad.RWS.Strict (RWS, asks, get, gets, modify', runRWS, tell)
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as BS
+import Data.Int (Int32, Int64)
+import Data.Map.Strict (Map)
+import Data.Map.Strict qualified as Map
+import Data.Maybe (isJust)
+import Data.Sequence qualified as Seq
+import Data.Set (Set)
+import Data.Set qualified as Set
+import Data.Text (Text)
+import Data.Text.Encoding qualified as TE
+import Data.Word (Word16, Word64, Word8)
+import GHC.Generics (Generic)
+import Haskoin.Block.Common (BlockHash)
+import Haskoin.Crypto.Hash (Hash256)
+import Haskoin.Network.Bloom (BloomFilter (..), BloomFlags (..))
+import Haskoin.Network.Common
+  ( MessageCommand,
+    NetworkAddressV2 (..),
+    Reject (..),
+    RejectCode (..),
+    VarString (..),
+    addressNetworkId,
+    fromNetworkAddressV2,
+  )
+import Haskoin.Network.CompactBlock (CompactBlock)
+import Haskoin.Network.Message (Message (..))
+import Haskoin.Network.Protocol.BitcoinCashNode.Constants
+import Haskoin.Network.Protocol.BitcoinCashNode.Options
+import Haskoin.Network.Protocol.Types
+import Haskoin.Transaction.Common (TxHash)
+
+-- | What the node keeps about a peer. The connection and handshake fields
+-- are here, those of the block and relay families in t'BlockState' and
+-- t'RelayState'.
+data State = State
+  { -- | the connection as it opened
+    conn :: !Setup,
+    -- | the permissions after 'effectivePermissions' (@m_permissionFlags@)
+    perms :: !Permissions,
+    -- | services offered to this peer (@nLocalServices@, @src\/net.h:955@)
+    ourServices :: !Word64,
+    -- | randomness of the node for this connection
+    rng :: !Rng,
+    -- | the node decided to close the connection (@fDisconnect@,
+    -- @src\/net.h:844@); nothing is processed after it
+    closing :: !Bool,
+    -- | our @version@ was sent (outbound connections, at @InitializeNode@)
+    versionSent :: !Bool,
+    -- | nonce of our @version@ (@nLocalHostNonce@, @src\/net.h:953@)
+    localNonce :: !Word64,
+    -- | protocol version of the peer, 0 before its @version@ (@nVersion@,
+    -- @src\/net.h:806@)
+    peerVersion :: !Int,
+    -- | services of the peer (@nServices@, @src\/net.h:776@)
+    peerServices :: !Word64,
+    -- | start height of the peer, -1 if unknown (@nStartingHeight@)
+    peerStartHeight :: !Int32,
+    -- | user agent of the peer after @SanitizeString@ (@cleanSubVer@)
+    peerSubVer :: !Text,
+    -- | the peer serves neither the whole chain nor its recent part
+    -- (@fClient@, @src\/net.h:822@)
+    client :: !Bool,
+    -- | the peer serves only the recent part of the chain
+    -- (@m_limited_node@, @src\/net.h:824@)
+    limitedNode :: !Bool,
+    -- | we sent @extversion@ and wait for the peer's (@extversionExpected@)
+    extVersionExpected :: !Bool,
+    -- | the peer's @extversion@ was parsed (@extversionEnabled@)
+    extVersionEnabled :: !Bool,
+    -- | the peer sent @sendaddrv2@ (@m_wants_addrv2@, @src\/net.h:829@)
+    wantsAddrV2 :: !Bool,
+    -- | the peer's @verack@ arrived (@fSuccessfullyConnected@,
+    -- @src\/net.h:843@)
+    connected :: !Bool,
+    -- | we sent a @verack@ (@mapSendBytesPerMsgType[VERACK] > 0@)
+    verAckSent :: !Bool,
+    -- | we sent a @getaddr@ (@mapSendBytesPerMsgType[GETADDR] > 0@)
+    getAddrSent :: !Bool,
+    -- | offset of the peer's clock in seconds (@nTimeOffset@)
+    timeOffset :: !Int64,
+    -- | time of the last bytes received, 0 for never (@nLastRecv@)
+    lastRecv :: !Micros,
+    -- | time of the last bytes sent, 0 for never (@nLastSend@)
+    lastSend :: !Micros,
+    -- | nonce of the ping that waits for its pong, 0 for none
+    -- (@nPingNonceSent@, @src\/net.h:917@)
+    pingNonceSent :: !Word64,
+    -- | when the last ping was sent (@nPingUsecStart@, @src\/net.h:919@)
+    pingStart :: !Micros,
+    -- | the last round trip (@nPingUsecTime@)
+    pingTime :: !(Maybe Micros),
+    -- | the best round trip (@nMinPingUsecTime@)
+    minPingTime :: !(Maybe Micros),
+    -- | an operator asked for a ping (@fPingQueued@)
+    pingQueued :: !Bool,
+    -- | the ban score (@nMisbehavior@, @src\/net_processing.cpp:275@)
+    misbehavior :: !Int,
+    -- | the score crossed @-banscore@ and the node has not acted on it yet
+    -- (@fShouldDiscourage@, @src\/net_processing.cpp:277@)
+    shouldDiscourage :: !Bool,
+    -- | @reject@ messages for invalid blocks from this peer, waiting to be
+    -- sent (@CNodeState::rejects@)
+    blockRejects :: ![Message],
+    -- | the peer counts as a preferred download source
+    -- (@fPreferredDownload@, @src\/net_processing.cpp:306@)
+    preferredDownload :: !Bool,
+    blocks :: !BlockState,
+    relay :: !RelayState
+  }
+  deriving (Eq, Show, Generic, NFData)
+
+-- | A block requested from this peer (@QueuedBlock@,
+-- @src\/net_processing.cpp:164-175@).
+data InFlight = InFlight
+  { inFlightHash :: !BlockHash,
+    -- | the header is known (@fValidatedHeaders@)
+    validatedHeaders :: !Bool,
+    -- | the compact block being completed (@partialBlock@)
+    partial :: !(Maybe CompactBlock)
+  }
+  deriving (Eq, Show, Generic, NFData)
+
+-- | The outbound chain-sync check (@m_chain_sync@,
+-- @src\/net_processing.cpp:341-354@).
+data ChainSync = ChainSync
+  { -- | deadline in seconds, 0 for none (@m_timeout@)
+    syncTimeout :: !Int64,
+    -- | the tip whose work the peer must reach (@m_work_header@)
+    workHeader :: !(Maybe BlockInfo),
+    -- | the last-chance @getheaders@ was sent (@m_sent_getheaders@)
+    sentGetHeaders :: !Bool,
+    -- | the peer is protected from this check (@m_protect@)
+    protect :: !Bool
+  }
+  deriving (Eq, Show, Generic, NFData)
+
+-- | What the node keeps about blocks for this peer.
+data BlockState = BlockState
+  { -- | best block the peer is known to have (@pindexBestKnownBlock@)
+    bestKnown :: !(Maybe BlockInfo),
+    -- | last announced hash the node did not know (@hashLastUnknownBlock@)
+    lastUnknown :: !(Maybe BlockHash),
+    -- | best header sent to the peer (@pindexBestHeaderSent@)
+    bestHeaderSent :: !(Maybe BlockInfo),
+    -- | streak of headers that did not connect (@nUnconnectingHeaders@)
+    unconnecting :: !Int,
+    -- | the initial @getheaders@ went out (@fSyncStarted@)
+    syncStarted :: !Bool,
+    -- | deadline of the headers sync, 'maxBound' once caught up
+    -- (@nHeadersSyncTimeout@)
+    headersSyncTimeout :: !Micros,
+    -- | when the peer started holding back the download window, 0 for
+    -- never (@nStallingSince@)
+    stallingSince :: !Micros,
+    -- | blocks requested from this peer, oldest first (@vBlocksInFlight@)
+    inFlight :: ![InFlight],
+    -- | when the oldest block in flight started downloading
+    -- (@nDownloadingSince@)
+    downloadingSince :: !Micros,
+    -- | the peer sent @sendheaders@ (@fPreferHeaders@)
+    preferHeaders :: !Bool,
+    -- | the peer asked for high-bandwidth compact blocks
+    -- (@fPreferHeaderAndIDs@)
+    preferHeaderAndIds :: !Bool,
+    -- | the peer sent @sendcmpct@ of version 1 (@fProvidesHeaderAndIDs@,
+    -- @fSupportsDesiredCmpctVersion@)
+    providesHeaderAndIds :: !Bool,
+    -- | we chose the peer for high-bandwidth compact blocks
+    -- (@m_bip152_highbandwidth_to@)
+    highBandwidthTo :: !Bool,
+    -- | the outbound chain-sync check
+    chainSync :: !ChainSync,
+    -- | time of the last new block announcement with more work than the tip
+    -- (@m_last_block_announcement@)
+    lastBlockAnnouncement :: !Int64,
+    -- | hashes of new tips to announce (@vBlockHashesToAnnounce@)
+    toAnnounce :: ![BlockHash],
+    -- | block hashes to announce by @inv@ (@vInventoryBlockToSend@)
+    blockInvs :: ![BlockHash],
+    -- | last hash of a 500-block @getblocks@ reply (@hashContinue@)
+    hashContinue :: !(Maybe BlockHash),
+    -- | blocks that the rest of the node asked this peer for, to request
+    -- in the next pass
+    toRequest :: ![BlockHash]
+  }
+  deriving (Eq, Show, Generic, NFData)
+
+-- | Where an announced transaction stands (@TxRequestTracker@ states,
+-- @src\/txrequest.h:18-202@).
+data TxRequestState
+  = -- | announced, not requested yet (@CANDIDATE@)
+    TxCandidate
+  | -- | requested, with the time the request expires (@REQUESTED@)
+    TxRequested !Micros
+  deriving (Eq, Show, Generic, NFData)
+
+-- | A transaction announced by this peer.
+data TxAnnouncement = TxAnnouncement
+  { -- | when it may be requested (@reqtime@)
+    reqTime :: !Micros,
+    txState :: !TxRequestState
+  }
+  deriving (Eq, Show, Generic, NFData)
+
+-- | What the node keeps about the relay of transactions, double-spend
+-- proofs and addresses for this peer.
+data RelayState = RelayState
+  { -- | the peer wants transactions (@fRelayTxes@, @src\/net.h:850@)
+    relayTxes :: !Bool,
+    -- | the peer's Bloom filter (@pfilter@, @src\/net.h:854@). It is never
+    -- null upstream: an empty filter matches everything.
+    bloom :: !BloomFilter,
+    -- | hashes the peer knows (@filterInventoryKnown@, a rolling Bloom
+    -- filter upstream, an exact set here)
+    knownInv :: !(Set Hash256),
+    -- | transactions to announce (@setInventoryTxToSendTopoSorted@); the
+    -- order of the mempool is the order of arrival here
+    txsToSend :: ![TxHash],
+    -- | proof ids to announce (@vInventoryToSend@)
+    otherInvs :: ![Hash256],
+    -- | next time to announce transactions (@nNextInvSend@)
+    nextInvSend :: !Micros,
+    -- | the peer sent @mempool@ (@fSendMempool@)
+    sendMempool :: !Bool,
+    -- | when the node last answered @mempool@, in seconds, 0 for never
+    -- (@timeLastMempoolReq@)
+    lastMempoolReq :: !Int64,
+    -- | the peer's @feefilter@ (@minFeeFilter@)
+    minFeeFilter :: !Word64,
+    -- | the last @feefilter@ we sent (@lastSentFeeFilter@)
+    lastSentFeeFilter :: !Word64,
+    -- | next time to send @feefilter@ (@nextSendTimeFeeFilter@)
+    nextFeeFilter :: !Micros,
+    -- | addresses to send (@vAddrToSend@)
+    addrToSend :: ![NetworkAddressV2],
+    -- | addresses the peer knows (@addrKnown@, a rolling Bloom filter
+    -- upstream, an exact set here)
+    addrKnown :: !(Set AddrKey),
+    -- | we asked for addresses and wait for the reply (@fGetAddr@)
+    getAddrPending :: !Bool,
+    -- | we answered a @getaddr@ (@fSentAddr@)
+    sentAddr :: !Bool,
+    -- | the address rate limiter (@m_addr_token_bucket@)
+    addrTokens :: !Double,
+    -- | when the bucket was last filled (@m_addr_token_timestamp@)
+    addrTokenTime :: !Micros,
+    -- | next time to send addresses (@m_next_addr_send@)
+    nextAddrSend :: !Micros,
+    -- | next time to advertise our address (@m_next_local_addr_send@)
+    nextLocalAddrSend :: !Micros,
+    -- | this peer's transaction announcements (its part of @m_txrequest@)
+    announcements :: !(Map TxHash TxAnnouncement),
+    -- | proof ids to request (@dsproofGetDatasToBatch@)
+    dsProofsToRequest :: ![Hash256]
+  }
+  deriving (Eq, Show, Generic, NFData)
+
+-- | The state when a connection opens (@CNode@ constructor,
+-- @CNodeState@ constructor and @InitializeNode@).
+initialState :: Options -> Setup -> State
+initialState o s =
+  State
+    { conn = s,
+      perms = ps,
+      ourServices = localServices o ps,
+      rng = g1,
+      closing = False,
+      versionSent = False,
+      localNonce = nonce,
+      peerVersion = 0,
+      peerServices = 0,
+      peerStartHeight = -1,
+      peerSubVer = "",
+      client = False,
+      limitedNode = False,
+      extVersionExpected = False,
+      extVersionEnabled = False,
+      wantsAddrV2 = False,
+      connected = False,
+      verAckSent = False,
+      getAddrSent = False,
+      timeOffset = 0,
+      lastRecv = 0,
+      lastSend = 0,
+      pingNonceSent = 0,
+      pingStart = 0,
+      pingTime = Nothing,
+      minPingTime = Nothing,
+      pingQueued = False,
+      misbehavior = 0,
+      shouldDiscourage = False,
+      blockRejects = [],
+      preferredDownload = False,
+      blocks =
+        BlockState
+          { bestKnown = Nothing,
+            lastUnknown = Nothing,
+            bestHeaderSent = Nothing,
+            unconnecting = 0,
+            syncStarted = False,
+            headersSyncTimeout = 0,
+            stallingSince = 0,
+            inFlight = [],
+            downloadingSince = 0,
+            preferHeaders = False,
+            preferHeaderAndIds = False,
+            providesHeaderAndIds = False,
+            highBandwidthTo = False,
+            chainSync = ChainSync 0 Nothing False False,
+            lastBlockAnnouncement = 0,
+            toAnnounce = [],
+            blockInvs = [],
+            hashContinue = Nothing,
+            toRequest = []
+          },
+      relay =
+        RelayState
+          { relayTxes = False,
+            bloom = emptyFilter,
+            knownInv = Set.empty,
+            txsToSend = [],
+            otherInvs = [],
+            nextInvSend = 0,
+            sendMempool = False,
+            lastMempoolReq = 0,
+            minFeeFilter = 0,
+            lastSentFeeFilter = 0,
+            nextFeeFilter = 0,
+            addrToSend = [],
+            addrKnown = Set.empty,
+            getAddrPending = False,
+            sentAddr = False,
+            addrTokens = 1,
+            addrTokenTime = s.openedAt,
+            nextAddrSend = 0,
+            nextLocalAddrSend = 0,
+            announcements = Map.empty,
+            dsProofsToRequest = []
+          }
+    }
+  where
+    ps = effectivePermissions o s
+    (nonce, g1) = nextWord64 (Rng s.seed)
+
+-- | The filter of a new connection, @CBloomFilter()@: empty, so that it
+-- matches every transaction (@src\/net.cpp:2878@).
+emptyFilter :: BloomFilter
+emptyFilter = BloomFilter Seq.empty 0 0 BloomUpdateNone
+
+-- | The key of an address in @addrKnown@: network, bytes and port
+-- (@CService::GetKey@).
+type AddrKey = (Word8, ByteString, Word16)
+
+-- | The key of an address.
+addrKey :: NetworkAddressV2 -> AddrKey
+addrKey a = (addressNetworkId a.network, a.address, a.port)
+
+-- | The language of the handlers: a reader of the options and the
+-- environment, a writer of effects, and the state.
+type M = RWS (Options, Env) [Effect] State
+
+-- | Run a handler.
+runM :: Options -> Env -> State -> M () -> (State, [Effect])
+runM o e s m = let ((), s', es) = runRWS m (o, e) s in (s', es)
+
+-- | The options.
+options :: M Options
+options = asks fst
+
+-- | The environment.
+env :: M Env
+env = asks snd
+
+-- | The current time.
+nowM :: M Micros
+nowM = asks (\(_, e) -> e.now)
+
+-- | Produce an effect.
+emit :: Action -> Cite -> M ()
+emit a c = tell [Effect a c]
+
+-- | Send a message, and note the time for the inactivity check.
+send :: Message -> Cite -> M ()
+send m c = do
+  t <- nowM
+  modify' (\s -> s {lastSend = t})
+  emit (Send m) c
+
+-- | Drop the message without an answer.
+ignore :: Cite -> M ()
+ignore = emit Ignore
+
+-- | An effect on the rest of the node that the peer does not see.
+process :: Text -> Cite -> M ()
+process t = emit (Process t)
+
+-- | Add to the ban score, as @Misbehaving@ does
+-- (@src\/net_processing.cpp:894-919@): a score of 0 does nothing, and the
+-- threshold is crossed when the old score was below @-banscore@ and the new
+-- one is not. The node acts on it after the message, or at the next pass of
+-- @SendMessages@.
+misbehaving :: Int -> Cite -> M ()
+misbehaving n c = when (n /= 0) $ do
+  o <- options
+  old <- gets (.misbehavior)
+  let new = old + n
+  emit (Misbehave n) c
+  modify' $ \s ->
+    s
+      { misbehavior = new,
+        shouldDiscourage =
+          s.shouldDiscourage || (new >= o.banScore && old < o.banScore)
+      }
+
+-- | Close the connection (@fDisconnect = true@).
+disconnect :: DisconnectReason -> Cite -> M ()
+disconnect r c = do
+  modify' (\s -> s {closing = True})
+  emit (Disconnect r) c
+
+-- | Change the block state.
+modifyBlocks :: (BlockState -> BlockState) -> M ()
+modifyBlocks f = modify' (\s -> s {blocks = f s.blocks})
+
+-- | Change the relay state.
+modifyRelay :: (RelayState -> RelayState) -> M ()
+modifyRelay f = modify' (\s -> s {relay = f s.relay})
+
+-- | 64 random bits.
+randomWord :: M Word64
+randomWord = do
+  g <- gets (.rng)
+  let (w, g') = nextWord64 g
+  modify' (\s -> s {rng = g'})
+  return w
+
+-- | A delay from an exponential distribution of this mean
+-- (@PoissonNextSend@, @src\/net.cpp:2980-2984@).
+randomDelay :: Micros -> M Micros
+randomDelay mean = do
+  g <- gets (.rng)
+  let (d, g') = poissonDelay mean g
+  modify' (\s -> s {rng = g'})
+  return d
+
+-- | The peer has this permission.
+hasPerm :: Permission -> M Bool
+hasPerm p = gets (Set.member p . (.perms))
+
+-- | The type of the connection.
+connType :: M ConnectionType
+connType = gets (.conn.connectionType)
+
+-- | The peer connected to the node.
+isInbound :: M Bool
+isInbound = (== Inbound) <$> connType
+
+-- | The node is in initial block download.
+inIBD :: M Bool
+inIBD = (.initialBlockDownload) <$> env
+
+-- | Queue an address for the peer, as @CNode::PushAddress@ does
+-- (@src\/net.h:993-1010@): only an address the peer does not know, and that
+-- it can read: an @addrv2@-only address goes only to a peer that sent
+-- @sendaddrv2@. A full queue of 1000 has a random entry replaced.
+pushAddress :: NetworkAddressV2 -> M ()
+pushAddress a = do
+  s <- get
+  let known = addrKey a `Set.member` s.relay.addrKnown
+      readable = s.wantsAddrV2 || isJust (fromNetworkAddressV2 a)
+      valid = not (BS.null a.address)
+      queue = s.relay.addrToSend
+  when (valid && not known && readable) $
+    if length queue >= maxAddrToSend
+      then do
+        w <- randomWord
+        let i = fromIntegral (w `mod` fromIntegral (length queue))
+            queue' = take i queue <> [a] <> drop (i + 1) queue
+        modifyRelay (\r -> r {addrToSend = queue'})
+      else modifyRelay (\r -> r {addrToSend = queue <> [a]})
+
+-- | A @reject@ message, if the code is one that the library can send. The
+-- reason is cut to 111 bytes (@MAX_REJECT_MESSAGE_LENGTH@).
+rejectMessage :: MessageCommand -> Word8 -> Text -> Maybe Hash256 -> Maybe Message
+rejectMessage cmd code reason h = do
+  c <- case code of
+    0x01 -> Just RejectMalformed
+    0x10 -> Just RejectInvalid
+    0x11 -> Just RejectObsolete
+    0x12 -> Just RejectDuplicate
+    0x40 -> Just RejectNonStandard
+    0x41 -> Just RejectDust
+    0x42 -> Just RejectInsufficientFee
+    0x43 -> Just RejectCheckpoint
+    _ -> Nothing
+  let r = BS.take maxRejectMessageLength (TE.encodeUtf8 reason)
+  return (MReject (Reject cmd c (VarString r) h))
+
+-- | Send a @reject@ if @-enablebip61@ is on (the default) and the code is
+-- one between 1 and 0xff that the library knows.
+sendReject :: MessageCommand -> Word8 -> Text -> Maybe Hash256 -> Cite -> M ()
+sendReject cmd code reason h c = do
+  o <- options
+  when o.enableBip61 $
+    mapM_ (`send` c) (rejectMessage cmd code reason h)
diff --git a/src/Haskoin/Network/Protocol/BitcoinCore.hs b/src/Haskoin/Network/Protocol/BitcoinCore.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Network/Protocol/BitcoinCore.hs
@@ -0,0 +1,350 @@
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- |
+-- Module      : Haskoin.Network.Protocol.BitcoinCore
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- The protocol machine of Bitcoin Core 32.1 (commit @f0de87f0@), the
+-- reference node of the Bitcoin networks: how it treats one peer, message by
+-- message and timer by timer, as a pure function.
+--
+-- = Purpose
+--
+-- A program that talks to Bitcoin Core, such as haskoin-node, must know
+-- what the node does with each message: which ones it drops before the
+-- handshake, which ones close the connection, which ones get the address
+-- discouraged, when it pings and how long it waits. None of that is in the
+-- BIPs. This module is a translation of the code that decides it,
+-- @ProcessMessage@, @SendMessages@ and their helpers in
+-- @src\/net_processing.cpp@, and the transport and inactivity rules of
+-- @src\/net.cpp@, with a t'Cite' of the deciding line behind every t'Effect'.
+-- It serves as an oracle for tests, and as a map for a reader of the
+-- upstream code. The report @doc\/protocol\/bitcoin-core.md@ of the
+-- repository describes the same rules in prose, with links to the same
+-- lines, and changes with this module.
+--
+-- = Use
+--
+-- > let o = defaultOptions btc
+-- >     s0 = start o setup
+-- >     (s1, effects) = step o env s0 (Receive (MVersion ver))
+--
+-- The machine is one connection. 'Receive' is one message going through
+-- @ProcessMessage@, followed by the punishment check that opens
+-- @SendMessages@, since upstream runs @SendMessages@ for the same peer
+-- right after each message. 'Tick' is the rest of @SendMessages@ and the
+-- inactivity checks of the socket thread, which upstream runs about every
+-- 100 milliseconds; a caller should tick as often, and before each message
+-- if it wants upstream's order exactly. 'Notify' is news from the rest of
+-- the node: a new tip, a transaction to announce, a block to request.
+--
+-- An outbound connection sends the node's @version@ on its first pass. A
+-- message from an outbound peer that arrives before that pass makes the
+-- machine send the @version@ first, as upstream processes no message
+-- before it.
+--
+-- = The four networks
+--
+-- One machine serves the four Bitcoin chains; 'defaultOptions' fills in
+-- what differs:
+--
+-- * __main__ (@btc@): minimum chain work @0x0145ec036acc5ba740052af1a0@,
+--   magic @f9beb4d9@. While the tip has less work, @getheaders@ gets an
+--   empty answer, @sendheaders@ is not sent, and an outbound peer whose
+--   chain has less work is dropped during initial block download.
+-- * __testnet3__ (@btcTest@): minimum chain work
+--   @0x17f49f702147f10c0eb6@, magic @0b110907@. Upstream skips the
+--   difficulty transition check of the low-work headers sync, which the
+--   t'Env' answers.
+-- * __testnet4__ (@btcTest4@): minimum chain work
+--   @0x0e346a558455ade8eca9@, magic @1c163f28@; BIP 94 is enforced by
+--   header validation, in the t'Env'.
+-- * __regtest__ (@btcRegTest@): minimum chain work 0, so @getheaders@ is
+--   always answered, @sendheaders@ goes out as soon as the peer is known to
+--   have any block, and the anti-DoS threshold of headers is the work of
+--   the tip less 144 blocks. Upstream allows a mock clock on regtest; the
+--   machine always takes the time from the t'Env'.
+--
+-- Every timer, limit and protocol version is the same on the four chains,
+-- and so is the block interval of 600 seconds that several timers scale
+-- by.
+--
+-- = Connection types and permissions
+--
+-- 'start' expands the configured 'Permissions' as upstream does: a bare
+-- @-whitelist@ ('PermImplicit') gives 'PermNoBan' (which includes
+-- 'PermDownload'), 'PermMempool', and 'PermRelay' unless @-blocksonly@ is
+-- set or @-whitelistrelay@ is off, and 'PermForceRelay' (which includes
+-- 'PermRelay') with @-whitelistforcerelay@. A peer with 'PermNoBan' and a
+-- 'Manual' connection are never punished for misbehaviour; a local peer,
+-- and an inbound Tor peer, whose address is that of the local proxy, are
+-- disconnected without discouragement. The connection types differ in
+-- what the node expects of the peer's services, whether it relays
+-- transactions and addresses, and the timers that apply; the report has
+-- the table.
+--
+-- = What is simplified
+--
+-- Validation, the mempool and every decision that spans peers come from the
+-- t'Env' or as a 'Notification'; each submodule says what it leaves out.
+-- The machine has no send buffer, so the back-pressure of @fPauseSend@ is
+-- not modelled, and a @getdata@ is served at once. Upstream keeps
+-- rolling Bloom filters of known transactions and addresses, which forget;
+-- the machine keeps sets, which do not.
+module Haskoin.Network.Protocol.BitcoinCore
+  ( -- * Machine
+    upstream,
+    Options (..),
+    defaultOptions,
+    State,
+    start,
+    step,
+
+    -- * Inspection
+    handshakeComplete,
+    versionReceived,
+    isDisconnected,
+    discouragementPending,
+    blocksInFlight,
+    pingOutstanding,
+    txRelayEnabled,
+    addrRelayEnabled,
+    permissionsOf,
+    commonVersionOf,
+    peerServicesOf,
+    ourServicesOf,
+    wtxidRelayOf,
+    wantsAddrV2Of,
+    prefersHeadersOf,
+    compactBlocksOf,
+    feeFilterOf,
+    syncStartedOf,
+    expandPermissions,
+    localServices,
+  )
+where
+
+import Control.Monad (unless, when)
+import Data.ByteString qualified as B
+import Data.Bytes.Get (getWord64le, getWord8, runGetS)
+import Data.Int (Int32)
+import Data.Word (Word64)
+import Haskoin.Network.Common (Addr (..), AddrV2 (..), Inv (..), toNetworkAddressV2)
+import Haskoin.Network.CompactBlock (SendCompact (..))
+import Haskoin.Network.Message (Message (..))
+import Haskoin.Network.Protocol.BitcoinCore.Blocks
+import Haskoin.Network.Protocol.BitcoinCore.Constants
+import Haskoin.Network.Protocol.BitcoinCore.Handshake
+import Haskoin.Network.Protocol.BitcoinCore.Machine
+import Haskoin.Network.Protocol.BitcoinCore.Relay
+import Haskoin.Network.Protocol.BitcoinCore.State
+import Haskoin.Network.Protocol.Types
+
+-- | One step of the machine: the new state and what the node did, in
+-- order. Nothing happens to a connection that the node already decided to
+-- close.
+step :: Options -> Env -> State -> Input -> (State, [Effect])
+step o e s input
+  | s.disconnected = (s, [])
+  | otherwise = runM o e s $ case input of
+      Receive m -> do
+        received
+        outboundVersionFirst
+        scoped (processMessage m)
+        _ <- maybeDiscourageAndDisconnect
+        return ()
+      BadFrame err -> do
+        received
+        outboundVersionFirst
+        badFrame err
+      Tick -> do
+        scoped inactivityCheck
+        alive <- not . (.disconnected) <$> getS
+        when alive sendMessages
+      Notify n -> notify n
+  where
+    received = do
+      t <- now
+      modifyS $ \st -> st {lastRecv = Just t}
+    outboundVersionFirst = do
+      st <- getS
+      when (st.connectionType /= Inbound && not st.versionSent) $ do
+        pushNodeVersion
+        modifyS $ \x -> x {versionSent = True}
+
+-- | @ProcessMessage@ (@src\/net_processing.cpp@, line 3828): the gates in
+-- upstream order, then the handler of the command.
+processMessage :: Message -> M ()
+processMessage m = do
+  case m of
+    MVersion v -> handleVersion v >> stop
+    _ -> return ()
+  s <- getS
+  when (s.peerVersion == Nothing) $ do
+    ignore $ netProcessing 4076 "non-version message before version handshake"
+    stop
+  case m of
+    MVerAck -> handleVerAck >> stop
+    MSendHeaders -> handleSendHeaders >> stop
+    MSendCompact sc -> handleSendCmpct sc >> stop
+    MOther "sendcmpct" p -> rawSendCmpct p >> stop
+    MWtxidRelay -> handleWtxidRelay >> stop
+    MSendAddrV2 -> handleSendAddrV2 >> stop
+    MOther "feature" p -> handleFeature p >> stop
+    MSendTxRcncl r -> handleSendTxRcncl r >> stop
+    _ -> return ()
+  unless s.successfullyConnected $ do
+    ignore $ netProcessing 4321 "Unsupported message prior to verack"
+    stop
+  when (s.connectionType == PrivateBroadcast) $
+    case m of
+      MPong _ -> return ()
+      MGetData _ -> return ()
+      _ -> do
+        ignore $ netProcessing 4327 "Ignoring incoming message on private broadcast connection"
+        stop
+  case m of
+    MAddr (Addr as) -> handleAddrs False (map toNetworkAddressV2 as)
+    MAddrV2 (AddrV2 as) -> handleAddrs True as
+    MInv inv -> handleInv inv
+    MGetData gd -> handleGetData gd
+    MGetBlocks gb -> handleGetBlocks gb
+    MGetBlockTxn r -> handleGetBlockTxn r
+    MGetHeaders gh -> handleGetHeaders gh
+    MTx tx -> handleTx tx
+    MCompactBlock cb -> handleCmpctBlock cb
+    MBlockTxn bt -> handleBlockTxn bt
+    MHeaders hs -> handleHeaders hs
+    MBlock b -> handleBlock b
+    MGetAddr -> handleGetAddr
+    MMempool -> handleMempool
+    MPing p -> handlePing p
+    MPong p -> handlePong p
+    MFilterLoad f -> handleFilterLoad f
+    MFilterAdd f -> handleFilterAdd f
+    MFilterClear -> handleFilterClear
+    MFeeFilter f -> handleFeeFilter f
+    MGetCFilters r -> handleGetCFilters r
+    MGetCFHeaders r -> handleGetCFHeaders r
+    MGetCFCheckpt r -> handleGetCFCheckpt r
+    MNotFound nf -> handleNotFound nf
+    _ -> ignore $ netProcessing 5360 "Unknown message type"
+
+-- | A @sendcmpct@ that the caller passes as raw bytes. t'SendCompact' reads
+-- the announce byte as a flag, so the one rule it cannot carry, an announce
+-- byte above 1, which is misbehaviour, is checked here (line 4172).
+rawSendCmpct :: B.ByteString -> M ()
+rawSendCmpct p =
+  case runGetS ((,) <$> getWord8 <*> getWord64le) p of
+    Left _ -> ignore $ netProcessing 5493 "Exception caught"
+    Right (hb, v)
+      | hb > 1 -> do
+          let c = netProcessing 4173 "invalid sendcmpct announce field"
+          misbehaving c
+          ignore c
+      | otherwise -> handleSendCmpct (SendCompact (hb == 1) v)
+
+-- | @SendMessages@ (line 6059), after the inactivity checks.
+sendMessages :: M ()
+sendMessages = do
+  gone <- maybeDiscourageAndDisconnect
+  when gone stop
+  s0 <- getS
+  when (s0.connectionType /= Inbound && not s0.versionSent) $ do
+    pushNodeVersion
+    modifyS $ \x -> x {versionSent = True}
+  s <- getS
+  unless s.successfullyConnected stop
+  t <- now
+  when (s.connectionType == PrivateBroadcast) $ do
+    when (s.connectedAt + privateBroadcastLifetime < t) $
+      disconnect Timeout $
+        netProcessing 6093 "did not complete the transaction send within the lifetime"
+    stop
+  when (s.connectionType == AddrFetch && t - s.connectedAt > 10 * avgAddressBroadcastInterval) $ do
+    disconnect Done $ netProcessing 6100 "addrfetch connection timeout"
+    stop
+  scoped maybeSendPing
+  whenM ((.disconnected) <$> getS) stop
+  maybeSendAddr
+  maybeSendSendHeaders
+  initialGetHeaders
+  blockEntries <- sendBlockAnnouncements
+  txEntries <- sendTxTrickle
+  sendInvs (blockEntries ++ txEntries)
+  scoped blockTimeouts
+  whenM ((.disconnected) <$> getS) stop
+  considerEviction
+  whenM ((.disconnected) <$> getS) stop
+  maybeSendFeeFilter
+  where
+    sendInvs [] = return ()
+    sendInvs xs = do
+      let (now', rest) = splitAt maxInvSz xs
+      send (MInv (Inv now')) $ netProcessing 6438 "inv"
+      sendInvs rest
+
+-- | News from the rest of the node.
+notify :: Notification -> M ()
+notify n = case n of
+  NewTip hs -> newTip hs
+  TxAccepted tx -> txAccepted tx
+  RelayAddress a -> relayAddress a
+  HighBandwidth on -> highBandwidth on
+  RequestBlock h -> requestBlock h
+  RequestTx h -> requestTx h
+  OperatorDisconnect -> disconnect Resources $ netCpp 3967 "disconnect by id"
+  MarkStalling -> markStalling
+  PingRequested -> modifyS $ \s -> s {pingQueued = True}
+  NewPoWValidBlock h -> newPoWValidBlock h
+  Evict -> disconnect Resources $ netCpp 1749 "selected for eviction"
+
+-- | The permissions of the peer, expanded.
+permissionsOf :: State -> Permissions
+permissionsOf s = s.permissions
+
+-- | The common protocol version (@m_greatest_common_version@).
+commonVersionOf :: State -> Int32
+commonVersionOf s = s.commonVersion
+
+-- | The services the peer offered in its @version@.
+peerServicesOf :: State -> Word64
+peerServicesOf s = s.theirServices
+
+-- | The services the node offers to the peer.
+ourServicesOf :: State -> Word64
+ourServicesOf s = s.ourServices
+
+-- | The peer relays transactions by wtxid (BIP 339).
+wtxidRelayOf :: State -> Bool
+wtxidRelayOf s = s.wtxidRelay
+
+-- | The peer asked for @addrv2@ (BIP 155).
+wantsAddrV2Of :: State -> Bool
+wantsAddrV2Of s = s.wantsAddrV2
+
+-- | The peer sent @sendheaders@.
+prefersHeadersOf :: State -> Bool
+prefersHeadersOf s = s.blocks.prefersHeaders
+
+-- | Compact blocks: whether the peer offered them, whether it wants them
+-- pushed, and whether the node chose it for high bandwidth.
+compactBlocksOf :: State -> (Bool, Bool, Bool)
+compactBlocksOf s = (s.blocks.providesCmpct, s.blocks.requestedHbCmpct, s.blocks.highBandwidthTo)
+
+-- | The fee filter that the peer sent, if transaction relay exists.
+feeFilterOf :: State -> Maybe Word64
+feeFilterOf s = (.feeFilterReceived) <$> s.txRelay
+
+-- | The initial headers sync started with the peer (@fSyncStarted@).
+syncStartedOf :: State -> Bool
+syncStartedOf s = s.blocks.syncStarted
diff --git a/src/Haskoin/Network/Protocol/BitcoinCore/Blocks.hs b/src/Haskoin/Network/Protocol/BitcoinCore/Blocks.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Network/Protocol/BitcoinCore/Blocks.hs
@@ -0,0 +1,1282 @@
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE MultiWayIf #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- |
+-- Module      : Haskoin.Network.Protocol.BitcoinCore.Blocks
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- Headers and blocks on a connection to Bitcoin Core 32.1: the messages
+-- that move them (@getheaders@, @headers@, @getblocks@, the block part of
+-- @inv@ and @getdata@, @block@, @sendheaders@, @sendcmpct@, @cmpctblock@,
+-- @getblocktxn@, @blocktxn@, and the BIP 157 requests), the announcements
+-- of new blocks, and the timers of the block download.
+--
+-- Bitcoin Core treats headers as the backbone of the download: a peer that
+-- announces a block it does not know gets a @getheaders@, not a
+-- @getdata@; blocks are requested only once their headers connect. The
+-- rules against abuse follow from that. A header that fails validation, or
+-- a block that does, gets the peer discouraged, but only when the fault is
+-- the peer's: a block from a compact block reconstruction may be wrong
+-- because of a collision of short ids, and is forgiven.
+--
+-- What the machine leaves to the t'Env':
+--
+-- * validation of headers and blocks (@checkHeaders@ of t'Env',
+--   @checkBlock@ of t'Env'), and the block index (@lookupBlock@ of t'Env',
+--   @blockAtHeight@ of t'Env');
+-- * the choice of the blocks to download from which peer
+--   (@FindNextBlocksToDownload@), which spans peers: the node asks for a
+--   block with 'RequestBlock' and marks a staller with 'MarkStalling';
+-- * the low-work headers sync (@HeadersSyncState@), whose commitments the
+--   machine does not keep: it follows the presync as long as
+--   @checkHeaders@ of t'Env' says the headers have too little work, and treats
+--   any other verdict as the end of it;
+-- * the choice of high-bandwidth compact block peers, which comes as
+--   'HighBandwidth'.
+--
+-- Where upstream asks whether one block is an ancestor of another
+-- (@GetAncestor@), the machine can answer only for blocks of the active
+-- chain, through @blockAtHeight@ of t'Env'; for a block off the active chain it
+-- compares hashes. The difference shows only in announcements after a
+-- reorganisation.
+module Haskoin.Network.Protocol.BitcoinCore.Blocks
+  ( -- * Messages
+    handleSendHeaders,
+    handleSendCmpct,
+    blockInvs,
+    handleGetHeaders,
+    handleHeaders,
+    handleGetBlocks,
+    getBlockData,
+    handleBlock,
+    handleCmpctBlock,
+    handleGetBlockTxn,
+    handleBlockTxn,
+    handleGetCFilters,
+    handleGetCFHeaders,
+    handleGetCFCheckpt,
+
+    -- * Sending
+    maybeSendSendHeaders,
+    initialGetHeaders,
+    sendBlockAnnouncements,
+    blockTimeouts,
+    considerEviction,
+
+    -- * Notifications
+    newTip,
+    newPoWValidBlock,
+    highBandwidth,
+    requestBlock,
+    markStalling,
+
+    -- * Helpers
+    canServeBlocks,
+    syncFromPeer,
+  )
+where
+
+import Control.Monad (forM_, unless, when)
+import Data.Bits ((.&.))
+import Data.List (find)
+import Data.Maybe (fromMaybe, isJust, isNothing)
+import Data.Word (Word32)
+import Haskoin.Block.Common
+  ( Block (..),
+    BlockHash (..),
+    BlockHeader (..),
+    BlockHeight,
+    BlockLocator,
+    GetBlocks (..),
+    GetHeaders (..),
+    Headers (..),
+    headerHash,
+  )
+import Haskoin.Block.Headers (headerWork)
+import Haskoin.Network.BlockFilter
+  ( GetCFCheckpt (..),
+    GetCFHeaders (..),
+    GetCFilters (..),
+  )
+import Haskoin.Network.Common
+  ( GetData (..),
+    Inv (..),
+    InvType (..),
+    InvVector (..),
+    VarInt (..),
+    nodeBloom,
+    nodeCompactFilters,
+    nodeNetwork,
+    nodeNetworkLimited,
+    nodeWitness,
+  )
+import Haskoin.Network.CompactBlock
+  ( BlockTxn (..),
+    CompactBlock (..),
+    GetBlockTxn (..),
+    SendCompact (..),
+  )
+import Haskoin.Network.Data (Network (..))
+import Haskoin.Network.Message (Message (..))
+import Haskoin.Network.Protocol.BitcoinCore.Constants
+import Haskoin.Network.Protocol.BitcoinCore.Machine
+import Haskoin.Network.Protocol.BitcoinCore.State
+import Haskoin.Network.Protocol.Types
+import Haskoin.Transaction.Common (Tx (..))
+
+-- | The zero hash, the stop hash of every locator the node sends.
+zeroHash :: BlockHash
+zeroHash = "0000000000000000000000000000000000000000000000000000000000000000"
+
+-- | @CanServeBlocks@: the peer offers @NODE_NETWORK@ or
+-- @NODE_NETWORK_LIMITED@.
+canServeBlocks :: State -> Bool
+canServeBlocks s = s.theirServices .&. (nodeNetwork + nodeNetworkLimited) /= 0
+
+-- | The inventory type of a block request (@GetFetchFlags@): with witness
+-- when the peer offers @NODE_WITNESS@.
+blockRequest :: State -> BlockHash -> InvVector
+blockRequest s (BlockHash h)
+  | s.theirServices .&. nodeWitness /= 0 = InvVector InvWitnessBlock h
+  | otherwise = InvVector InvBlock h
+
+-- | @CanDirectFetch@: the tip is less than 20 block intervals old.
+canDirectFetch :: M Bool
+canDirectFetch = do
+  e <- env
+  o <- opts
+  let spacing = fromIntegral o.network.targetSpacing
+  return (fromIntegral e.tip.time > e.now `div` 1000000 - 20 * spacing)
+
+-- | @GetAntiDoSWorkThreshold@: the work a new chain must show before its
+-- headers are stored, the larger of the minimum chain work and the work of
+-- the tip less 144 blocks of its own proof. The proof of the tip is
+-- estimated from the work of the tip's header.
+antiDoSThreshold :: M Integer
+antiDoSThreshold = do
+  e <- env
+  o <- opts
+  let proof = maybe 0 headerWork (e.headerOf e.tip.hash)
+  return (max o.minimumChainWork (e.tip.work - 144 * proof))
+
+-- | @MaybeSendGetHeaders@: send a @getheaders@ unless one went out less
+-- than 2 minutes ago and is still unanswered.
+maybeSendGetHeaders :: BlockLocator -> Cite -> M Bool
+maybeSendGetHeaders loc c = do
+  s <- getS
+  t <- now
+  let recent = maybe False (\l -> t - l <= headersResponseTime) s.blocks.lastGetHeaders
+  if recent
+    then return False
+    else do
+      send (MGetHeaders (GetHeaders locatorVersion loc zeroHash)) c
+      modifyBlocks $ \b -> b {lastGetHeaders = Just t}
+      return True
+
+-- | @ProcessBlockAvailability@ and @UpdateBlockAvailability@: raise the
+-- best block known to the peer when the node knows the block and it has
+-- more work; otherwise remember the hash for later.
+updateBlockAvailability :: BlockHash -> M ()
+updateBlockAvailability h = do
+  e <- env
+  processBlockAvailability
+  case e.lookupBlock h of
+    Just bi | bi.work > 0 -> raiseBestKnown bi
+    _ -> modifyBlocks $ \b -> b {lastUnknownBlock = Just h}
+
+-- | @ProcessBlockAvailability@: promote the last unknown block once the
+-- node knows it.
+processBlockAvailability :: M ()
+processBlockAvailability = do
+  s <- getS
+  e <- env
+  forM_ s.blocks.lastUnknownBlock $ \u ->
+    case e.lookupBlock u of
+      Just bi | bi.work > 0 -> do
+        raiseBestKnown bi
+        modifyBlocks $ \b -> b {lastUnknownBlock = Nothing}
+      _ -> return ()
+
+-- | Set the best known block if it has at least the work of the last one.
+raiseBestKnown :: BlockInfo -> M ()
+raiseBestKnown bi = do
+  e <- env
+  s <- getS
+  let bestWork = maybe (-1) (.work) (s.blocks.bestKnownBlock >>= e.lookupBlock)
+  when (bi.work >= bestWork) $
+    modifyBlocks $
+      \b -> b {bestKnownBlock = Just bi.hash}
+
+-- | The work of the best block known to the peer.
+bestKnownWork :: M (Maybe Integer)
+bestKnownWork = do
+  s <- getS
+  e <- env
+  return $ (.work) <$> (s.blocks.bestKnownBlock >>= e.lookupBlock)
+
+-- | @PeerHasHeader@: the block is an ancestor of the best block known to
+-- the peer or of the best header sent to it. Ancestors are known only on
+-- the active chain.
+peerHasHeader :: BlockInfo -> M Bool
+peerHasHeader bi = do
+  s <- getS
+  e <- env
+  let ancestorOf h = case e.lookupBlock h of
+        Nothing -> False
+        Just top
+          | top.hash == bi.hash -> True
+          | top.inActiveChain && bi.inActiveChain -> top.height >= bi.height
+          | otherwise -> False
+  return $ maybe False ancestorOf s.blocks.bestKnownBlock || maybe False ancestorOf s.blocks.bestHeaderSent
+
+-- | @BlockRequestAllowed@: a block of the active chain, or a valid one at
+-- most 30 days older than the best header. Upstream also bounds the work
+-- between them; the machine checks the time only.
+blockRequestAllowed :: BlockInfo -> M Bool
+blockRequestAllowed bi = do
+  e <- env
+  return $
+    bi.inActiveChain
+      || ( bi.status == HaveData
+             && fromIntegral e.bestHeader.time - fromIntegral bi.time < staleRelayAge
+         )
+
+-- | Mark a block as requested from the peer (@BlockRequested@).
+blockRequested :: BlockHash -> Maybe CompactBlock -> M ()
+blockRequested h pc = do
+  t <- now
+  modifyBlocks $ \b ->
+    b
+      { inFlight = b.inFlight ++ [InFlight h pc False],
+        downloadingSince = if null b.inFlight then t else b.downloadingSince
+      }
+
+-- | @RemoveBlockRequest@ for this peer. The stalling mark goes with it.
+removeBlockRequest :: BlockHash -> M ()
+removeBlockRequest h = do
+  t <- now
+  modifyBlocks $ \b ->
+    let rest = filter ((/= h) . (.block)) b.inFlight
+        wasFirst = case b.inFlight of
+          (x : _) -> x.block == h
+          [] -> False
+     in if length rest == length b.inFlight
+          then b
+          else
+            b
+              { inFlight = rest,
+                stallingSince = Nothing,
+                downloadingSince = if wasFirst then max t b.downloadingSince else b.downloadingSince
+              }
+
+-- | @sendheaders@ (line 4160): the peer wants new blocks announced with
+-- headers. Accepted before @verack@; it cannot be undone.
+handleSendHeaders :: M ()
+handleSendHeaders = modifyBlocks $ \b -> b {prefersHeaders = True}
+
+-- | @sendcmpct@ (line 4165). An announce field above 1 is misbehaviour,
+-- even before @verack@; a version other than 2 is ignored.
+handleSendCmpct :: SendCompact -> M ()
+handleSendCmpct sc
+  | sc.version /= cmpctBlocksVersion =
+      ignore $ netProcessing 4178 "sendcmpct of an unknown version"
+  | otherwise =
+      modifyBlocks $ \b -> b {providesCmpct = True, requestedHbCmpct = sc.announce}
+
+-- | The block entries of an @inv@ (lines 4377 to 4438), after the
+-- transaction entries were looked at by the caller. Each @MSG_BLOCK@
+-- updates what the peer has. The last one the node lacks may trigger a
+-- @getheaders@: from a peer the headers sync started with, or from one
+-- other peer per new block. The node never asks for an announced block
+-- directly.
+blockInvs :: [BlockHash] -> M ()
+blockInvs hs = do
+  e <- env
+  best <- foldBest hs
+  forM_ best $ \_ -> do
+    s <- getS
+    when (s.blocks.syncStarted || not s.blocks.invTriggeredGetHeaders) $ do
+      _ <-
+        maybeSendGetHeaders (e.locatorFrom e.bestHeader.hash) $
+          netProcessing 4425 "getheaders after block inv"
+      unless s.blocks.syncStarted $
+        modifyBlocks $
+          \b -> b {invTriggeredGetHeaders = True}
+  where
+    foldBest = go Nothing
+    go acc [] = return acc
+    go acc (h : rest) = do
+      e <- env
+      s <- getS
+      updateBlockAvailability h
+      let have = isJust (e.lookupBlock h)
+          requested = any ((== h) . (.block)) s.blocks.inFlight || e.inFlightElsewhere h > 0
+      if not have && not e.loadingBlocks && not requested
+        then go (Just h) rest
+        else go acc rest
+
+-- | @getheaders@ (line 4629). Serves up to 2000 headers of the active
+-- chain after the fork point of the locator, or the one header named by
+-- the stop hash when the locator is empty. While the tip has less than the
+-- minimum chain work, a peer without 'PermDownload' gets an empty
+-- @headers@.
+handleGetHeaders :: GetHeaders -> M ()
+handleGetHeaders gh = do
+  e <- env
+  o <- opts
+  s <- getS
+  when (length gh.locator > maxLocatorSz) $ do
+    disconnect ProtocolViolation $ netProcessing 4636 "getheaders locator size too large"
+    stop
+  when e.loadingBlocks $ do
+    ignore $ netProcessing 4641 "Ignoring getheaders while importing/reindexing"
+    stop
+  when (e.tip.work < o.minimumChainWork && not (hasPermission PermDownload s)) $ do
+    send (MHeaders (Headers [])) $
+      netProcessing 4655 "active chain has too little work; sending empty response"
+    stop
+  start' <-
+    if null gh.locator
+      then case e.lookupBlock gh.stop of
+        Nothing -> do
+          ignore $ netProcessing 4666 "getheaders for an unknown stop hash"
+          stop
+        Just bi -> do
+          ok <- blockRequestAllowed bi
+          unless ok $ do
+            ignore $ netProcessing 4669 "ignoring request for old block header that isn't in the main chain"
+            stop
+          return (Just bi)
+      else return (fmap succ (Just (forkHeight e gh.locator)) >>= e.blockAtHeight)
+  let walk _ Nothing = []
+      walk n (Just bi)
+        | n <= 0 = []
+        | bi.hash == gh.stop = [bi]
+        | n == 1 = [bi]
+        | not (null gh.locator) || bi.inActiveChain = bi : walk (n - 1) (e.blockAtHeight (bi.height + 1))
+        | otherwise = [bi]
+      bis = if null gh.locator then maybe [] (: []) start' else walk maxHeadersResults start'
+      hdrs = [(h, VarInt 0) | Just h <- map (e.headerOf . (.hash)) bis]
+      lastSent = case bis of
+        [] -> e.tip.hash
+        _ -> (last bis).hash
+  modifyBlocks $ \b -> b {bestHeaderSent = Just lastSent}
+  send (MHeaders (Headers hdrs)) $ netProcessing 4704 "headers"
+
+-- | @FindForkInGlobalIndex@: the height of the first locator entry on the
+-- active chain, or of the genesis block when none is.
+forkHeight :: Env -> BlockLocator -> BlockHeight
+forkHeight e loc =
+  case find (.inActiveChain) [bi | Just bi <- map e.lookupBlock loc] of
+    Just bi -> bi.height
+    Nothing -> 0
+
+-- | @headers@ (line 5066): too many is misbehaviour, then
+-- @processHeaders@.
+handleHeaders :: Headers -> M ()
+handleHeaders (Headers hs) = do
+  e <- env
+  when e.loadingBlocks $ do
+    ignore $ netProcessing 5068 "Unexpected headers message received"
+    stop
+  when (length hs > maxHeadersResults) $ do
+    let c = netProcessing 5076 "headers message size"
+    misbehaving c
+    ignore c
+    stop
+  processHeaders False (map fst hs)
+
+-- | @ProcessHeadersMessage@ (line 3216). In order: an empty message ends a
+-- low-work sync; a header with bad proof of work or a broken sequence is
+-- misbehaviour; a running low-work sync takes the headers; headers that do
+-- not connect get a @getheaders@ back; headers of too little work start or
+-- feed the low-work sync; then validation, which may punish; then a full
+-- message asks for more, the peer's best block moves, and blocks may be
+-- fetched at once.
+processHeaders :: Bool -> [BlockHeader] -> M ()
+processHeaders viaCompact hs = do
+  e <- env
+  s0 <- getS
+  when (null hs) $ do
+    modifyBlocks $ \b -> b {lowWorkSync = Nothing, lastGetHeaders = Nothing}
+    stop
+  let verdict = e.checkHeaders hs
+      chained = and (zipWith (\a b -> b.prev == headerHash a) hs (drop 1 hs))
+      full = length hs == maxHeadersResults
+      lastH = headerHash (last hs)
+      firstPrev = case hs of
+        (x : _) -> x.prev
+        [] -> zeroHash
+  when (verdict == HeadersBadPoW) $ do
+    let c = netProcessing 2867 "header with invalid proof of work"
+    misbehaving c
+    ignore c
+    stop
+  when (not chained || verdict == HeadersNonContinuous) $ do
+    let c = netProcessing 2873 "non-continuous headers sequence"
+    misbehaving c
+    ignore c
+    stop
+  -- IsContinuationOfLowWorkHeadersSync
+  haveSync <- case s0.blocks.lowWorkSync of
+    Just chainStart
+      | verdict == HeadersLowWork ->
+          if full
+            then do
+              modifyBlocks $ \b -> b {lastGetHeaders = Nothing}
+              _ <-
+                maybeSendGetHeaders (lastH : e.locatorFrom chainStart) $
+                  netProcessing 2944 "more getheaders for low-work headers sync"
+              stop
+            else do
+              modifyBlocks $ \b -> b {lowWorkSync = Nothing}
+              ignore $
+                cite "src/headerssync.cpp" 103 "Initial headers sync aborted: incomplete headers message"
+              stop
+      | otherwise -> do
+          modifyBlocks $ \b -> b {lowWorkSync = Nothing}
+          return False
+    Nothing -> return False
+  parent <- case e.lookupBlock firstPrev of
+    Just p | verdict /= HeadersUnconnected -> return p
+    _ -> do
+      -- HandleUnconnectingHeaders
+      _ <-
+        maybeSendGetHeaders (e.locatorFrom e.bestHeader.hash) $
+          netProcessing 2903 "received header that does not connect: getheaders"
+      updateBlockAvailability lastH
+      stop
+  modifyBlocks $ \b -> b {lastGetHeaders = Nothing}
+  let known = e.lookupBlock lastH
+      ancestorOfBest = maybe False (\k -> k.inActiveChain || k.hash == e.bestHeader.hash) known
+      alreadyValidated = ancestorOfBest || hasPermission PermNoBan s0
+      claimed = parent.work + sum (map headerWork hs)
+  threshold <- antiDoSThreshold
+  when (not alreadyValidated && (verdict == HeadersLowWork || claimed < threshold)) $ do
+    if full
+      then do
+        modifyBlocks $ \b -> b {lowWorkSync = Just firstPrev, lastGetHeaders = Nothing}
+        _ <-
+          maybeSendGetHeaders (lastH : e.locatorFrom firstPrev) $
+            netProcessing 2944 "initial getheaders for low-work headers sync"
+        return ()
+      else ignore $ netProcessing 3056 "Ignoring low-work chain"
+    stop
+  case verdict of
+    HeadersInvalid _ -> punish "invalid header received" (netProcessing 2063 "invalid header received")
+    HeadersCachedInvalid
+      | s0.connectionType /= Inbound && not viaCompact -> do
+          let c = netProcessing 2056 "invalid header received (cached invalid)"
+          misbehaving c
+          ignore c
+          stop
+      | otherwise -> do
+          ignore $ netProcessing 2059 "cached invalid header: not punished"
+          stop
+    HeadersTimeFuture -> do
+      ignore $ netProcessing 2070 "header from the future: not punished"
+      stop
+    _ -> return ()
+  process "headers" $ netProcessing 3339 "ProcessNewBlockHeaders"
+  let lastHeight = case verdict of
+        HeadersAccepted h -> h
+        _ -> parent.height + fromIntegral (length hs)
+      lastInfo =
+        fromMaybe
+          BlockInfo
+            { hash = lastH,
+              height = lastHeight,
+              status = HeaderOnly,
+              inActiveChain = False,
+              work = claimed,
+              time = (last hs).timestamp
+            }
+          known
+      receivedNew = isNothing known
+  when (full && not haveSync) $ do
+    _ <-
+      maybeSendGetHeaders (lastH : e.locatorFrom firstPrev) $
+        netProcessing 3364 "more getheaders"
+    return ()
+  -- UpdatePeerStateForReceivedHeaders
+  processBlockAvailability
+  raiseBestKnown lastInfo
+  when (receivedNew && lastInfo.work > e.tip.work) $ do
+    t <- now
+    modifyBlocks $ \b -> b {lastBlockAnnouncement = Just t}
+  o <- opts
+  s1 <- getS
+  bestWork <- fromMaybe lastInfo.work <$> bestKnownWork
+  when
+    ( e.initialBlockDownload
+        && not full
+        && bestWork < o.minimumChainWork
+        && s1.connectionType `elem` [OutboundFullRelay, BlockRelayOnly]
+    )
+    $ do
+      disconnect Unsuitable $
+        netProcessing 3196 "outbound peer headers chain has insufficient work"
+      stop
+  when
+    ( s1.connectionType == OutboundFullRelay
+        && e.otherProtectedOutbound < 4
+        && bestWork >= e.tip.work
+        && not s1.blocks.chainSync.protect
+    )
+    $ modifyBlocks
+    $ \b -> b {chainSync = b.chainSync {protect = True}}
+  headersDirectFetch lastInfo (zip hs (scanl1 (+) (map headerWork hs)))
+  where
+    punish :: String -> Cite -> M ()
+    punish _ c = do
+      misbehaving c
+      ignore c
+      stop
+
+-- | @HeadersDirectFetchBlocks@ (line 3099): when the tip is recent and
+-- the new headers lead to more work, ask at once for up to 16 of their
+-- blocks that the node lacks, oldest first, as one @getdata@. A lone block
+-- from a peer that offers compact blocks is asked as a compact block when
+-- nothing else is in flight.
+headersDirectFetch :: BlockInfo -> [(BlockHeader, Integer)] -> M ()
+headersDirectFetch lastInfo _ = do
+  e <- env
+  o <- opts
+  direct <- canDirectFetch
+  when (direct && lastInfo.status /= Invalid && e.tip.work <= lastInfo.work) $ do
+    s <- getS
+    let walk acc h n
+          | n > maxBlocksInTransitPerPeer = (acc, False)
+          | otherwise = case e.lookupBlock h of
+              Just bi | bi.inActiveChain -> (acc, True)
+              mbi ->
+                let have = maybe False ((== HaveData) . (.status)) mbi
+                    requested =
+                      any ((== h) . (.block)) s.blocks.inFlight || e.inFlightElsewhere h > 0
+                    acc' = if have || requested then acc else h : acc
+                 in case e.headerOf h of
+                      Just hd -> walk acc' hd.prev (length acc' + if have || requested then n else n)
+                      Nothing -> (acc', False)
+        (toFetch, reached) = walk [] lastInfo.hash (0 :: Int)
+    if not reached
+      then ignore $ netProcessing 3123 "Large reorg, won't direct fetch"
+      else do
+        let budget = maxBlocksInTransitPerPeer - length s.blocks.inFlight
+            chosen = take (max 0 budget) toFetch
+        forM_ chosen $ \h -> blockRequested h Nothing
+        unless (null chosen) $ do
+          let invs = map (blockRequest s) chosen
+              compact =
+                not o.blocksOnly
+                  && s.blocks.providesCmpct
+                  && length chosen == 1
+                  && e.otherBlocksInFlight + length s.blocks.inFlight == 0
+              invs' = case chosen of
+                [BlockHash one] | compact -> [InvVector InvCompactBlock one]
+                _ -> invs
+          send (MGetData (GetData invs')) $ netProcessing 3154 "headers direct fetch"
+
+-- | @getblocks@ (line 4495): queue up to 500 hashes of the active chain
+-- after the fork point, to go out as @inv@ at the next pass. The 500th
+-- becomes the continuation block.
+handleGetBlocks :: GetBlocks -> M ()
+handleGetBlocks gb = do
+  e <- env
+  o <- opts
+  when (length gb.locator > maxLocatorSz) $ do
+    disconnect ProtocolViolation $ netProcessing 4501 "getblocks locator size too large"
+    stop
+  let first = forkHeight e gb.locator + 1
+      pruneFloor = fromIntegral e.tip.height - 282 :: Integer
+      go n h acc
+        | n <= 0 = (reverse acc, Nothing)
+        | otherwise = case e.blockAtHeight h of
+            Nothing -> (reverse acc, Nothing)
+            Just bi
+              | bi.hash == gb.stop -> (reverse acc, Nothing)
+              | o.prune && (bi.status /= HaveData || fromIntegral bi.height <= pruneFloor) ->
+                  (reverse acc, Nothing)
+              | n == 1 -> (reverse (bi.hash : acc), Just bi.hash)
+              | otherwise -> go (n - 1 :: Int) (h + 1) (bi.hash : acc)
+      (hashes, cont) = go 500 first []
+  modifyBlocks $ \b ->
+    b
+      { forInvRelay = b.forInvRelay ++ hashes,
+        continuationBlock = maybe b.continuationBlock Just cont
+      }
+
+-- | @ProcessGetBlockData@ (line 2564): one block entry of a @getdata@.
+-- Unknown and unservable blocks get no answer at all, not even
+-- @notfound@.
+getBlockData :: InvVector -> M ()
+getBlockData iv = do
+  s <- getS
+  e <- env
+  o <- opts
+  let h = BlockHash iv.invHash
+      filtered = iv.invType == InvMerkleBlock
+  when (filtered && s.ourServices .&. nodeBloom == 0) $ do
+    disconnect ProtocolViolation $
+      netProcessing 2570 "filtered block request received when NODE_BLOOM service disabled"
+    stop
+  bi <- case e.lookupBlock h of
+    Nothing -> do
+      ignore $ netProcessing 2613 "getdata for an unknown block"
+      stop
+    Just x -> return x
+  ok <- blockRequestAllowed bi
+  unless ok $ do
+    ignore $ netProcessing 2616 "ignoring request for old block that isn't in the main chain"
+    stop
+  let historical = fromIntegral e.bestHeader.time - fromIntegral bi.time > (7 * 86400 :: Integer)
+  when
+    ( o.maxUploadTarget > 0
+        && e.historicalUploadTargetReached
+        && (historical || filtered)
+        && not (hasPermission PermDownload s)
+    )
+    $ do
+      disconnect Resources $ netProcessing 2625 "historical block serving limit reached"
+      stop
+  let limited = s.ourServices .&. nodeNetworkLimited /= 0 && s.ourServices .&. nodeNetwork == 0
+      depth = fromIntegral e.tip.height - fromIntegral bi.height :: Integer
+  when
+    ( not (hasPermission PermNoBan s)
+        && limited
+        && depth > fromIntegral nodeNetworkLimitedMinBlocks + 2
+    )
+    $ do
+      disconnect Resources $
+        netProcessing 2635 "Ignore block request below NODE_NETWORK_LIMITED threshold"
+      stop
+  when (bi.status /= HaveData) $ do
+    ignore $ netProcessing 2641 "getdata for a block without data"
+    stop
+  blk <- case e.blockData h of
+    Nothing -> do
+      disconnect Resources $ netProcessing 2674 "Block was pruned before it could be read"
+      stop
+    Just b -> return b
+  direct <- canDirectFetch
+  case iv.invType of
+    InvBlock -> send (MBlock (stripWitness blk)) $ netProcessing 2681 "block without witness"
+    InvWitnessBlock -> send (MBlock blk) $ netProcessing 2683 "block with witness"
+    InvMerkleBlock ->
+      case s.txRelay >>= (.bloomFilter) of
+        Nothing -> ignore $ netProcessing 2694 "filtered block request without a filter"
+        Just bf -> case e.filteredBlock bf h of
+          Nothing -> ignore $ netProcessing 2694 "filtered block request without a filter"
+          Just (mb, txs, bf') -> do
+            modifyTxRelay $ \r -> r {bloomFilter = Just bf'}
+            send (MMerkleBlock mb) $ netProcessing 2695 "merkleblock"
+            forM_ txs $ \tx ->
+              send (MTx (stripTx tx)) $ netProcessing 2703 "matched transaction of merkleblock"
+    InvCompactBlock
+      | direct && fromIntegral bi.height >= (fromIntegral e.tip.height - maxCmpctBlockDepth :: Int) ->
+          case e.compactBlockOf h of
+            Just cb -> send (MCompactBlock cb) $ netProcessing 2717 "cmpctblock"
+            Nothing -> send (MBlock blk) $ netProcessing 2720 "block instead of cmpctblock"
+      | otherwise -> send (MBlock blk) $ netProcessing 2720 "block instead of cmpctblock"
+    _ -> return ()
+  s' <- getS
+  when (s'.blocks.continuationBlock == Just h) $ do
+    let BlockHash th = e.tip.hash
+    send (MInv (Inv [InvVector InvBlock th])) $ netProcessing 2734 "continuation inv of getblocks"
+    modifyBlocks $ \b -> b {continuationBlock = Nothing}
+  where
+    stripTx tx = tx {witness = []}
+    stripWitness b = b {txs = map stripTx b.txs}
+
+-- | @block@ (line 5104). A block that does not match its own merkle root
+-- or witness commitment is misbehaviour when its parent is known. The
+-- block goes to validation, which reports through @BlockChecked@: an
+-- invalid block from this peer is punished by @MaybePunishNodeForBlock@.
+handleBlock :: Block -> M ()
+handleBlock blk = do
+  e <- env
+  when e.loadingBlocks $ do
+    ignore $ netProcessing 5108 "Unexpected block message received"
+    stop
+  let h = headerHash blk.header
+      verdict = e.checkBlock blk
+      parentKnown = isJust (e.lookupBlock blk.header.prev)
+  when (parentKnown && verdict == BlockMutated) $ do
+    let c = netProcessing 5123 "mutated block"
+    misbehaving c
+    removeBlockRequest h
+    ignore c
+    stop
+  removeBlockRequest h
+  processBlock False verdict h
+
+-- | @ProcessBlock@ and @BlockChecked@ (lines 3680 and 2328): hand the
+-- block to validation and judge the verdict. A block from a compact block
+-- reconstruction is judged leniently.
+processBlock :: Bool -> BlockVerdict -> BlockHash -> M ()
+processBlock viaCompact verdict _ = do
+  process "block" $ netProcessing 3683 "ProcessNewBlock"
+  s <- getS
+  case verdict of
+    BlockAccepted -> return ()
+    BlockDuplicate -> return ()
+    BlockInvalid blame _
+      | blame && not viaCompact -> misbehaving $ netProcessing 2047 "invalid block (consensus)"
+      | otherwise -> return ()
+    BlockMutated
+      | not viaCompact -> misbehaving $ netProcessing 2047 "invalid block (mutated)"
+      | otherwise -> return ()
+    BlockCachedInvalid
+      | not viaCompact && s.connectionType /= Inbound ->
+          misbehaving $ netProcessing 2056 "invalid block (cached invalid)"
+      | otherwise -> return ()
+    BlockMissingParent -> misbehaving $ netProcessing 2067 "invalid block (missing parent)"
+
+-- | @cmpctblock@ (line 4785). Ignored in blocks-only mode and from a peer
+-- that never offered compact blocks. A block the node did not ask for is
+-- taken only from a peer it chose for high bandwidth. When the block is
+-- near the tip, the node tries to rebuild it from its mempool and asks for
+-- the missing transactions with @getblocktxn@; a block too far ahead is
+-- treated as an announcement of its header.
+handleCmpctBlock :: CompactBlock -> M ()
+handleCmpctBlock cb = do
+  e <- env
+  o <- opts
+  s <- getS
+  when e.loadingBlocks $ do
+    ignore $ netProcessing 4789 "Unexpected cmpctblock message received"
+    stop
+  when o.blocksOnly $ do
+    ignore $ netProcessing 4791 "cmpctblock in blocks-only mode"
+    stop
+  unless s.blocks.providesCmpct $ do
+    ignore $ netProcessing 4799 "cmpctblock from a peer that did not send sendcmpct"
+    stop
+  let hdr = cb.header
+      h = headerHash hdr
+  prev <- case e.lookupBlock hdr.prev of
+    Nothing -> do
+      if not e.initialBlockDownload
+        then do
+          ok <-
+            maybeSendGetHeaders (e.locatorFrom e.bestHeader.hash) $
+              netProcessing 4817 "cmpctblock that does not connect: getheaders"
+          unless ok $ ignore $ netProcessing 4819 "cmpctblock that does not connect"
+        else ignore $ netProcessing 4819 "cmpctblock that does not connect"
+      stop
+    Just p -> return p
+  threshold <- antiDoSThreshold
+  let work = prev.work + headerWork hdr
+  when (work < threshold) $ do
+    ignore $ netProcessing 4822 "Ignoring low-work compact block"
+    stop
+  let known = e.lookupBlock h
+      receivedNew = isNothing known
+  case e.checkHeaders [hdr] of
+    HeadersInvalid _ -> punishCompact
+    HeadersBadPoW -> punishCompact
+    HeadersNonContinuous -> punishCompact
+    HeadersUnconnected -> punishCompact
+    HeadersCachedInvalid -> do
+      ignore $ netProcessing 2059 "cached invalid header via cmpctblock: not punished"
+      stop
+    HeadersTimeFuture -> do
+      ignore $ netProcessing 2070 "header from the future via cmpctblock: not punished"
+      stop
+    _ -> return ()
+  let info =
+        fromMaybe
+          BlockInfo
+            { hash = h,
+              height = prev.height + 1,
+              status = HeaderOnly,
+              inActiveChain = False,
+              work = work,
+              time = hdr.timestamp
+            }
+          known
+  processBlockAvailability
+  raiseBestKnown info
+  when (receivedNew && work > e.tip.work) $ do
+    t <- now
+    modifyBlocks $ \b -> b {lastBlockAnnouncement = Just t}
+  when (info.status == HaveData) $ do
+    ignore $ netProcessing 4870 "cmpctblock for a block the node has"
+    stop
+  s1 <- getS
+  let elsewhere = e.inFlightElsewhere h
+      mine = find ((== h) . (.block)) s1.blocks.inFlight
+      fromThisPeer = isJust mine
+      alreadyInFlight = elsewhere + (if fromThisPeer then 1 else 0)
+      firstInFlight = alreadyInFlight == 0 || (fromThisPeer && elsewhere == 0)
+  when (not fromThisPeer && not s1.blocks.highBandwidthTo) $ do
+    ignore $ netProcessing 4889 "unsolicited compact block"
+    stop
+  when (work <= e.tip.work) $ do
+    if fromThisPeer
+      then send (MGetData (GetData [blockRequest s1 h])) $ netProcessing 4899 "getdata for a block with less work"
+      else ignore $ netProcessing 4901 "compact block with less work than the tip"
+    stop
+  direct <- canDirectFetch
+  when (alreadyInFlight == 0 && not direct) $ do
+    ignore $ netProcessing 4906 "compact block while the tip is old"
+    stop
+  if fromIntegral info.height <= (fromIntegral e.tip.height + 2 :: Integer)
+    then
+      if (alreadyInFlight < maxCmpctBlocksInflightPerBlock && length s1.blocks.inFlight < maxBlocksInTransitPerPeer)
+        || fromThisPeer
+        then do
+          case mine of
+            Just ifl | isJust ifl.partial -> do
+              ignore $ netProcessing 4921 "already syncing this compact block"
+              stop
+            Just _ -> modifyBlocks $ \b -> b {inFlight = map (setPartial h) b.inFlight}
+            Nothing -> blockRequested h (Just cb)
+          case e.initCompact cb of
+            CompactInvalid -> do
+              removeBlockRequest h
+              let c = netProcessing 4929 "invalid compact block"
+              misbehaving c
+              ignore c
+            CompactFailed
+              | firstInFlight ->
+                  send (MGetData (GetData [blockRequest s1 h])) $
+                    netProcessing 4936 "compact block failed to reconstruct: getdata"
+              | otherwise -> do
+                  removeBlockRequest h
+                  ignore $ netProcessing 4939 "compact block failed to reconstruct"
+            CompactComplete blk -> completeFromCompact h blk
+            CompactMissing idx
+              | firstInFlight ->
+                  send (MGetBlockTxn (GetBlockTxn h idx)) $ netProcessing 4955 "getblocktxn"
+              | s1.blocks.highBandwidthTo
+                  && (s1.connectionType /= Inbound || alreadyInFlight < maxCmpctBlocksInflightPerBlock - 1) ->
+                  send (MGetBlockTxn (GetBlockTxn h idx)) $ netProcessing 4965 "getblocktxn (parallel)"
+              | otherwise -> do
+                  removeBlockRequest h
+                  ignore $ netProcessing 4968 "compact block: not asking for transactions"
+        else case e.initCompact cb of
+          CompactComplete blk -> do
+            process "block from compact block" $ netProcessing 5036 "ProcessBlock (reconstructed)"
+            processBlock True (e.checkBlock blk) h
+          _ -> ignore $ netProcessing 4980 "compact block failed optimistic reconstruction"
+    else
+      if fromThisPeer
+        then send (MGetData (GetData [blockRequest s1 h])) $ netProcessing 4996 "getdata for a compact block far ahead"
+        else processHeaders True [hdr]
+  where
+    setPartial h ifl
+      | ifl.block == h = ifl {partial = Just cb, filled = False}
+      | otherwise = ifl
+    punishCompact = do
+      let c = netProcessing 2063 "invalid header via cmpctblock"
+      misbehaving c
+      ignore c
+      stop
+
+-- | A block rebuilt from a compact block and its transactions goes to
+-- validation, judged as coming through a compact block.
+completeFromCompact :: BlockHash -> Block -> M ()
+completeFromCompact h blk = do
+  e <- env
+  removeBlockRequest h
+  processBlock True (e.checkBlock blk) h
+
+-- | @getblocktxn@ (line 4560): the transactions of a recent block, or the
+-- whole block when it is more than 10 blocks deep. An empty list of
+-- positions closes the connection; a position past the end is
+-- misbehaviour.
+handleGetBlockTxn :: GetBlockTxn -> M ()
+handleGetBlockTxn req = do
+  e <- env
+  when (null req.indexes) $ do
+    disconnect ProtocolViolation $ netProcessing 4567 "getblocktxn received with no transaction indexes"
+    stop
+  bi <- case e.lookupBlock req.hash of
+    Just bi | bi.status == HaveData -> return bi
+    _ -> do
+      ignore $ netProcessing 4595 "getblocktxn for a block we don't have"
+      stop
+  if fromIntegral bi.height >= (fromIntegral e.tip.height - maxBlockTxnDepth :: Int)
+    then case e.blockData req.hash of
+      Nothing -> ignore $ netProcessing 4595 "getblocktxn for a block we don't have"
+      Just blk -> do
+        let n = fromIntegral (length blk.txs) :: Word32
+        if any (>= n) req.indexes
+          then do
+            let c = netProcessing 2849 "getblocktxn with out-of-bounds tx indices"
+            misbehaving c
+            ignore c
+          else
+            send (MBlockTxn (BlockTxn req.hash [blk.txs !! fromIntegral i | i <- req.indexes])) $
+              netProcessing 2860 "blocktxn"
+    else getBlockData (InvVector InvWitnessBlock req.hash.get)
+
+-- | @blocktxn@ (line 5049) and @ProcessCompactBlockTxns@ (line 3697).
+handleBlockTxn :: BlockTxn -> M ()
+handleBlockTxn bt = do
+  e <- env
+  s <- getS
+  when e.loadingBlocks $ do
+    ignore $ netProcessing 5054 "Unexpected blocktxn message received"
+    stop
+  let h = bt.hash
+      elsewhere = e.inFlightElsewhere h
+  ifl <- case find (\i -> i.block == h && isJust i.partial) s.blocks.inFlight of
+    Nothing -> do
+      ignore $ netProcessing 3721 "block transactions for block we weren't expecting"
+      stop
+    Just i -> return i
+  when ifl.filled $ do
+    removeBlockRequest h
+    let c = netProcessing 3732 "previous compact block reconstruction attempt failed"
+    misbehaving c
+    ignore c
+    stop
+  let firstInFlight = elsewhere == 0
+  case ifl.partial of
+    Nothing -> return ()
+    Just cb -> case e.fillCompact cb bt.transactions of
+      CompactInvalid -> do
+        removeBlockRequest h
+        let c = netProcessing 3743 "invalid compact block/non-matching block transactions"
+        misbehaving c
+        ignore c
+      CompactComplete blk -> completeFromCompact h blk
+      _
+        | firstInFlight -> do
+            modifyBlocks $ \b -> b {inFlight = map markFilled b.inFlight}
+            send (MGetData (GetData [blockRequest s h])) $
+              netProcessing 3753 "compact block failed to reconstruct: getdata"
+        | otherwise -> do
+            removeBlockRequest h
+            ignore $ netProcessing 3756 "compact block failed to reconstruct"
+  where
+    markFilled i
+      | i.block == bt.hash = i {filled = True}
+      | otherwise = i
+
+-- | @PrepareBlockFilterRequest@ (line 3518): the checks that every BIP 157
+-- request passes. Every failure closes the connection, without
+-- discouragement.
+prepareFilterRequest :: Word32 -> Maybe Word32 -> BlockHash -> Int -> M ()
+prepareFilterRequest ftype mstart stopHash maxSize = do
+  s <- getS
+  e <- env
+  when (ftype /= 0 || s.ourServices .&. nodeCompactFilters == 0) $ do
+    disconnect ProtocolViolation $ netProcessing 3530 "peer requested unsupported block filter type"
+    stop
+  stopInfo <- case e.lookupBlock stopHash of
+    Nothing -> do
+      disconnect ProtocolViolation $ netProcessing 3542 "peer sent getcf* with unknown or old stop hash"
+      stop
+    Just bi -> do
+      ok <- blockRequestAllowed bi
+      unless ok $ do
+        disconnect ProtocolViolation $ netProcessing 3542 "peer sent getcf* with unknown or old stop hash"
+        stop
+      return bi
+  forM_ mstart $ \start' -> do
+    when (start' > stopInfo.height) $ do
+      disconnect ProtocolViolation $ netProcessing 3552 "peer sent getcf* with start height above stop height"
+      stop
+    when (fromIntegral (stopInfo.height - start') >= maxSize) $ do
+      disconnect ProtocolViolation $ netProcessing 3558 "peer requested too many cfilters/cfheaders"
+      stop
+
+-- | @getcfilters@ (line 3571).
+handleGetCFilters :: GetCFilters -> M ()
+handleGetCFilters r = do
+  prepareFilterRequest (fromIntegral r.filterType) (Just r.startHeight) r.stopHash maxGetCFiltersSize
+  e <- env
+  case e.blockFilters r of
+    Nothing -> ignore $ netProcessing 3589 "failed to find block filter"
+    Just fs -> forM_ fs $ \f -> send (MCFilter f) $ netProcessing 3596 "cfilter"
+
+-- | @getcfheaders@ (line 3600).
+handleGetCFHeaders :: GetCFHeaders -> M ()
+handleGetCFHeaders r = do
+  prepareFilterRequest (fromIntegral r.filterType) (Just r.startHeight) r.stopHash maxGetCFHeadersSize
+  e <- env
+  case e.blockFilterHeaders r of
+    Nothing -> ignore $ netProcessing 3624 "failed to find block filter header"
+    Just m -> send (MCFHeaders m) $ netProcessing 3635 "cfheaders"
+
+-- | @getcfcheckpt@ (line 3642).
+handleGetCFCheckpt :: GetCFCheckpt -> M ()
+handleGetCFCheckpt r = do
+  prepareFilterRequest (fromIntegral r.filterType) Nothing r.stopHash maxBound
+  e <- env
+  case e.blockFilterCheckpoint r of
+    Nothing -> ignore $ netProcessing 3668 "failed to find block filter header"
+    Just m -> send (MCFCheckpt m) $ netProcessing 3674 "cfcheckpt"
+
+-- | @MaybeSendSendHeaders@ (line 5817): once the peer is known to have a
+-- block with more than the minimum chain work, tell it to announce blocks
+-- with headers. Sent once.
+maybeSendSendHeaders :: M ()
+maybeSendSendHeaders = do
+  s <- getS
+  o <- opts
+  w <- bestKnownWork
+  when (not s.blocks.sentSendHeaders && s.commonVersion >= sendHeadersVersion) $
+    forM_ w $ \work ->
+      when (work > o.minimumChainWork) $ do
+        send MSendHeaders $ netProcessing 5832 "sendheaders"
+        modifyBlocks $ \b -> b {sentSendHeaders = True}
+
+-- | Whether the node syncs headers and blocks from the peer
+-- (@sync_blocks_and_headers_from_peer@, line 6123): a preferred download
+-- peer, or any peer that can serve blocks (not an address fetch) when there
+-- is no preferred one or nothing is in flight.
+syncFromPeer :: M Bool
+syncFromPeer = do
+  s <- getS
+  e <- env
+  return $
+    s.blocks.preferredDownload
+      || ( canServeBlocks s
+             && s.connectionType /= AddrFetch
+             && ( e.otherPreferredDownload == 0
+                    || e.otherBlocksInFlight + length s.blocks.inFlight == 0
+                )
+         )
+
+-- | The initial @getheaders@ (line 6146): to the first peer to sync from,
+-- or to every peer once the best header is less than a day old. It starts
+-- the headers sync timeout.
+initialGetHeaders :: M ()
+initialGetHeaders = do
+  s <- getS
+  e <- env
+  o <- opts
+  sync <- syncFromPeer
+  when (not s.blocks.syncStarted && canServeBlocks s && not e.loadingBlocks)
+    $ when
+      ( (e.otherSyncStarted == 0 && sync)
+          || fromIntegral e.bestHeader.time > e.now `div` 1000000 - 86400
+      )
+    $ do
+      let startFrom = maybe e.bestHeader.hash (.prev) (e.headerOf e.bestHeader.hash)
+          startHash = if e.bestHeader.height == 0 then e.bestHeader.hash else startFrom
+      sent <- maybeSendGetHeaders (e.locatorFrom startHash) $ netProcessing 6159 "initial getheaders"
+      when sent $ do
+        let behind = max 0 (e.now `div` 1000000 - fromIntegral e.bestHeader.time)
+            spacing = max 1 (fromIntegral o.network.targetSpacing)
+            timeout =
+              e.now + headersDownloadTimeoutBase + headersDownloadTimeoutPerHeader * behind `div` spacing
+        modifyBlocks $ \b -> b {syncStarted = True, headersSyncTimeout = Just timeout}
+
+-- | The block announcements of @SendMessages@ (lines 6178 to 6325): the
+-- new blocks queued by 'newTip' go out as one @cmpctblock@ to a peer that
+-- asked for high-bandwidth compact blocks, as @headers@ to a peer that
+-- sent @sendheaders@, and otherwise as an @inv@ of the newest; then the
+-- @inv@ of blocks queued by @getblocks@.
+sendBlockAnnouncements :: M [InvVector]
+sendBlockAnnouncements = do
+  e <- env
+  s <- getS
+  let queue = s.blocks.forHeadersRelay
+      b = s.blocks
+      revert0 =
+        (not b.prefersHeaders && (not b.requestedHbCmpct || length queue > 1))
+          || length queue > maxBlocksToAnnounce
+  processBlockAvailability
+  (revert, hdrs, bestIdx) <-
+    if revert0
+      then return (True, [], Nothing)
+      else collect e queue
+  revert' <-
+    if not revert && not (null hdrs)
+      then case bestIdx of
+        Just best
+          | length hdrs == 1 && b.requestedHbCmpct -> do
+              case e.compactBlockOf best.hash of
+                Just cb -> send (MCompactBlock cb) $ netProcessing 6262 "sending header-and-ids"
+                Nothing -> return ()
+              modifyBlocks $ \bs -> bs {bestHeaderSent = Just best.hash}
+              return False
+          | b.prefersHeaders -> do
+              send (MHeaders (Headers [(h, VarInt 0) | h <- hdrs])) $ netProcessing 6275 "headers announcement"
+              modifyBlocks $ \bs -> bs {bestHeaderSent = Just best.hash}
+              return False
+        _ -> return True
+      else return revert
+  when (revert' && not (null queue)) $ do
+    let lastHash = last queue
+    case e.lookupBlock lastHash of
+      Just bi -> do
+        has <- peerHasHeader bi
+        unless has $ modifyBlocks $ \bs -> bs {forInvRelay = bs.forInvRelay ++ [lastHash]}
+      Nothing -> return ()
+  modifyBlocks $ \bs -> bs {forHeadersRelay = []}
+  s' <- getS
+  let invs = [InvVector InvBlock h | BlockHash h <- s'.blocks.forInvRelay]
+  modifyBlocks $ \bs -> bs {forInvRelay = []}
+  return invs
+  where
+    collect :: Env -> [BlockHash] -> M (Bool, [BlockHeader], Maybe BlockInfo)
+    collect e queue = go queue Nothing False []
+      where
+        go [] best _ acc = return (False, reverse acc, best)
+        go (h : rest) best found acc =
+          case e.lookupBlock h of
+            Nothing -> return (True, [], Nothing)
+            Just bi
+              | not bi.inActiveChain -> return (True, [], Nothing)
+              | otherwise -> do
+                  let hdr = e.headerOf h
+                      chainsOn = case (best, hdr) of
+                        (Just p, Just hd) -> hd.prev == p.hash
+                        (Just _, Nothing) -> False
+                        (Nothing, _) -> True
+                  if not chainsOn
+                    then return (True, [], Nothing)
+                    else
+                      if found
+                        then go rest (Just bi) True (maybe acc (: acc) hdr)
+                        else do
+                          has <- peerHasHeader bi
+                          if has
+                            then go rest (Just bi) False acc
+                            else do
+                              parentHas <- case hdr >>= e.lookupBlock . (.prev) of
+                                Nothing -> return (bi.height == 0)
+                                Just p -> peerHasHeader p
+                              if parentHas
+                                then go rest (Just bi) True (maybe acc (: acc) hdr)
+                                else return (True, [], Nothing)
+
+-- | The block timers of @SendMessages@ (lines 6440 to 6501): a stalling
+-- peer, a block that takes too long, and a headers sync that takes too
+-- long. A peer with 'PermNoBan' is not disconnected for the last one: its
+-- sync starts over with another peer.
+blockTimeouts :: M ()
+blockTimeouts = do
+  s <- getS
+  e <- env
+  o <- opts
+  t <- now
+  forM_ s.blocks.stallingSince $ \since ->
+    when (since < t - blockStallingTimeoutDefault) $ do
+      disconnect Timeout $ netProcessing 6446 "Peer is stalling block download"
+      stop
+  unless (null s.blocks.inFlight) $ do
+    let spacing = seconds (fromIntegral o.network.targetSpacing)
+        allowed = spacing + (spacing * fromIntegral e.otherPeersDownloading) `div` 2
+    when (t > s.blocks.downloadingSince + allowed) $ do
+      disconnect Timeout $ netProcessing 6465 "Timeout downloading block"
+      stop
+  when s.blocks.syncStarted $
+    forM_ s.blocks.headersSyncTimeout $ \deadline ->
+      if fromIntegral e.bestHeader.time <= t `div` 1000000 - 86400
+        then
+          when (t > deadline && e.otherSyncStarted == 0 && e.otherPreferredDownload >= 1) $
+            if hasPermission PermNoBan s
+              then modifyBlocks $ \b -> b {syncStarted = False, headersSyncTimeout = Just 0}
+              else do
+                disconnect Timeout $ netProcessing 6481 "Timeout downloading headers"
+                stop
+        else modifyBlocks $ \b -> b {headersSyncTimeout = Nothing}
+
+-- | @ConsiderEviction@ (line 5501): an outbound peer, unless protected,
+-- must show a chain with the work of the tip within 20 minutes of falling
+-- behind; then it gets a @getheaders@ and 2 more minutes.
+considerEviction :: M ()
+considerEviction = do
+  s <- getS
+  e <- env
+  t <- now
+  let cs = s.blocks.chainSync
+      outbound = s.connectionType `elem` [OutboundFullRelay, BlockRelayOnly]
+  when (not cs.protect && outbound && s.blocks.syncStarted) $ do
+    w <- bestKnownWork
+    let workHeaderWork = cs.workHeader >>= e.lookupBlock >>= Just . (.work)
+    if
+      | maybe False (>= e.tip.work) w ->
+          when (cs.timeout /= 0) $
+            setChainSync (ChainSync 0 Nothing False cs.protect)
+      | cs.timeout == 0 || (isJust workHeaderWork && isJust w && w >= workHeaderWork) ->
+          setChainSync (ChainSync (t + chainSyncTimeout) (Just e.tip.hash) False cs.protect)
+      | cs.timeout > 0 && t > cs.timeout ->
+          if cs.sentGetHeaders
+            then disconnect Unsuitable $ netProcessing 5538 "Outbound peer has old chain"
+            else do
+              let from = fromMaybe e.tip.hash (cs.workHeader >>= e.headerOf >>= Just . (.prev))
+              _ <-
+                maybeSendGetHeaders (e.locatorFrom from) $
+                  netProcessing 5545 "sending getheaders to outbound peer to verify chain work"
+              setChainSync cs {sentGetHeaders = True, timeout = t + headersResponseTime}
+      | otherwise -> return ()
+  where
+    setChainSync c = modifyBlocks $ \b -> b {chainSync = c}
+
+-- | @UpdatedBlockTip@ (line 2290): outside initial block download, queue
+-- up to 8 of the new blocks for announcement to the peer.
+newTip :: [BlockHeader] -> M ()
+newTip hdrs = do
+  e <- env
+  unless e.initialBlockDownload $ do
+    let hashes = reverse (take maxBlocksToAnnounce (reverse (map headerHash hdrs)))
+    modifyBlocks $ \b -> b {forHeadersRelay = b.forHeadersRelay ++ hashes}
+
+-- | @NewPoWValidBlock@ (line 2235): a new block that extends the tip goes
+-- at once as @cmpctblock@ to a peer that asked for high-bandwidth compact
+-- blocks, has the parent and not the block, before full validation.
+newPoWValidBlock :: BlockHeader -> M ()
+newPoWValidBlock hdr = do
+  s <- getS
+  e <- env
+  let h = headerHash hdr
+  when (s.successfullyConnected && s.commonVersion >= invalidCbNoBanVersion && s.blocks.requestedHbCmpct) $ do
+    hasBlock <- maybe (return False) peerHasHeader (e.lookupBlock h)
+    hasParent <- case e.lookupBlock hdr.prev of
+      Just p -> peerHasHeader p
+      Nothing -> return False
+    when (not hasBlock && hasParent) $
+      forM_ (e.compactBlockOf h) $ \cb -> do
+        send (MCompactBlock cb) $ netProcessing 2280 "NewPoWValidBlock sending header-and-ids"
+        modifyBlocks $ \b -> b {bestHeaderSent = Just h}
+
+-- | @MaybeSetPeerAsAnnouncingHeaderAndIDs@ (line 1372): the node chose the
+-- peer as one of its three high-bandwidth compact block peers, or dropped
+-- it. Only for a peer that offered compact blocks, outside blocks-only.
+highBandwidth :: Bool -> M ()
+highBandwidth on = do
+  s <- getS
+  o <- opts
+  when (s.successfullyConnected && s.blocks.providesCmpct && not o.blocksOnly && on /= s.blocks.highBandwidthTo) $ do
+    send (MSendCompact (SendCompact on cmpctBlocksVersion)) $
+      if on
+        then netProcessing 1412 "sendcmpct high bandwidth"
+        else netProcessing 1422 "sendcmpct low bandwidth (displaced)"
+    modifyBlocks $ \b -> b {highBandwidthTo = on}
+
+-- | The node asks the peer for a block (@FindNextBlocksToDownload@ and
+-- @BlockRequested@, line 6534, or @FetchBlock@). Ignored when 16 blocks
+-- are already in flight, the peer cannot serve blocks, or the handshake is
+-- not done.
+requestBlock :: BlockHash -> M ()
+requestBlock h = do
+  s <- getS
+  when (s.successfullyConnected && canServeBlocks s && length s.blocks.inFlight < maxBlocksInTransitPerPeer) $
+    unless (any ((== h) . (.block)) s.blocks.inFlight) $ do
+      blockRequested h Nothing
+      send (MGetData (GetData [blockRequest s h])) $ netProcessing 6562 "getdata for blocks"
+
+-- | The block download waits on this peer (line 6541).
+markStalling :: M ()
+markStalling = do
+  t <- now
+  s <- getS
+  when (isNothing s.blocks.stallingSince && not (null s.blocks.inFlight)) $
+    modifyBlocks $
+      \b -> b {stallingSince = Just t}
diff --git a/src/Haskoin/Network/Protocol/BitcoinCore/Constants.hs b/src/Haskoin/Network/Protocol/BitcoinCore/Constants.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Network/Protocol/BitcoinCore/Constants.hs
@@ -0,0 +1,364 @@
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+-- |
+-- Module      : Haskoin.Network.Protocol.BitcoinCore.Constants
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- The constants of Bitcoin Core 32.1 that the protocol machine of
+-- "Haskoin.Network.Protocol.BitcoinCore" uses, each with the name it has
+-- upstream, and the helpers that build a t'Cite' into that release.
+--
+-- They live apart from the rules so that a new release can be checked
+-- against one list: a constant that changes upstream changes here, and the
+-- rules that read it follow. None of them depends on the network: Bitcoin
+-- Core uses the same timeouts, limits and versions on every chain, and what
+-- differs by chain is in 'Haskoin.Network.Data.Network'.
+module Haskoin.Network.Protocol.BitcoinCore.Constants
+  ( -- * Upstream
+    upstream,
+    netProcessing,
+    netCpp,
+
+    -- * Protocol versions
+    protocolVersion,
+    privateBroadcastVersion,
+    initProtoVersion,
+    minPeerProtoVersion,
+    bip0031Version,
+    sendHeadersVersion,
+    feeFilterVersion,
+    shortIdsBlocksVersion,
+    invalidCbNoBanVersion,
+    wtxidRelayVersion,
+    featureVersion,
+    locatorVersion,
+    cmpctBlocksVersion,
+    txReconciliationVersion,
+
+    -- * Timers
+    timeoutInterval,
+    defaultPeerConnectTimeout,
+    pingInterval,
+    privateBroadcastLifetime,
+    avgAddressBroadcastInterval,
+    avgLocalAddressBroadcastInterval,
+    headersDownloadTimeoutBase,
+    headersDownloadTimeoutPerHeader,
+    headersResponseTime,
+    chainSyncTimeout,
+    blockStallingTimeoutDefault,
+    inboundInventoryBroadcastInterval,
+    outboundInventoryBroadcastInterval,
+    avgFeeFilterBroadcastInterval,
+    maxFeeFilterChangeDelay,
+
+    -- * Limits
+    maxInvSz,
+    maxGetDataSz,
+    maxLocatorSz,
+    maxHeadersResults,
+    maxBlocksInTransitPerPeer,
+    maxBlocksToAnnounce,
+    maxCmpctBlockDepth,
+    maxBlockTxnDepth,
+    maxCmpctBlocksInflightPerBlock,
+    maxGetCFiltersSize,
+    maxGetCFHeadersSize,
+    nodeNetworkLimitedMinBlocks,
+    nodeNetworkLimitedAllowConnBlocks,
+    maxAddrToSend,
+    maxAddrRatePerSecond,
+    maxAddrProcessingTokenBucket,
+    maxBloomFilterSize,
+    maxHashFuncs,
+    maxScriptElementSize,
+    maxMoney,
+    maxPeerTxAnnouncements,
+    maxFeatureIdLength,
+    maxFeatureDataLength,
+    staleRelayAge,
+    defaultMinRelayTxFee,
+    defaultUserAgent,
+    finalAlert,
+  )
+where
+
+import Data.ByteString (ByteString)
+import Data.Bytes.Get (runGetS)
+import Data.Bytes.Serial (deserialize)
+import Data.Int (Int32, Int64)
+import Data.Maybe (fromMaybe)
+import Data.Text (Text)
+import Data.Word (Word32, Word64)
+import Haskoin.Network.Common (Alert)
+import Haskoin.Network.Protocol.Types
+import Haskoin.Util (decodeHex)
+
+-- | The release whose source the machine translates.
+upstream :: Upstream
+upstream =
+  Upstream
+    { project = "Bitcoin Core",
+      release = "32.1",
+      tag = "v32.1",
+      commit = "f0de87f040621468b956f01f526a43a010310501",
+      repository = "https://github.com/bitcoin/bitcoin"
+    }
+
+-- | A t'Cite' of @src\/net_processing.cpp@, where nearly every rule lives.
+netProcessing :: Int -> Text -> Cite
+netProcessing = cite "src/net_processing.cpp"
+
+-- | A t'Cite' of @src\/net.cpp@: transport, inactivity and the sending filter
+-- of private broadcast connections.
+netCpp :: Int -> Text -> Cite
+netCpp = cite "src/net.cpp"
+
+-- | @PROTOCOL_VERSION@, the version that the node advertises
+-- (@src\/node\/protocol_version.h@).
+protocolVersion :: Int32
+protocolVersion = 70017
+
+-- | The version that a private broadcast connection advertises, to look
+-- like an older and more common node (@CNode::AdvertisedVersion@,
+-- @src\/net.h@).
+privateBroadcastVersion :: Int32
+privateBroadcastVersion = 70016
+
+-- | @INIT_PROTO_VERSION@: the common version before the peer's @version@.
+initProtoVersion :: Int32
+initProtoVersion = 209
+
+-- | @MIN_PEER_PROTO_VERSION@: older peers are disconnected.
+minPeerProtoVersion :: Int32
+minPeerProtoVersion = 31800
+
+-- | @BIP0031_VERSION@: above it, a ping carries a nonce and gets a pong.
+bip0031Version :: Int32
+bip0031Version = 60000
+
+-- | @SENDHEADERS_VERSION@.
+sendHeadersVersion :: Int32
+sendHeadersVersion = 70012
+
+-- | @FEEFILTER_VERSION@.
+feeFilterVersion :: Int32
+feeFilterVersion = 70013
+
+-- | @SHORT_IDS_BLOCKS_VERSION@: the node offers compact blocks from here.
+shortIdsBlocksVersion :: Int32
+shortIdsBlocksVersion = 70014
+
+-- | @INVALID_CB_NO_BAN_VERSION@: compact blocks may be announced to the
+-- peer before they are fully validated.
+invalidCbNoBanVersion :: Int32
+invalidCbNoBanVersion = 70015
+
+-- | @WTXID_RELAY_VERSION@: @wtxidrelay@, @sendaddrv2@ and @sendtxrcncl@.
+wtxidRelayVersion :: Int32
+wtxidRelayVersion = 70016
+
+-- | @FEATURE_VERSION@: the @feature@ message of BIP 434.
+featureVersion :: Int32
+featureVersion = 70017
+
+-- | @CBlockLocator::DUMMY_VERSION@, the version field of the locators that
+-- the node sends (@src\/primitives\/block.h@).
+locatorVersion :: Word32
+locatorVersion = 70016
+
+-- | @CMPCTBLOCKS_VERSION@: the only compact block version (2, with
+-- witnesses).
+cmpctBlocksVersion :: Word64
+cmpctBlocksVersion = 2
+
+-- | @TXRECONCILIATION_VERSION@ of Erlay (BIP 330).
+txReconciliationVersion :: Word32
+txReconciliationVersion = 1
+
+-- | @TIMEOUT_INTERVAL@, 20 minutes: ping timeout and inactivity.
+timeoutInterval :: Micros
+timeoutInterval = seconds (20 * 60)
+
+-- | @DEFAULT_PEER_CONNECT_TIMEOUT@, 60 seconds (@-peertimeout@).
+defaultPeerConnectTimeout :: Micros
+defaultPeerConnectTimeout = seconds 60
+
+-- | @PING_INTERVAL@, 2 minutes.
+pingInterval :: Micros
+pingInterval = seconds 120
+
+-- | @PRIVATE_BROADCAST_MAX_CONNECTION_LIFETIME@, 3 minutes.
+privateBroadcastLifetime :: Micros
+privateBroadcastLifetime = seconds 180
+
+-- | @AVG_ADDRESS_BROADCAST_INTERVAL@, 30 seconds. An address fetch
+-- connection lives ten times as long.
+avgAddressBroadcastInterval :: Micros
+avgAddressBroadcastInterval = seconds 30
+
+-- | @AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL@, 24 hours.
+avgLocalAddressBroadcastInterval :: Micros
+avgLocalAddressBroadcastInterval = seconds 86400
+
+-- | @HEADERS_DOWNLOAD_TIMEOUT_BASE@, 15 minutes.
+headersDownloadTimeoutBase :: Micros
+headersDownloadTimeoutBase = seconds (15 * 60)
+
+-- | @HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER@, 1 millisecond.
+headersDownloadTimeoutPerHeader :: Micros
+headersDownloadTimeoutPerHeader = millis 1
+
+-- | @HEADERS_RESPONSE_TIME@, 2 minutes.
+headersResponseTime :: Micros
+headersResponseTime = seconds 120
+
+-- | @CHAIN_SYNC_TIMEOUT@, 20 minutes.
+chainSyncTimeout :: Micros
+chainSyncTimeout = seconds (20 * 60)
+
+-- | @BLOCK_STALLING_TIMEOUT_DEFAULT@, 2 seconds. Upstream doubles it, up to
+-- 64 seconds, each time it disconnects a peer for stalling, and lets it
+-- decay as blocks connect; that is state of the whole node and is not
+-- modelled.
+blockStallingTimeoutDefault :: Micros
+blockStallingTimeoutDefault = seconds 2
+
+-- | @INBOUND_INVENTORY_BROADCAST_INTERVAL@, 5 seconds.
+inboundInventoryBroadcastInterval :: Micros
+inboundInventoryBroadcastInterval = seconds 5
+
+-- | @OUTBOUND_INVENTORY_BROADCAST_INTERVAL@, 2 seconds.
+outboundInventoryBroadcastInterval :: Micros
+outboundInventoryBroadcastInterval = seconds 2
+
+-- | @AVG_FEEFILTER_BROADCAST_INTERVAL@, 10 minutes.
+avgFeeFilterBroadcastInterval :: Micros
+avgFeeFilterBroadcastInterval = seconds 600
+
+-- | @MAX_FEEFILTER_CHANGE_DELAY@, 5 minutes.
+maxFeeFilterChangeDelay :: Micros
+maxFeeFilterChangeDelay = seconds 300
+
+-- | @MAX_INV_SZ@: entries of an @inv@ or @getdata@.
+maxInvSz :: Int
+maxInvSz = 50000
+
+-- | @MAX_GETDATA_SZ@: entries of a @getdata@ that the node sends.
+maxGetDataSz :: Int
+maxGetDataSz = 1000
+
+-- | @MAX_LOCATOR_SZ@.
+maxLocatorSz :: Int
+maxLocatorSz = 101
+
+-- | @MAX_HEADERS_RESULTS@.
+maxHeadersResults :: Int
+maxHeadersResults = 2000
+
+-- | @MAX_BLOCKS_IN_TRANSIT_PER_PEER@.
+maxBlocksInTransitPerPeer :: Int
+maxBlocksInTransitPerPeer = 16
+
+-- | @MAX_BLOCKS_TO_ANNOUNCE@: more new blocks than this go out as @inv@.
+maxBlocksToAnnounce :: Int
+maxBlocksToAnnounce = 8
+
+-- | @MAX_CMPCTBLOCK_DEPTH@.
+maxCmpctBlockDepth :: Int
+maxCmpctBlockDepth = 5
+
+-- | @MAX_BLOCKTXN_DEPTH@.
+maxBlockTxnDepth :: Int
+maxBlockTxnDepth = 10
+
+-- | @MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK@.
+maxCmpctBlocksInflightPerBlock :: Int
+maxCmpctBlocksInflightPerBlock = 3
+
+-- | @MAX_GETCFILTERS_SIZE@.
+maxGetCFiltersSize :: Int
+maxGetCFiltersSize = 1000
+
+-- | @MAX_GETCFHEADERS_SIZE@.
+maxGetCFHeadersSize :: Int
+maxGetCFHeadersSize = 2000
+
+-- | @NODE_NETWORK_LIMITED_MIN_BLOCKS@.
+nodeNetworkLimitedMinBlocks :: Int
+nodeNetworkLimitedMinBlocks = 288
+
+-- | @NODE_NETWORK_LIMITED_ALLOW_CONN_BLOCKS@.
+nodeNetworkLimitedAllowConnBlocks :: Int64
+nodeNetworkLimitedAllowConnBlocks = 144
+
+-- | @MAX_ADDR_TO_SEND@.
+maxAddrToSend :: Int
+maxAddrToSend = 1000
+
+-- | @MAX_ADDR_RATE_PER_SECOND@.
+maxAddrRatePerSecond :: Double
+maxAddrRatePerSecond = 0.1
+
+-- | @MAX_ADDR_PROCESSING_TOKEN_BUCKET@.
+maxAddrProcessingTokenBucket :: Double
+maxAddrProcessingTokenBucket = 1000
+
+-- | @MAX_BLOOM_FILTER_SIZE@ (@src\/common\/bloom.h@).
+maxBloomFilterSize :: Int
+maxBloomFilterSize = 36000
+
+-- | @MAX_HASH_FUNCS@ (@src\/common\/bloom.h@).
+maxHashFuncs :: Word32
+maxHashFuncs = 50
+
+-- | @MAX_SCRIPT_ELEMENT_SIZE@: the largest @filteradd@.
+maxScriptElementSize :: Int
+maxScriptElementSize = 520
+
+-- | @MAX_MONEY@ in satoshi.
+maxMoney :: Word64
+maxMoney = 2100000000000000
+
+-- | @MAX_PEER_TX_ANNOUNCEMENTS@ (@src\/node\/txdownloadman.h@).
+maxPeerTxAnnouncements :: Int
+maxPeerTxAnnouncements = 5000
+
+-- | @MAX_FEATUREID_LENGTH@ (@src\/protocol.h@).
+maxFeatureIdLength :: Int
+maxFeatureIdLength = 80
+
+-- | @MAX_FEATUREDATA_LENGTH@ (@src\/protocol.h@).
+maxFeatureDataLength :: Int
+maxFeatureDataLength = 512
+
+-- | @STALE_RELAY_AGE_LIMIT@, 30 days, in seconds.
+staleRelayAge :: Int64
+staleRelayAge = 30 * 24 * 60 * 60
+
+-- | @DEFAULT_MIN_RELAY_TX_FEE@, in satoshi per 1000 virtual bytes.
+defaultMinRelayTxFee :: Word64
+defaultMinRelayTxFee = 100
+
+-- | The user agent of a node with no @-uacomment@ (@FormatSubVersion@).
+defaultUserAgent :: ByteString
+defaultUserAgent = "/Satoshi:32.1.0/"
+
+-- | The final @alert@ that the node sends to peers of version 70012 or
+-- older (@ProcessMessage@, @src\/net_processing.cpp@): the last message of
+-- the retired alert system, which tells old nodes that its key is public.
+finalAlert :: Alert
+finalAlert =
+  either error id . runGetS deserialize . fromMaybe (error "finalAlert: bad hex") . decodeHex $
+    "60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f\
+    \00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920\
+    \636f6d70726f6d697365642c2075706772616465207265717569726564004630\
+    \440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc\
+    \3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf\
+    \689bf71b50"
diff --git a/src/Haskoin/Network/Protocol/BitcoinCore/Handshake.hs b/src/Haskoin/Network/Protocol/BitcoinCore/Handshake.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Network/Protocol/BitcoinCore/Handshake.hs
@@ -0,0 +1,559 @@
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE MultiWayIf #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- |
+-- Module      : Haskoin.Network.Protocol.BitcoinCore.Handshake
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- The life of a connection to Bitcoin Core 32.1, apart from blocks and
+-- relay: framing errors, the handshake (@version@, @verack@ and the
+-- messages allowed between them: @wtxidrelay@, @sendaddrv2@, @feature@,
+-- @sendtxrcncl@), @ping@ and @pong@, the inactivity checks and the
+-- punishment of misbehaviour.
+--
+-- Each handler names the upstream function it translates and the lines
+-- that decide. Most of them are in @ProcessMessage@ of
+-- @src\/net_processing.cpp@; the framing and inactivity rules are in
+-- @src\/net.cpp@.
+--
+-- The handshake of Bitcoin Core is lenient in one direction and strict in
+-- the other. Before the peer's @version@, every other message is dropped
+-- without a word; between @version@ and @verack@, only the feature
+-- negotiation messages count, and the rest are dropped. But a feature
+-- negotiation message after @verack@ closes the connection, because the
+-- features must be fixed before either side relies on them.
+module Haskoin.Network.Protocol.BitcoinCore.Handshake
+  ( -- * Framing
+    badFrame,
+
+    -- * Handshake
+    pushNodeVersion,
+    handleVersion,
+    handleVerAck,
+    handleWtxidRelay,
+    handleSendAddrV2,
+    handleFeature,
+    handleSendTxRcncl,
+
+    -- * Ping
+    handlePing,
+    handlePong,
+    maybeSendPing,
+
+    -- * Timers and punishment
+    inactivityCheck,
+    shouldRunInactivityChecks,
+    maybeDiscourageAndDisconnect,
+
+    -- * Shared rules
+    rejectIncomingTxs,
+    setupAddressRelay,
+    maybeDisconnectForTxRelayCapacity,
+  )
+where
+
+import Control.Monad (unless, when)
+import Data.Bits ((.&.), (.|.))
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as B
+import Data.Bytes.Get (getBytes, isEmpty, runGetS)
+import Data.Bytes.Serial (deserialize)
+import Data.Int (Int64)
+import Data.Word (Word64)
+import Haskoin.Network.Common
+  ( Inv (..),
+    InvType (..),
+    InvVector (..),
+    NetworkAddress (..),
+    Ping (..),
+    Pong (..),
+    SendTxRcncl (..),
+    VarInt (..),
+    VarString (..),
+    Version (..),
+    nodeNetwork,
+    nodeNetworkLimited,
+    nodeWitness,
+    sockToHostAddress,
+  )
+import Haskoin.Network.CompactBlock (SendCompact (..))
+import Haskoin.Network.Data (Network (..))
+import Haskoin.Network.Message (Message (..))
+import Haskoin.Network.Protocol.BitcoinCore.Constants
+import Haskoin.Network.Protocol.BitcoinCore.Machine
+import Haskoin.Network.Protocol.BitcoinCore.State
+import Haskoin.Network.Protocol.Types
+import Haskoin.Transaction.Common (TxHash (..), txHash)
+import Network.Socket (SockAddr (..))
+
+-- | Bytes from the peer that are not a message the node accepts
+-- (@V1Transport::readHeader@, @V1Transport::GetReceivedMessage@,
+-- @V2Transport::ProcessReceivedPacketBytes@ and the exception handler of
+-- @ProcessMessages@). A wrong magic or a size over the limit is a transport
+-- error and closes the socket at once; a wrong checksum or a malformed
+-- command name drops the message; a payload that does not parse throws in
+-- @ProcessMessage@, which @ProcessMessages@ catches and logs.
+badFrame :: FrameError -> M ()
+badFrame err = do
+  s <- getS
+  case err of
+    WrongMagic _
+      | s.transport == TransportV2 ->
+          disconnect ProtocolViolation $
+            netCpp 1144 "V2 transport error: V1 peer with wrong MessageStart"
+      | otherwise ->
+          disconnect ProtocolViolation $
+            netCpp 765 "Header error: Wrong MessageStart"
+    Oversized _ _
+      | s.transport == TransportV2 ->
+          disconnect ProtocolViolation $
+            netCpp 1230 "V2 transport error: packet too large"
+      | otherwise ->
+          disconnect ProtocolViolation $
+            netCpp 773 "Header error: Size too large"
+    BadChecksum _ -> ignore $ netCpp 836 "Header error: Wrong checksum"
+    BadCommand _ -> ignore $ netCpp 840 "Header error: Invalid message type"
+    BadPayload _ -> ignore $ netProcessing 5493 "Exception caught"
+
+-- | @PushNodeVersion@: the node's @version@. A private broadcast connection
+-- sends an anonymous one: no services, time 0, height 0, the user agent
+-- @\/pynode:0.0.1\/@ and no relay. The address of the peer in @addr_recv@ is
+-- left empty here: the machine does not know it, and upstream leaves it
+-- empty for inbound peers' services and for unroutable addresses.
+pushNodeVersion :: M ()
+pushNodeVersion = do
+  s <- getS
+  o <- opts
+  e <- env
+  rejects <- rejectIncomingTxs
+  let pb = s.connectionType == PrivateBroadcast
+      zeroAddr = sockToHostAddress (SockAddrInet6 0 0 (0, 0, 0, 0) 0)
+      services = if pb then 0 else s.ourServices
+      v =
+        Version
+          { version = if pb then privateBroadcastVersion else protocolVersion,
+            services = services,
+            timestamp = if pb then 0 else e.now `div` 1000000,
+            addrRecv = NetworkAddress 0 zeroAddr,
+            addrSend = NetworkAddress services zeroAddr,
+            nonce = s.localNonce,
+            userAgent = VarString (if pb then "/pynode:0.0.1/" else o.userAgent),
+            startHeight = if pb then 0 else fromIntegral e.tip.height,
+            relay = not pb && not rejects
+          }
+  send (MVersion v) $ netProcessing 1675 "send version message"
+  modifyS $ \st -> st {versionSent = True}
+
+-- | @RejectIncomingTxs@: the node told the peer not to send transactions,
+-- and disconnects it if it does: a block-relay-only or feeler connection,
+-- or @-blocksonly@ without 'PermRelay'.
+rejectIncomingTxs :: M Bool
+rejectIncomingTxs = do
+  s <- getS
+  o <- opts
+  return $
+    s.connectionType == BlockRelayOnly
+      || s.connectionType == Feeler
+      || (o.blocksOnly && not (hasPermission PermRelay s))
+
+-- | @SetupAddressRelay@: start address relay with the peer, unless the
+-- connection is block-relay-only or a feeler. Outbound peers start at their
+-- @version@, inbound peers at their first @addr@, @addrv2@ or @getaddr@.
+setupAddressRelay :: M Bool
+setupAddressRelay = do
+  s <- getS
+  if s.connectionType == BlockRelayOnly || s.connectionType == Feeler
+    then return False
+    else do
+      putS s {addrRelay = True}
+      return True
+
+-- | @MaybeDisconnectForTxRelayCapacity@: an inbound peer that relays
+-- transactions takes one of the limited slots for them
+-- (@-inboundrelaypercent@). When they are full, the node evicts another
+-- such peer, and only if it cannot does it drop this one. Which peer goes
+-- is a decision across peers: @txRelayInboundFull@ of t'Env' says that none
+-- could. True when the peer is dropped.
+maybeDisconnectForTxRelayCapacity :: M Bool
+maybeDisconnectForTxRelayCapacity = do
+  s <- getS
+  e <- env
+  if s.connectionType /= Inbound || not s.relaysTxs || not e.txRelayInboundFull
+    then return False
+    else do
+      disconnect Resources $
+        netProcessing 5415 "failed to find a tx-relaying eviction candidate"
+      return True
+
+-- | The services the node wants from an outbound peer
+-- (@GetDesirableServiceFlags@): @NODE_NETWORK | NODE_WITNESS@, or
+-- @NODE_NETWORK_LIMITED | NODE_WITNESS@ from a limited peer when the tip
+-- is less than 144 blocks old by the clock.
+desirableServices :: Word64 -> M Word64
+desirableServices services = do
+  e <- env
+  o <- opts
+  let spacing = max 1 (fromIntegral o.network.targetSpacing) :: Int64
+      depth = (e.now `div` 1000000 - fromIntegral e.tip.time) `div` spacing
+  return $
+    if services .&. nodeNetworkLimited /= 0 && depth < nodeNetworkLimitedAllowConnBlocks
+      then nodeNetworkLimited .|. nodeWitness
+      else nodeNetwork .|. nodeWitness
+
+-- | Whether the connection type requires services (@ExpectServicesFromConn@).
+expectServices :: ConnectionType -> Bool
+expectServices t = t `elem` [OutboundFullRelay, BlockRelayOnly, AddrFetch, PrivateBroadcast]
+
+-- | @version@ (@ProcessMessage@, @src\/net_processing.cpp@, from line 3837).
+handleVersion :: Version -> M ()
+handleVersion v = do
+  s0 <- getS
+  when (s0.peerVersion /= Nothing) $ do
+    ignore $ netProcessing 3839 "redundant version message"
+    stop
+  let services = v.services
+  desirable <- desirableServices services
+  when (expectServices s0.connectionType && desirable .&. services /= desirable) $ do
+    disconnect Unsuitable $
+      netProcessing 3871 "peer does not offer the expected services"
+    stop
+  when (v.version < minPeerProtoVersion) $ do
+    disconnect ProtocolViolation $ netProcessing 3878 "peer using obsolete version"
+    stop
+  e <- env
+  when (s0.connectionType == Inbound && e.ownNonce v.nonce) $ do
+    disconnect ProtocolViolation $ netProcessing 3904 "connected to self"
+    stop
+  when (s0.connectionType == Inbound) pushNodeVersion
+  let advertised =
+        if s0.connectionType == PrivateBroadcast
+          then privateBroadcastVersion
+          else protocolVersion
+      common = min v.version advertised
+      VarString ua = v.userAgent
+      makeTxRelay =
+        s0.connectionType /= BlockRelayOnly
+          && s0.connectionType /= Feeler
+          && (v.relay || s0.ourServices .&. nodeBloomBit /= 0)
+  modifyS $ \s ->
+    s
+      { peerVersion = Just v.version,
+        commonVersion = common,
+        theirServices = services,
+        peerUserAgent = ua,
+        txRelay = if makeTxRelay then Just (newTxRelay v.relay) else s.txRelay,
+        relaysTxs = s.relaysTxs || (makeTxRelay && v.relay)
+      }
+  when (s0.connectionType == PrivateBroadcast) $ do
+    if v.relay
+      then send MVerAck $ netProcessing 3957 "private broadcast: verack"
+      else
+        disconnect Unsuitable $
+          netProcessing 3961 "does not support transaction relay (connected in vain)"
+    stop
+  when (common >= wtxidRelayVersion) $
+    send MWtxidRelay $
+      netProcessing 3967 "wtxidrelay"
+  when (common >= 70016) $
+    send MSendAddrV2 $
+      netProcessing 3976 "sendaddrv2"
+  o <- opts
+  s1 <- getS
+  when
+    ( common >= wtxidRelayVersion
+        && o.txReconciliation
+        && maybe False (.relayTxs) s1.txRelay
+        && s1.connectionType /= AddrFetch
+        && not o.blocksOnly
+    )
+    $ do
+      salt <- random nextWord64
+      modifyS $ \s -> s {reconciliation = PreRegistered salt}
+      send (MSendTxRcncl (SendTxRcncl txReconciliationVersion salt)) $
+        netProcessing 3990 "sendtxrcncl"
+  dropped <- maybeDisconnectForTxRelayCapacity
+  when dropped stop
+  send MVerAck $ netProcessing 4003 "verack"
+  let canServe = services .&. (nodeNetwork .|. nodeNetworkLimited) /= 0
+      inbound = s0.connectionType == Inbound
+      preferred =
+        (not inbound || hasPermission PermNoBan s0)
+          && s0.connectionType /= AddrFetch
+          && canServe
+  modifyBlocks $ \b -> b {preferredDownload = preferred}
+  unless inbound $ do
+    getaddr <- setupAddressRelay
+    when getaddr $ do
+      send MGetAddr $ netProcessing 4027 "getaddr"
+      modifyS $ \s ->
+        s {getAddrSent = True, addrTokens = s.addrTokens + fromIntegral maxAddrToSend}
+  when (common <= 70012) $
+    send (MAlert finalAlert) $
+      netProcessing 4063 "final alert"
+  when (s0.connectionType == Feeler) $
+    disconnect Done $
+      netProcessing 4069 "feeler connection completed"
+  where
+    nodeBloomBit = 4 :: Word64
+
+-- | @verack@ (@ProcessMessage@, from line 4080). On a private broadcast
+-- connection, the node announces its transaction at once. Otherwise it
+-- offers compact blocks in low-bandwidth mode, forgets an Erlay
+-- registration that did not complete, and the handshake is done.
+handleVerAck :: M ()
+handleVerAck = do
+  s <- getS
+  when s.successfullyConnected $ do
+    ignore $ netProcessing 4082 "ignoring redundant verack message"
+    stop
+  when (s.connectionType == PrivateBroadcast) $ do
+    modifyS $ \st -> st {successfullyConnected = True}
+    e <- env
+    case e.privateBroadcastTx of
+      Nothing ->
+        disconnect Done $
+          netProcessing 3816 "no more transactions for private broadcast (connected in vain)"
+      Just tx -> do
+        let TxHash h = txHash tx
+        modifyS $ \st -> st {privateTx = Just (txHash tx)}
+        send (MInv (Inv [InvVector InvTx h])) $
+          netProcessing 3825 "P2P handshake completed, sending INV"
+    stop
+  when (s.commonVersion >= shortIdsBlocksVersion) $
+    send (MSendCompact (SendCompact False cmpctBlocksVersion)) $
+      netProcessing 4134 "sendcmpct"
+  o <- opts
+  when (o.txReconciliation && (not s.wtxidRelay || s.reconciliation /= Registered)) $
+    modifyS $
+      \st -> st {reconciliation = NoReconciliation}
+  modifyS $ \st -> st {successfullyConnected = True}
+
+-- | @wtxidrelay@ (from line 4192): allowed only before @verack@, and
+-- counted only with a common version of 70016 or more.
+handleWtxidRelay :: M ()
+handleWtxidRelay = do
+  s <- getS
+  when s.successfullyConnected $ do
+    disconnect ProtocolViolation $ netProcessing 4196 "wtxidrelay received after verack"
+    stop
+  if s.commonVersion >= wtxidRelayVersion
+    then
+      if s.wtxidRelay
+        then ignore $ netProcessing 4204 "ignoring duplicate wtxidrelay"
+        else putS s {wtxidRelay = True}
+    else ignore $ netProcessing 4207 "ignoring wtxidrelay due to old common version"
+
+-- | @sendaddrv2@ (from line 4214): allowed only before @verack@, with any
+-- version.
+handleSendAddrV2 :: M ()
+handleSendAddrV2 = do
+  s <- getS
+  if s.successfullyConnected
+    then disconnect ProtocolViolation $ netProcessing 4218 "sendaddrv2 received after verack"
+    else putS s {wantsAddrV2 = True}
+
+-- | @feature@ of BIP 434 (from line 4225), which this library does not know
+-- and receives as @MOther "feature"@. Allowed only before @verack@ and with
+-- a common version of 70017; the payload must be a feature id of 4 to 80
+-- bytes and data of at most 512 bytes, with nothing after. No feature is
+-- known in 32.1, so a good one is logged and ignored.
+handleFeature :: ByteString -> M ()
+handleFeature payload = do
+  s <- getS
+  when s.successfullyConnected $ do
+    disconnect ProtocolViolation $ netProcessing 4229 "feature received after verack"
+    stop
+  when (s.commonVersion < featureVersion) $ do
+    disconnect ProtocolViolation $
+      netProcessing 4234 "feature received with incompatible version"
+    stop
+  case runGetS parseFeature payload of
+    Right (fid, True)
+      | B.length fid >= 4 -> ignore $ netProcessing 4260 "unknown feature advertised"
+    _ -> disconnect ProtocolViolation $ netProcessing 4250 "invalid feature payload"
+  where
+    parseFeature = do
+      fid <- limited maxFeatureIdLength
+      _ <- limited maxFeatureDataLength
+      end <- isEmpty
+      return (fid, end)
+    limited n = do
+      VarInt l <- deserialize
+      if l > fromIntegral n
+        then fail "too long"
+        else getBytes (fromIntegral l)
+
+-- | @sendtxrcncl@ of Erlay (from line 4267).
+handleSendTxRcncl :: SendTxRcncl -> M ()
+handleSendTxRcncl m = do
+  o <- opts
+  s <- getS
+  unless o.txReconciliation $ do
+    ignore $ netProcessing 4269 "sendtxrcncl ignored, txreconciliation not enabled"
+    stop
+  when s.successfullyConnected $ do
+    disconnect ProtocolViolation $ netProcessing 4275 "sendtxrcncl received after verack"
+    stop
+  rejects <- rejectIncomingTxs
+  when rejects $ do
+    disconnect ProtocolViolation $
+      netProcessing 4282 "sendtxrcncl received to which we indicated no tx relay"
+    stop
+  unless (maybe False (.relayTxs) s.txRelay) $ do
+    disconnect ProtocolViolation $
+      netProcessing 4292 "sendtxrcncl received which indicated no tx relay to us"
+    stop
+  case s.reconciliation of
+    NoReconciliation ->
+      ignore $ netProcessing 4304 "Ignore unexpected txreconciliation signal"
+    Registered ->
+      disconnect ProtocolViolation $
+        netProcessing 4310 "sendtxrcncl received from already registered peer"
+    PreRegistered _
+      | min m.version txReconciliationVersion < 1 ->
+          disconnect ProtocolViolation $ netProcessing 4314 "txreconciliation protocol violation"
+      | otherwise -> putS s {reconciliation = Registered}
+
+-- | @ping@ (from line 5217): a pong with the same nonce when the common
+-- version is above 60000, nothing otherwise.
+handlePing :: Ping -> M ()
+handlePing (Ping n) = do
+  s <- getS
+  if s.commonVersion > bip0031Version
+    then send (MPong (Pong n)) $ netProcessing 5232 "pong"
+    else ignore $ netProcessing 5218 "ping of an old version: no pong"
+
+-- | @ProcessPong@ (from line 5890). Problems are logged, never punished.
+-- A pong that matches finishes the ping and measures it; on a private
+-- broadcast connection it also means the transaction arrived, and the node
+-- disconnects. A pong with nonce zero cancels the ping; another wrong
+-- nonce leaves it waiting.
+handlePong :: Pong -> M ()
+handlePong (Pong n) = do
+  s <- getS
+  t <- now
+  if s.pingNonceSent == 0
+    then ignore $ netProcessing 5929 "Unsolicited pong without ping"
+    else
+      if n == s.pingNonceSent
+        then do
+          let rtt = t - s.pingStart
+          putS
+            s
+              { pingNonceSent = 0,
+                lastPingTime = if rtt >= 0 then Just rtt else s.lastPingTime,
+                minPingTime =
+                  if rtt >= 0 then Just (maybe rtt (min rtt) s.minPingTime) else s.minPingTime
+              }
+          when (rtt >= 0 && s.connectionType == PrivateBroadcast) $ do
+            process "private broadcast: transaction received" $
+              netProcessing 5910 "NodeConfirmedReception"
+            disconnect Done $
+              netProcessing 5913 "Got a PONG (the transaction will probably reach the network)"
+        else
+          if n == 0
+            then do
+              putS s {pingNonceSent = 0}
+              ignore $ netProcessing 5925 "Nonce zero"
+            else ignore $ netProcessing 5921 "Nonce mismatch"
+
+-- | @ShouldRunInactivityChecks@: the connection is older than
+-- @-peertimeout@.
+shouldRunInactivityChecks :: M Bool
+shouldRunInactivityChecks = do
+  s <- getS
+  o <- opts
+  t <- now
+  return (s.connectedAt + o.peerTimeout < t)
+
+-- | @CConnman::InactivityCheck@ (@src\/net.cpp@, from line 2045), run by
+-- the socket thread for every peer. Once the connection is older than
+-- @-peertimeout@: nothing ever received or sent, nothing sent or received
+-- for 20 minutes, or a handshake still not done, closes it. The send buffer
+-- check (@fPauseSend@) is not modelled: the machine has no buffers.
+inactivityCheck :: M ()
+inactivityCheck = do
+  run <- shouldRunInactivityChecks
+  when run $ do
+    s <- getS
+    t <- now
+    case (s.lastRecv, s.lastSend) of
+      (Just r, Just w)
+        | t > w + timeoutInterval ->
+            disconnect Timeout $ netCpp 2075 "socket sending timeout"
+        | t > r + timeoutInterval ->
+            disconnect Timeout $ netCpp 2083 "socket receive timeout"
+        | not s.successfullyConnected ->
+            disconnect Timeout $
+              if s.transport == TransportV2 && s.peerVersion == Nothing
+                then netCpp 2099 "V2 handshake timeout"
+                else netCpp 2101 "version handshake timeout"
+        | otherwise -> return ()
+      _ -> disconnect Timeout $ netCpp 2067 "socket no message in first seconds"
+
+-- | @MaybeSendPing@ (from line 5697): disconnect when a ping has waited 20
+-- minutes; otherwise send one when asked to, or when none is waiting and
+-- the last was sent more than 2 minutes ago. The first ping goes out at
+-- the first pass after the handshake, because @m_ping_start@ starts at the
+-- epoch.
+maybeSendPing :: M ()
+maybeSendPing = do
+  s <- getS
+  t <- now
+  run <- shouldRunInactivityChecks
+  when (run && s.pingNonceSent /= 0 && t > s.pingStart + timeoutInterval) $ do
+    disconnect Timeout $ netProcessing 5706 "ping timeout"
+    stop
+  let due = s.pingQueued || (s.pingNonceSent == 0 && t > s.pingStart + pingInterval)
+  when due $ do
+    nonce <- random nonZero
+    if s.commonVersion > bip0031Version
+      then do
+        modifyS $ \st -> st {pingQueued = False, pingStart = t, pingNonceSent = nonce}
+        send (MPing (Ping nonce)) $ netProcessing 5731 "ping"
+      else do
+        modifyS $ \st -> st {pingQueued = False, pingStart = t, pingNonceSent = 0}
+        send (MOther "ping" B.empty) $ netProcessing 5735 "ping without nonce"
+  where
+    nonZero g =
+      let (w, g') = nextWord64 g
+       in if w == 0 then nonZero g' else (w, g')
+
+-- | @MaybeDiscourageAndDisconnect@ (from line 5364), run first in every
+-- @SendMessages@. A peer with 'PermNoBan' and a manual connection are never
+-- punished. A private broadcast peer, and a local one (which includes an
+-- inbound Tor peer), are disconnected without discouragement: discouraging
+-- the address of the local Tor proxy would discourage every Tor peer. Any
+-- other peer is discouraged, which disconnects every connection from its
+-- address. True when the peer was disconnected.
+maybeDiscourageAndDisconnect :: M Bool
+maybeDiscourageAndDisconnect = do
+  s <- getS
+  case s.shouldDiscourage of
+    Nothing -> return False
+    Just why -> do
+      putS s {shouldDiscourage = Nothing}
+      if
+        | hasPermission PermNoBan s -> return False
+        | s.connectionType == Manual -> return False
+        | s.connectionType == PrivateBroadcast -> do
+            disconnect Misbehaviour $
+              netProcessing 5389 "Disconnecting misbehaving private broadcast peer"
+            return True
+        | s.isLocal -> do
+            disconnect Misbehaviour $
+              netProcessing 5398 "disconnecting but not discouraging local peer"
+            return True
+        | otherwise -> do
+            emit Discourage why
+            disconnect Misbehaviour $ netProcessing 5405 "Disconnecting and discouraging peer"
+            return True
diff --git a/src/Haskoin/Network/Protocol/BitcoinCore/Machine.hs b/src/Haskoin/Network/Protocol/BitcoinCore/Machine.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Network/Protocol/BitcoinCore/Machine.hs
@@ -0,0 +1,203 @@
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- |
+-- Module      : Haskoin.Network.Protocol.BitcoinCore.Machine
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- The small state monad in which the handlers of
+-- "Haskoin.Network.Protocol.BitcoinCore" are written, and the primitives
+-- that every handler uses: send a message, drop one, disconnect, flag
+-- misbehaviour, draw randomness.
+--
+-- The handlers are translations of C++ functions that mutate the state of
+-- a peer and push messages as they go, and stop early with @return@. A
+-- state monad that collects t'Effect's in order keeps the translation close
+-- to that shape, so that a reader can follow both side by side. The
+-- alternative, threading a state and a list of effects through every
+-- function by hand, made the handlers twice as long and hid the order of the
+-- decisions, which is what the machine is for.
+--
+-- A handler stops early with 'stop', as the C++ function returns; 'scoped'
+-- runs a sub-handler whose early return ends only that sub-handler.
+--
+-- 'send' applies the one filter of the transport that a peer can observe:
+-- on a private broadcast connection, the node sends only @version@,
+-- @verack@, @inv@, @tx@ and @ping@ (@CConnman::PushMessage@,
+-- @src\/net.cpp@).
+module Haskoin.Network.Protocol.BitcoinCore.Machine
+  ( M,
+    Run (..),
+    runM,
+    stop,
+    scoped,
+    opts,
+    env,
+    now,
+    getS,
+    putS,
+    modifyS,
+    modifyBlocks,
+    modifyTxRelay,
+    emit,
+    send,
+    ignore,
+    process,
+    disconnect,
+    misbehaving,
+    random,
+    isConn,
+    isInbound,
+    isPrivateBroadcast,
+    whenM,
+    unlessM,
+  )
+where
+
+import Control.Monad (unless, when)
+import Control.Monad.Except (ExceptT, catchError, runExceptT, throwError)
+import Control.Monad.State.Strict qualified as S
+import Data.Text (Text)
+import Haskoin.Network.Message (Message (..))
+import Haskoin.Network.Protocol.BitcoinCore.State
+import Haskoin.Network.Protocol.Types
+
+-- | What a step works on: the options and the environment, which do not
+-- change, the state of the peer, and the effects so far, newest first.
+data Run = Run
+  { options :: !Options,
+    environment :: Env,
+    state :: !State,
+    effects :: ![Effect]
+  }
+
+-- | The monad of the handlers: a state, and an early exit.
+type M = ExceptT () (S.State Run)
+
+-- | Run a handler: the new state and the effects in the order they
+-- happened.
+runM :: Options -> Env -> State -> M () -> (State, [Effect])
+runM o e s m =
+  let r = S.execState (runExceptT (scoped m)) (Run o e s [])
+   in (r.state, reverse r.effects)
+
+-- | Return from the handler now, keeping what it did so far.
+stop :: M a
+stop = throwError ()
+
+-- | Run a sub-handler; its 'stop' returns to here.
+scoped :: M () -> M ()
+scoped m = catchError m (\() -> return ())
+
+-- | The options of the node.
+opts :: M Options
+opts = S.gets (.options)
+
+-- | The environment of this step.
+env :: M Env
+env = S.gets (.environment)
+
+-- | The time of this step.
+now :: M Micros
+now = S.gets (.environment.now)
+
+-- | The state of the peer.
+getS :: M State
+getS = S.gets (.state)
+
+-- | Replace the state of the peer.
+putS :: State -> M ()
+putS s = S.modify' $ \r -> r {state = s}
+
+-- | Change the state of the peer.
+modifyS :: (State -> State) -> M ()
+modifyS f = S.modify' $ \r -> r {state = f r.state}
+
+-- | Change the block download state.
+modifyBlocks :: (BlockState -> BlockState) -> M ()
+modifyBlocks f = modifyS $ \s -> s {blocks = f s.blocks}
+
+-- | Change the transaction relay state, if there is one.
+modifyTxRelay :: (TxRelay -> TxRelay) -> M ()
+modifyTxRelay f = modifyS $ \s -> s {txRelay = f <$> s.txRelay}
+
+-- | Record an effect.
+emit :: Action -> Cite -> M ()
+emit a c = S.modify' $ \r -> r {effects = Effect a c : r.effects}
+
+-- | Send a message, and note the time of the last send for the inactivity
+-- checks. On a private broadcast connection, only the messages that
+-- @CConnman::PushMessage@ lets through are sent; the others are dropped
+-- without a trace, as upstream does.
+send :: Message -> Cite -> M ()
+send m c = do
+  pb <- isPrivateBroadcast
+  unless (pb && not (allowed m)) $ do
+    t <- now
+    modifyS $ \s -> s {lastSend = Just t}
+    emit (Send m) c
+  where
+    allowed (MVersion _) = True
+    allowed MVerAck = True
+    allowed (MInv _) = True
+    allowed (MTx _) = True
+    allowed (MPing _) = True
+    allowed _ = False
+
+-- | Drop the message without an answer.
+ignore :: Cite -> M ()
+ignore = emit Ignore
+
+-- | An effect on the rest of the node that the peer does not see.
+process :: Text -> Cite -> M ()
+process t = emit (Process t)
+
+-- | Close the connection (@fDisconnect = true@). Nothing more is processed
+-- for the peer after this.
+disconnect :: DisconnectReason -> Cite -> M ()
+disconnect r c = do
+  modifyS $ \s -> s {disconnected = True}
+  emit (Disconnect r) c
+
+-- | @Misbehaving@: flag the peer for discouragement, which
+-- @MaybeDiscourageAndDisconnect@ acts on before the node sends anything
+-- more. There is no score in Bitcoin Core 32.1: one call is enough. The
+-- t'Cite' is kept to explain the 'Discourage' effect when it comes.
+misbehaving :: Cite -> M ()
+misbehaving c = modifyS $ \s -> s {shouldDiscourage = Just c}
+
+-- | Draw from the randomness of the node.
+random :: (Rng -> (a, Rng)) -> M a
+random f = do
+  s <- getS
+  let (a, g) = f s.rng
+  putS s {rng = g}
+  return a
+
+-- | The connection is of this type.
+isConn :: ConnectionType -> M Bool
+isConn t = (== t) . (.connectionType) <$> getS
+
+-- | The peer connected to the node.
+isInbound :: M Bool
+isInbound = isConn Inbound
+
+-- | A private broadcast connection.
+isPrivateBroadcast :: M Bool
+isPrivateBroadcast = isConn PrivateBroadcast
+
+-- | Run an action if a condition holds.
+whenM :: M Bool -> M () -> M ()
+whenM c a = c >>= \b -> when b a
+
+-- | Run an action unless a condition holds.
+unlessM :: M Bool -> M () -> M ()
+unlessM c a = c >>= \b -> unless b a
diff --git a/src/Haskoin/Network/Protocol/BitcoinCore/Relay.hs b/src/Haskoin/Network/Protocol/BitcoinCore/Relay.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Network/Protocol/BitcoinCore/Relay.hs
@@ -0,0 +1,663 @@
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- |
+-- Module      : Haskoin.Network.Protocol.BitcoinCore.Relay
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- Transactions and addresses on a connection to Bitcoin Core 32.1:
+-- @inv@ (with its block entries handed to
+-- "Haskoin.Network.Protocol.BitcoinCore.Blocks"), @getdata@, @tx@,
+-- @notfound@, @mempool@, @feefilter@, the BIP 37 filter messages, @addr@,
+-- @addrv2@ and @getaddr@, and what the node sends on its own: the trickle
+-- of transaction announcements, address relay and the fee filter.
+--
+-- Two facts of 32.1 shape this module. No transaction is ever punished:
+-- an invalid one only goes into the node's reject filters, and the only
+-- penalties of relay are oversized @inv@, @getdata@ and @addr@ messages
+-- and abuse of Bloom filters. And the pace of announcements is set by two
+-- token buckets shared by all inbound and all outbound peers
+-- (@InvToSendBucket@); the machine leaves those to the node, which tells
+-- each peer what to announce with 'TxAccepted', and keeps only the
+-- per-peer trickle timer.
+--
+-- Other simplifications, each because the decision spans peers or needs
+-- the mempool's internals: the transaction download (@TxDownloadManager@,
+-- with its delays, limits and orphan handling) is the node's, which asks
+-- this peer for a transaction with 'RequestTx'; a transaction in the
+-- mempool is served to any peer, while upstream serves only those that
+-- entered the mempool before the last announcement to that peer; queued
+-- announcements are sorted by fee rate, where upstream sorts by mining
+-- score; and an address that arrives is handed to the node with 'Process'
+-- instead of being relayed here, since the node picks the peers that
+-- relay it.
+module Haskoin.Network.Protocol.BitcoinCore.Relay
+  ( -- * Messages
+    handleInv,
+    handleGetData,
+    handleTx,
+    handleNotFound,
+    handleMempool,
+    handleFeeFilter,
+    handleFilterLoad,
+    handleFilterAdd,
+    handleFilterClear,
+    handleAddrs,
+    handleGetAddr,
+
+    -- * Sending
+    sendTxTrickle,
+    maybeSendAddr,
+    maybeSendFeeFilter,
+    feeFilterBuckets,
+    roundFeeFilter,
+
+    -- * Notifications
+    txAccepted,
+    relayAddress,
+    requestTx,
+  )
+where
+
+import Control.Monad (forM_, unless, when)
+import Data.Bits ((.&.))
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as B
+import Data.List (sortOn)
+import Data.Maybe (isJust, mapMaybe)
+import Data.Ord (Down (..))
+import Data.Set qualified as Set
+import Data.Word (Word16, Word64, Word8)
+import Haskoin.Block.Common (BlockHash (..))
+import Haskoin.Network.Bloom
+  ( BloomFilter (..),
+    FilterAdd (..),
+    FilterLoad (..),
+    bloomInsert,
+    bloomRelevantUpdate,
+  )
+import Haskoin.Network.Common
+  ( AddrV2 (..),
+    FeeFilter (..),
+    GetData (..),
+    Inv (..),
+    InvType (..),
+    InvVector (..),
+    NetworkAddressV2 (..),
+    NotFound (..),
+    addressNetworkId,
+    addressNetworkLength,
+    nodeNetwork,
+    nodeNetworkLimited,
+    nodeWitness,
+  )
+import Haskoin.Network.Common qualified as C
+import Haskoin.Network.Message (Message (..))
+import Haskoin.Network.Protocol.BitcoinCore.Blocks (blockInvs, getBlockData)
+import Haskoin.Network.Protocol.BitcoinCore.Constants
+import Haskoin.Network.Protocol.BitcoinCore.Handshake
+  ( maybeDisconnectForTxRelayCapacity,
+    maybeSendPing,
+    rejectIncomingTxs,
+    setupAddressRelay,
+  )
+import Haskoin.Network.Protocol.BitcoinCore.Machine
+import Haskoin.Network.Protocol.BitcoinCore.State
+import Haskoin.Network.Protocol.Types
+import Haskoin.Transaction.Common (OutPoint (..), Tx (..), TxHash (..), TxIn (..), txHash, txWitnessHash)
+
+-- | Transaction entries of an inventory (@IsGenTxMsg@).
+isTxInv :: InvType -> Bool
+isTxInv t = t `elem` [InvTx, InvWTx, InvWitnessTx]
+
+-- | The hash under which the peer knows a transaction: the wtxid if it
+-- relays by wtxid, else the txid.
+knownHash :: State -> Tx -> TxHash
+knownHash s tx = if s.wtxidRelay then txWitnessHash tx else txHash tx
+
+-- | @AddKnownTx@.
+addKnownTx :: TxHash -> M ()
+addKnownTx h = modifyTxRelay $ \r -> r {knownTxs = Set.insert h r.knownTxs}
+
+-- | @inv@ (line 4347). More than 50,000 entries is misbehaviour. The
+-- entries of the type the peer does not relay by (txid or wtxid) are
+-- skipped. A transaction entry from a peer that was told not to send
+-- transactions closes the connection at once; others go to the node's
+-- transaction download, except in initial block download.
+handleInv :: Inv -> M ()
+handleInv (Inv ivs) = do
+  when (length ivs > maxInvSz) $ do
+    let c = netProcessing 4352 "inv message size"
+    misbehaving c
+    ignore c
+    stop
+  rejects <- rejectIncomingTxs
+  s <- getS
+  e <- env
+  let relevant iv
+        | s.wtxidRelay = iv.invType /= InvTx
+        | otherwise = iv.invType /= InvWTx
+      go _ blocks [] = return blocks
+      go seen blocks (iv : rest)
+        | not (relevant iv) = go seen blocks rest
+        | iv.invType == InvBlock = go seen (BlockHash iv.invHash : blocks) rest
+        | isTxInv iv.invType = do
+            when rejects $ do
+              blockInvs (reverse blocks)
+              disconnect ProtocolViolation $
+                netProcessing 4394 "transaction inv sent in violation of protocol"
+              stop
+            let key = (iv.invType == InvWTx, iv.invHash)
+            if Set.member key seen
+              then go seen blocks rest
+              else do
+                addKnownTx (TxHash iv.invHash)
+                unless e.initialBlockDownload $
+                  process "transaction announcement" $
+                    netProcessing 4404 "AddTxAnnouncement"
+                go (Set.insert key seen) blocks rest
+        | otherwise = do
+            ignore $ netProcessing 4408 "Unknown inv type"
+            go seen blocks rest
+  blocks <- go Set.empty [] ivs
+  blockInvs (reverse blocks)
+
+-- | @getdata@ (line 4443) and @ProcessGetData@ (line 2764). On a private
+-- broadcast connection, only the one transaction that the node announced
+-- may be asked for. Elsewhere the entries are served in order: a run of
+-- transactions, with one @notfound@ for those the node lacks, then one
+-- block, then the next run. Upstream spreads this over several passes when
+-- the send buffer fills; the machine serves all at once.
+handleGetData :: GetData -> M ()
+handleGetData (GetData ivs) = do
+  when (length ivs > maxInvSz) $ do
+    let c = netProcessing 4448 "getdata message size"
+    misbehaving c
+    ignore c
+    stop
+  pb <- isPrivateBroadcast
+  when pb $ do
+    privateGetData ivs
+    stop
+  serve ivs
+  where
+    serve [] = return ()
+    serve items = do
+      let (txs, rest) = span (isTxInv . (.invType)) items
+      missing <- concat <$> mapM serveTx txs
+      unless (null missing) $
+        send (MNotFound (NotFound missing)) $
+          netProcessing 2831 "notfound"
+      case rest of
+        [] -> return ()
+        (iv : more) -> do
+          when (iv.invType `elem` [InvBlock, InvWitnessBlock, InvMerkleBlock, InvCompactBlock]) $
+            scoped (getBlockData iv)
+          s <- getS
+          unless s.disconnected (serve more)
+    serveTx iv = do
+      s <- getS
+      e <- env
+      case s.txRelay of
+        Nothing -> return []
+        Just _ -> case e.mempoolTx (TxHash iv.invHash) of
+          Just tx -> do
+            let tx' = if iv.invType == InvTx then tx {witness = []} else tx
+            send (MTx tx') $ netProcessing 2793 "tx"
+            return []
+          Nothing -> return [iv]
+
+-- | The @getdata@ of a private broadcast connection (line 4458): exactly
+-- the announced transaction, by txid, gets the transaction and a ping
+-- whose pong confirms the delivery. Anything else closes the connection.
+privateGetData :: [InvVector] -> M ()
+privateGetData ivs = do
+  s <- getS
+  e <- env
+  case (s.privateTx, e.privateBroadcastTx) of
+    (Just h, Just tx)
+      | [iv] <- ivs,
+        iv.invType == InvTx,
+        TxHash iv.invHash == h -> do
+          send (MTx tx) $ netProcessing 4473 "private broadcast: tx"
+          modifyS $ \st -> st {pingQueued = True}
+          maybeSendPing
+      | otherwise ->
+          disconnect ProtocolViolation $ netProcessing 4480 "got an unexpected GETDATA message"
+    _ -> disconnect ProtocolViolation $ netProcessing 4463 "got GETDATA without sending an INV"
+
+-- | @tx@ (line 4708). From a peer told not to send transactions it closes
+-- the connection; in initial block download it is dropped. Otherwise the
+-- mempool judges it, and whatever the verdict the peer is not punished.
+-- A peer with 'PermForceRelay' gets a transaction the node already has
+-- relayed again.
+handleTx :: Tx -> M ()
+handleTx tx = do
+  rejects <- rejectIncomingTxs
+  when rejects $ do
+    disconnect ProtocolViolation $ netProcessing 4711 "transaction sent in violation of protocol"
+    stop
+  e <- env
+  when e.initialBlockDownload $ do
+    ignore $ netProcessing 4718 "transaction during initial block download"
+    stop
+  s <- getS
+  addKnownTx (knownHash s tx)
+  case e.checkTx tx of
+    TxAlreadyKnown
+      | hasPermission PermForceRelay s ->
+          if isJust (e.mempoolTx (txHash tx))
+            then process "force relay" $ netProcessing 4749 "Force relaying tx"
+            else ignore $ netProcessing 4744 "Not relaying non-mempool transaction from forcerelay peer"
+      | otherwise -> ignore $ netProcessing 4738 "transaction already known: not validated"
+    TxAcceptedToMempool ->
+      process "transaction accepted" $ netProcessing 4769 "ProcessValidTx"
+    TxOrphan -> do
+      let parents = [p.hash | i <- tx.inputs, let p = i.outpoint]
+      forM_ parents addKnownTx
+      process "orphan transaction: parents requested" $ netProcessing 4773 "ProcessInvalidTx (missing inputs)"
+    TxPolicyReject _ ->
+      process "transaction rejected" $ netProcessing 4773 "ProcessInvalidTx"
+    TxConsensusInvalid _ ->
+      process "transaction rejected" $ netProcessing 4773 "ProcessInvalidTx"
+
+-- | @notfound@ (line 5343): the transaction entries mark the node's
+-- requests to this peer as failed, so that another peer is asked. Never a
+-- penalty.
+handleNotFound :: NotFound -> M ()
+handleNotFound (NotFound ivs)
+  | length ivs <= maxPeerTxAnnouncements + maxBlocksInTransitPerPeer
+      && any (isTxInv . (.invType)) ivs =
+      process "transaction requests failed" $ netProcessing 5355 "ReceivedNotFound"
+  | otherwise = ignore $ netProcessing 5347 "notfound without transactions"
+
+-- | @mempool@ of BIP 35 (line 5187): allowed when the node offers Bloom
+-- filters to the peer or the peer has 'PermMempool'. A refused request
+-- closes the connection, unless the peer has 'PermNoBan'. The answer goes
+-- out at the next trickle.
+handleMempool :: M ()
+handleMempool = do
+  s <- getS
+  o <- opts
+  e <- env
+  let bloom = s.ourServices .&. C.nodeBloom /= 0
+      mempoolPerm = hasPermission PermMempool s
+      noban = hasPermission PermNoBan s
+  when (not bloom && not mempoolPerm) $ do
+    if noban
+      then ignore $ netProcessing 5197 "mempool request with bloom filters disabled (noban)"
+      else disconnect ProtocolViolation $ netProcessing 5195 "mempool request with bloom filters disabled"
+    stop
+  when (o.maxUploadTarget > 0 && e.uploadTargetReached && not mempoolPerm) $ do
+    if noban
+      then ignore $ netProcessing 5207 "mempool request with bandwidth limit reached (noban)"
+      else disconnect Resources $ netProcessing 5205 "mempool request with bandwidth limit reached"
+    stop
+  modifyTxRelay $ \r -> r {sendMempool = True}
+
+-- | @feefilter@ of BIP 133 (line 5316): kept when it is a valid amount.
+handleFeeFilter :: FeeFilter -> M ()
+handleFeeFilter (FeeFilter rate)
+  | rate <= maxMoney = modifyTxRelay $ \r -> r {feeFilterReceived = rate}
+  | otherwise = ignore $ netProcessing 5319 "feefilter out of range"
+
+-- | Whether the node offers @NODE_BLOOM@ to the peer.
+offersBloom :: State -> Bool
+offersBloom s = s.ourServices .&. C.nodeBloom /= 0
+
+-- | @filterload@ of BIP 37 (line 5242). Without @NODE_BLOOM@ offered, it
+-- closes the connection, even for a peer with 'PermNoBan'. A filter over
+-- 36,000 bytes or 50 hash functions is misbehaviour. A loaded filter turns
+-- transaction relay on.
+handleFilterLoad :: FilterLoad -> M ()
+handleFilterLoad (FilterLoad bf) = do
+  s <- getS
+  unless (offersBloom s) $ do
+    disconnect ProtocolViolation $
+      netProcessing 5245 "filterload received despite not offering bloom services"
+    stop
+  if length bf.array > maxBloomFilterSize || bf.functions > maxHashFuncs
+    then do
+      let c = netProcessing 5254 "too-large bloom filter"
+      misbehaving c
+      ignore c
+    else case s.txRelay of
+      Nothing -> ignore $ netProcessing 5255 "filterload without transaction relay"
+      Just _ -> do
+        modifyTxRelay $ \r -> r {bloomFilter = Just bf, relayTxs = True}
+        modifyS $ \st -> st {relaysTxs = True}
+        _ <- maybeDisconnectForTxRelayCapacity
+        return ()
+
+-- | @filteradd@ (line 5268): data over 520 bytes, or no filter loaded, is
+-- misbehaviour.
+handleFilterAdd :: FilterAdd -> M ()
+handleFilterAdd (FilterAdd bytes) = do
+  s <- getS
+  unless (offersBloom s) $ do
+    disconnect ProtocolViolation $
+      netProcessing 5271 "filteradd received despite not offering bloom services"
+    stop
+  let bad = do
+        let c = netProcessing 5291 "bad filteradd message"
+        misbehaving c
+        ignore c
+  if B.length bytes > maxScriptElementSize
+    then bad
+    else case s.txRelay of
+      Nothing -> return ()
+      Just r -> case r.bloomFilter of
+        Nothing -> bad
+        Just bf -> modifyTxRelay $ \x -> x {bloomFilter = Just (bloomInsert bf bytes)}
+
+-- | @filterclear@ (line 5296): drop the filter and relay every
+-- transaction.
+handleFilterClear :: M ()
+handleFilterClear = do
+  s <- getS
+  unless (offersBloom s) $ do
+    disconnect ProtocolViolation $
+      netProcessing 5299 "filterclear received despite not offering bloom services"
+    stop
+  case s.txRelay of
+    Nothing -> ignore $ netProcessing 5303 "filterclear without transaction relay"
+    Just _ -> do
+      modifyTxRelay $ \r -> r {bloomFilter = Nothing, relayTxs = True}
+      modifyS $ \st -> st {relaysTxs = True}
+      _ <- maybeDisconnectForTxRelayCapacity
+      return ()
+
+-- | The key of an address in the known set.
+addrKey :: NetworkAddressV2 -> (Word8, ByteString, Word16)
+addrKey a = (addressNetworkId a.network, a.address, a.port)
+
+-- | @ProcessAddrs@ (line 5972), for @addr@ and @addrv2@. No address relay
+-- with block-relay-only and feeler connections. More than 1,000 addresses
+-- is misbehaviour. A token bucket, refilled at 0.1 a second, limits how
+-- many are processed, unless the peer has 'PermAddr'. An address fetch
+-- connection is done once it gets more than one address.
+handleAddrs :: Bool -> [NetworkAddressV2] -> M ()
+handleAddrs v2 addrs = do
+  ok <- setupAddressRelay
+  unless ok $ do
+    ignore $ netProcessing 5978 "ignoring addr message from block-relay-only or feeler peer"
+    stop
+  when (length addrs > maxAddrToSend) $ do
+    let c =
+          netProcessing 5984 $
+            if v2 then "addrv2 message size" else "addr message size"
+    misbehaving c
+    ignore c
+    stop
+  t <- now
+  s <- getS
+  let elapsed = max 0 (fromIntegral (t - s.addrTokensAt) / 1000000) :: Double
+      bucket0
+        | s.addrTokens < maxAddrProcessingTokenBucket =
+            min maxAddrProcessingTokenBucket (s.addrTokens + elapsed * maxAddrRatePerSecond)
+        | otherwise = s.addrTokens
+      rateLimited = not (hasPermission PermAddr s)
+      step' (bucket, acc) a
+        | bucket < 1 && rateLimited = (bucket, acc)
+        | bucket < 1 = (bucket, a : acc)
+        | otherwise = (bucket - 1, a : acc)
+      (bucket1, taken) = foldl step' (bucket0, []) addrs
+      useful a =
+        a.services .&. (nodeNetwork + nodeNetworkLimited) /= 0
+          || a.services .&. (nodeNetwork + nodeWitness) == nodeNetwork + nodeWitness
+      kept = filter useful (reverse taken)
+  putS
+    s
+      { addrTokens = bucket1,
+        addrTokensAt = t,
+        addrKnown = foldr (Set.insert . addrKey) s.addrKnown kept,
+        getAddrSent = if length addrs < 1000 then False else s.getAddrSent
+      }
+  unless (null kept) $
+    process "addresses to the address manager" $
+      netProcessing 6049 "addrman Add"
+  s' <- getS
+  when (s'.connectionType == AddrFetch && length addrs > 1) $
+    disconnect Done $
+      netProcessing 6055 "addrfetch connection completed"
+
+-- | @getaddr@ (line 5151): answered once, and only for an inbound peer.
+-- The answer, from the node's cache unless the peer has 'PermAddr', goes
+-- out with the next address send.
+handleGetAddr :: M ()
+handleGetAddr = do
+  s <- getS
+  e <- env
+  when (s.connectionType /= Inbound) $ do
+    ignore $ netProcessing 5158 "Ignoring getaddr from an outbound connection"
+    stop
+  _ <- setupAddressRelay
+  when s.getAddrRecvd $ do
+    ignore $ netProcessing 5169 "Ignoring repeated getaddr"
+    stop
+  modifyS $ \st -> st {getAddrRecvd = True, addrsToSend = []}
+  forM_ (e.addressesForPeer (hasPermission PermAddr s)) pushAddress
+
+-- | Whether an address can go to the peer: addresses that the old format
+-- cannot carry go only to peers that sent @sendaddrv2@ (@IsAddrCompatible@).
+addrCompatible :: State -> NetworkAddressV2 -> Bool
+addrCompatible s a = s.wantsAddrV2 || isJust (C.fromNetworkAddressV2 a)
+
+-- | @PushAddress@: queue an address unless the peer knows it or cannot
+-- take it; a full queue replaces a random entry.
+pushAddress :: NetworkAddressV2 -> M ()
+pushAddress a = do
+  s <- getS
+  let valid = maybe True (== fromIntegral (lengthOf a)) (addressNetworkLength a.network)
+  when (valid && not (Set.member (addrKey a) s.addrKnown) && addrCompatible s a) $
+    if length s.addrsToSend >= maxAddrToSend
+      then do
+        i <- random (randomBelow (fromIntegral (length s.addrsToSend)))
+        let (before, after) = splitAt (fromIntegral i) s.addrsToSend
+        modifyS $ \st -> st {addrsToSend = before ++ [a] ++ drop 1 after}
+      else modifyS $ \st -> st {addrsToSend = st.addrsToSend ++ [a]}
+  where
+    lengthOf x = B.length x.address
+
+-- | @MaybeSendAddr@ (line 5740): with address relay on, the node's own
+-- address about once a day (at once the first time, in a message of its
+-- own), and the queue of addresses about every 30 seconds, as @addrv2@ to
+-- a peer that asked for it and @addr@ otherwise.
+maybeSendAddr :: M ()
+maybeSendAddr = do
+  s <- getS
+  o <- opts
+  e <- env
+  t <- now
+  when s.addrRelay $ do
+    when (o.listen && not e.initialBlockDownload && s.nextLocalAddrSend < t) $ do
+      when (s.nextLocalAddrSend /= 0) $ modifyS $ \st -> st {addrKnown = Set.empty}
+      forM_ e.localAddress $ \la0 -> do
+        let la = la0 {services = s.ourServices, time = fromIntegral (t `div` 1000000)}
+        if s.nextLocalAddrSend == 0
+          then when (addrCompatible s la) $ sendAddrs [la] $ netProcessing 5767 "self-announcement"
+          else pushAddress la
+      d <- random (poissonDelay avgLocalAddressBroadcastInterval)
+      modifyS $ \st -> st {nextLocalAddrSend = t + d}
+    s1 <- getS
+    when (t > s1.nextAddrSend) $ do
+      d <- random (poissonDelay avgAddressBroadcastInterval)
+      let fresh = go s1.addrKnown s1.addrsToSend
+          go _ [] = []
+          go known (a : rest)
+            | Set.member (addrKey a) known = go known rest
+            | otherwise = a : go (Set.insert (addrKey a) known) rest
+          known' = foldr (Set.insert . addrKey) s1.addrKnown s1.addrsToSend
+      modifyS $ \st -> st {nextAddrSend = t + d, addrKnown = known', addrsToSend = []}
+      unless (null fresh) $ sendAddrs fresh $ netProcessing 5805 "addr"
+  where
+    sendAddrs as c = do
+      s <- getS
+      if s.wantsAddrV2
+        then send (MAddrV2 (AddrV2 as)) c
+        else send (MAddr (C.Addr (mapMaybe C.fromNetworkAddressV2 as))) c
+
+-- | The fee filter buckets (@MakeFeeSet@ in
+-- @src\/policy\/fees\/block_policy_estimator.cpp@): 0, then 50 satoshi per
+-- 1000 virtual bytes rising by a tenth up to 10,000,000.
+feeFilterBuckets :: [Double]
+feeFilterBuckets = 0 : takeWhile (<= 1e7) (iterate (* 1.1) 50)
+
+-- | @FeeFilterRounder::round@: the first bucket at or above the fee rate,
+-- or, two times in three, the bucket below it, so that the filter does not
+-- reveal the mempool exactly.
+roundFeeFilter :: Word64 -> Rng -> (Word64, Rng)
+roundFeeFilter x g =
+  let (r, g') = nextWord64 g
+      above = dropWhile (< fromIntegral x) feeFilterBuckets
+      below = takeWhile (< fromIntegral x) feeFilterBuckets
+      pick = case above of
+        [] -> last feeFilterBuckets
+        (a : _)
+          | not (null below) && (r .&. 0xffffffff) `mod` 3 /= 0 -> last below
+          | otherwise -> a
+   in (truncate pick, g')
+
+-- | @MaybeSendFeefilter@ (line 5838): about every 10 minutes, the minimum
+-- fee rate of the mempool, rounded, and the maximum during initial block
+-- download. Not in blocks-only mode, nor to a peer with 'PermForceRelay',
+-- nor on a block-relay-only connection.
+maybeSendFeeFilter :: M ()
+maybeSendFeeFilter = do
+  s <- getS
+  o <- opts
+  e <- env
+  t <- now
+  let skip =
+        o.blocksOnly
+          || s.commonVersion < feeFilterVersion
+          || hasPermission PermForceRelay s
+          || s.connectionType == BlockRelayOnly
+  unless skip $ do
+    let maxFilter = truncate (last feeFilterBuckets) :: Word64
+        current = if e.initialBlockDownload then maxMoney else e.mempoolMinFee
+    when (not e.initialBlockDownload && s.feeFilterSent == maxFilter) $
+      modifyS $
+        \st -> st {nextFeeFilter = 0}
+    s1 <- getS
+    if t > s1.nextFeeFilter
+      then do
+        rounded <- random (roundFeeFilter current)
+        let toSend = max rounded o.minRelayTxFee
+        when (toSend /= s1.feeFilterSent) $ do
+          send (MFeeFilter (FeeFilter toSend)) $ netProcessing 5867 "feefilter"
+          modifyS $ \st -> st {feeFilterSent = toSend}
+        d <- random (poissonDelay avgFeeFilterBroadcastInterval)
+        modifyS $ \st -> st {nextFeeFilter = t + d}
+      else when
+        ( t + maxFeeFilterChangeDelay < s1.nextFeeFilter
+            && ( current < 3 * s1.feeFilterSent `div` 4
+                   || current > 4 * s1.feeFilterSent `div` 3
+               )
+        )
+        $ do
+          d <- random (randomBelow (fromIntegral maxFeeFilterChangeDelay))
+          modifyS $ \st -> st {nextFeeFilter = t + fromIntegral d}
+
+-- | The transaction part of the trickle (lines 6327 to 6436): when the
+-- timer of the peer fires (always, for a peer with 'PermNoBan'), the
+-- answer to @mempool@ and the queued transactions, less those under the
+-- peer's fee filter, those it knows and those its Bloom filter rejects.
+-- Returns the entries for the @inv@, which the caller sends after the
+-- block entries.
+sendTxTrickle :: M [InvVector]
+sendTxTrickle = do
+  s <- getS
+  e <- env
+  t <- now
+  case s.txRelay of
+    Nothing -> return []
+    Just r0 -> do
+      fire <-
+        if r0.nextInvSend < t
+          then do
+            let mean
+                  | s.connectionType == Inbound = inboundInventoryBroadcastInterval
+                  | otherwise = outboundInventoryBroadcastInterval
+            d <- random (poissonDelay mean)
+            modifyTxRelay $ \r -> r {nextInvSend = t + d}
+            return True
+          else return (hasPermission PermNoBan s)
+      if not fire
+        then return []
+        else do
+          unless r0.relayTxs $ modifyTxRelay $ \r -> r {toSend = []}
+          mempoolInvs <-
+            if r0.sendMempool
+              then do
+                modifyTxRelay $ \r -> r {sendMempool = False, toSend = []}
+                concat <$> mapM (announce False) e.mempoolTxs
+              else return []
+          pending <- maybe [] (.toSend) . (.txRelay) <$> getS
+          let queued = mapMaybe e.mempoolTx pending
+              byFee = sortOn (Down . maybe 0 id . e.txFeeRate . txHash) queued
+          modifyTxRelay $ \r -> r {toSend = []}
+          queuedInvs <- concat <$> mapM (announce True) byFee
+          return (mempoolInvs ++ queuedInvs)
+  where
+    announce checkKnown tx = do
+      s <- getS
+      e <- env
+      case s.txRelay of
+        Nothing -> return []
+        Just r -> do
+          let h = knownHash s tx
+              rate = maybe 0 id (e.txFeeRate (txHash tx))
+              inv = InvVector (if s.wtxidRelay then InvWTx else InvTx) h.get
+          if rate < r.feeFilterReceived || (checkKnown && Set.member h r.knownTxs)
+            then return []
+            else case r.bloomFilter of
+              Just bf -> case bloomRelevantUpdate bf tx of
+                Nothing -> return []
+                Just bf' -> do
+                  modifyTxRelay $ \x -> x {bloomFilter = Just bf', knownTxs = Set.insert h x.knownTxs}
+                  return [inv]
+              Nothing -> do
+                addKnownTx h
+                return [inv]
+
+-- | A transaction entered the mempool and the node's announcement buckets
+-- released it (@InitiateTxBroadcastToAll@ and @ProcessInvBacklog@): queue
+-- it for the next trickle, for a peer with transaction relay that has had
+-- its first pass after the handshake.
+txAccepted :: Tx -> M ()
+txAccepted tx = do
+  s <- getS
+  case s.txRelay of
+    Just r
+      | r.nextInvSend /= 0 ->
+          modifyTxRelay $ \x -> x {toSend = x.toSend ++ [txWitnessHash tx]}
+    _ -> return ()
+
+-- | The node relays an address through this peer (@RelayAddress@ chose
+-- it): queue it if address relay is on.
+relayAddress :: NetworkAddressV2 -> M ()
+relayAddress a = do
+  s <- getS
+  when s.addrRelay $ pushAddress a
+
+-- | The node's transaction download asks the peer for a transaction (line
+-- 6552): by wtxid from a peer that relays by wtxid, by txid with the
+-- witness flag otherwise.
+requestTx :: TxHash -> M ()
+requestTx h = do
+  s <- getS
+  when (s.successfullyConnected && isJust s.txRelay) $ do
+    let t
+          | s.wtxidRelay = InvWTx
+          | s.theirServices .&. nodeWitness /= 0 = InvWitnessTx
+          | otherwise = InvTx
+    send (MGetData (GetData [InvVector t h.get])) $ netProcessing 6553 "getdata for a transaction"
diff --git a/src/Haskoin/Network/Protocol/BitcoinCore/State.hs b/src/Haskoin/Network/Protocol/BitcoinCore/State.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Network/Protocol/BitcoinCore/State.hs
@@ -0,0 +1,548 @@
+{-# LANGUAGE DeriveAnyClass #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- |
+-- Module      : Haskoin.Network.Protocol.BitcoinCore.State
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- The options of a Bitcoin Core 32.1 node and the state that it keeps about
+-- one peer, for the machine of "Haskoin.Network.Protocol.BitcoinCore".
+--
+-- Upstream spreads the state of a peer over three structures: @CNode@ in
+-- @src\/net.h@ (the connection: transport, permissions, handshake flags),
+-- @Peer@ in @src\/net_processing.cpp@ (what the protocol negotiated: ping,
+-- address relay, transaction relay) and @CNodeState@ in the same file (what
+-- the block download knows, under @cs_main@). t'State' keeps them in one
+-- record, with the block part in t'BlockState' and the transaction part in
+-- t'TxRelay'. Each field names its upstream counterpart, so that a reader of
+-- either code can find the other.
+--
+-- What is left out of the state is what only the rest of the node needs:
+-- statistics for eviction, byte counters, the address manager. Global
+-- tables that several peers share, such as the blocks in flight from all
+-- peers, are asked of the t'Env' instead.
+module Haskoin.Network.Protocol.BitcoinCore.State
+  ( -- * Options
+    Options (..),
+    defaultOptions,
+    localServices,
+
+    -- * State
+    State (..),
+    TxRelay (..),
+    BlockState (..),
+    InFlight (..),
+    ChainSync (..),
+    Reconciliation (..),
+    start,
+    expandPermissions,
+    hasPermission,
+    newTxRelay,
+
+    -- * Inspection
+    handshakeComplete,
+    versionReceived,
+    isDisconnected,
+    discouragementPending,
+    blocksInFlight,
+    pingOutstanding,
+    txRelayEnabled,
+    addrRelayEnabled,
+  )
+where
+
+import Control.DeepSeq (NFData)
+import Data.Bits ((.|.))
+import Data.ByteString (ByteString)
+import Data.Int (Int32)
+import Data.Maybe (isJust)
+import Data.Set (Set)
+import Data.Set qualified as Set
+import Data.Word (Word16, Word64, Word8)
+import GHC.Generics (Generic)
+import Haskoin.Block.Common (BlockHash)
+import Haskoin.Network.Bloom (BloomFilter)
+import Haskoin.Network.Common
+  ( AddressNetwork (..),
+    NetworkAddressV2,
+    nodeBloom,
+    nodeCompactFilters,
+    nodeNetwork,
+    nodeNetworkLimited,
+    nodeP2PV2,
+    nodeWitness,
+  )
+import Haskoin.Network.CompactBlock (CompactBlock)
+import Haskoin.Network.Data (Network (..))
+import Haskoin.Network.Protocol.BitcoinCore.Constants
+import Haskoin.Network.Protocol.Types
+import Haskoin.Transaction.Common (TxHash)
+
+-- | The options of the node that change what a peer sees. Each field is a
+-- command-line option of @bitcoind@, or a constant of the chain that the
+-- node takes from its chain parameters. 'defaultOptions' gives the values
+-- of a node started with no options.
+data Options = Options
+  { -- | the chain, which gives the magic bytes and the minimum chain work
+    network :: !Network,
+    -- | @-blocksonly@ (default off): the node tells its peers not to send
+    -- transactions, and disconnects those that do unless they have
+    -- 'PermRelay' (@ignore_incoming_txs@)
+    blocksOnly :: !Bool,
+    -- | @-peerbloomfilters@ (default off): the node offers @NODE_BLOOM@ and
+    -- serves BIP 37 filters and the @mempool@ message
+    peerBloomFilters :: !Bool,
+    -- | @-peerblockfilters@ (default off): the node offers
+    -- @NODE_COMPACT_FILTERS@ and serves BIP 157 filters
+    peerBlockFilters :: !Bool,
+    -- | @-txreconciliation@ (default off, debug only): the node sends and
+    -- accepts @sendtxrcncl@ (Erlay, BIP 330)
+    txReconciliation :: !Bool,
+    -- | @-maxuploadtarget@ in bytes a day, 0 for none (the default). Whether
+    -- the target is reached is @uploadTargetReached@ and
+    -- @historicalUploadTargetReached@ of t'Env'; this field only says whether
+    -- there is one.
+    maxUploadTarget :: !Word64,
+    -- | @-listen@ (default on): the node advertises its own address
+    listen :: !Bool,
+    -- | @-prune@ (default off): a pruned node offers @NODE_NETWORK_LIMITED@
+    -- without @NODE_NETWORK@, and refuses deep blocks
+    prune :: !Bool,
+    -- | @-v2transport@ (default on): the node offers @NODE_P2P_V2@
+    v2Transport :: !Bool,
+    -- | @-whitelistrelay@: 'Nothing' for the upstream default, which is on
+    -- unless @-blocksonly@ is set, and on whenever @-whitelistforcerelay@ is
+    -- (@src\/init.cpp@ soft-sets it)
+    whitelistRelay :: !(Maybe Bool),
+    -- | @-whitelistforcerelay@ (default off)
+    whitelistForceRelay :: !Bool,
+    -- | @-peertimeout@ (default 60 seconds): how long a new connection has
+    -- to finish its handshake before the inactivity checks apply
+    peerTimeout :: !Micros,
+    -- | @-minimumchainwork@ (debug only), by default
+    -- @minimumChainWork@ of t'Network' of the chain
+    minimumChainWork :: !Integer,
+    -- | @-minrelaytxfee@ (default 100 satoshi per 1000 virtual bytes), the
+    -- floor of the fee filter that the node sends
+    minRelayTxFee :: !Word64,
+    -- | the user agent, @\/Satoshi:32.1.0\/@ unless @-uacomment@ adds to it
+    userAgent :: !ByteString
+  }
+  deriving (Eq, Show, Generic, NFData)
+
+-- | The options of a node started on a chain with no options. The chain
+-- gives the magic bytes and the minimum chain work; every other default is
+-- the same on the four Bitcoin chains.
+defaultOptions :: Network -> Options
+defaultOptions net =
+  Options
+    { network = net,
+      blocksOnly = False,
+      peerBloomFilters = False,
+      peerBlockFilters = False,
+      txReconciliation = False,
+      maxUploadTarget = 0,
+      listen = True,
+      prune = False,
+      v2Transport = True,
+      whitelistRelay = Nothing,
+      whitelistForceRelay = False,
+      peerTimeout = defaultPeerConnectTimeout,
+      minimumChainWork = net.minimumChainWork,
+      minRelayTxFee = defaultMinRelayTxFee,
+      userAgent = defaultUserAgent
+    }
+
+-- | The services that the node offers to every peer (@g_local_services@):
+-- @NODE_NETWORK_LIMITED | NODE_WITNESS@ always, @NODE_NETWORK@ unless
+-- pruned, @NODE_P2P_V2@ with @-v2transport@, @NODE_COMPACT_FILTERS@ with
+-- @-peerblockfilters@ and @NODE_BLOOM@ with @-peerbloomfilters@
+-- (@src\/init.cpp@).
+localServices :: Options -> Word64
+localServices o =
+  foldr
+    (.|.)
+    (nodeNetworkLimited .|. nodeWitness)
+    [ if o.prune then 0 else nodeNetwork,
+      if o.v2Transport then nodeP2PV2 else 0,
+      if o.peerBlockFilters then nodeCompactFilters else 0,
+      if o.peerBloomFilters then nodeBloom else 0
+    ]
+
+-- | The state of Erlay for the peer (@TxReconciliationTracker@).
+data Reconciliation
+  = -- | nothing was sent or registered
+    NoReconciliation
+  | -- | the node sent @sendtxrcncl@ with this salt (@PreRegisterPeer@)
+    PreRegistered !Word64
+  | -- | the peer answered with its own @sendtxrcncl@ (@RegisterPeer@)
+    Registered
+  deriving (Eq, Show, Generic, NFData)
+
+-- | Transaction relay with the peer (@Peer::TxRelay@). It exists only if the
+-- connection is not block-relay-only or a feeler, and the peer asked for
+-- transactions in its @version@ or the node offers it Bloom filters.
+data TxRelay = TxRelay
+  { -- | @m_relay_txs@: the peer wants transaction announcements
+    relayTxs :: !Bool,
+    -- | @m_bloom_filter@: the BIP 37 filter of the peer
+    bloomFilter :: !(Maybe BloomFilter),
+    -- | @m_tx_inventory_known_filter@: transactions announced by the peer or
+    -- to it. Upstream it is a rolling Bloom filter of 50,000 entries, which
+    -- forgets; here it is a set, which does not.
+    knownTxs :: !(Set TxHash),
+    -- | @m_tx_inventory_to_send@: transactions to announce at the next
+    -- trickle, by wtxid
+    toSend :: ![TxHash],
+    -- | @m_send_mempool@: the peer sent @mempool@
+    sendMempool :: !Bool,
+    -- | @m_next_inv_send_time@: the next trickle; 0 until the first
+    -- @SendMessages@ after the handshake
+    nextInvSend :: !Micros,
+    -- | @m_fee_filter_received@: the fee filter of the peer
+    feeFilterReceived :: !Word64
+  }
+  deriving (Eq, Show, Generic, NFData)
+
+-- | A new t'TxRelay'.
+newTxRelay :: Bool -> TxRelay
+newTxRelay r =
+  TxRelay
+    { relayTxs = r,
+      bloomFilter = Nothing,
+      knownTxs = Set.empty,
+      toSend = [],
+      sendMempool = False,
+      nextInvSend = 0,
+      feeFilterReceived = 0
+    }
+
+-- | A block requested from the peer (@QueuedBlock@).
+data InFlight = InFlight
+  { block :: !BlockHash,
+    -- | @partialBlock@: the compact block being completed, if the request
+    -- is a @getblocktxn@
+    partial :: !(Maybe CompactBlock),
+    -- | @partialBlock->header.IsNull()@: @FillBlock@ already used the
+    -- compact block, so a second @blocktxn@ for it is misbehaviour
+    filled :: !Bool
+  }
+  deriving (Eq, Show, Generic, NFData)
+
+-- | The chain sync check of an outbound peer (@CNodeState::ChainSyncTimeoutState@).
+data ChainSync = ChainSync
+  { -- | @m_timeout@, 0 when unset
+    timeout :: !Micros,
+    -- | @m_work_header@: the tip when the timer started
+    workHeader :: !(Maybe BlockHash),
+    -- | @m_sent_getheaders@
+    sentGetHeaders :: !Bool,
+    -- | @m_protect@: one of the four outbound peers never evicted this way
+    protect :: !Bool
+  }
+  deriving (Eq, Show, Generic, NFData)
+
+-- | What the block download knows of the peer: the fields of @CNodeState@
+-- and the block fields of @Peer@.
+data BlockState = BlockState
+  { -- | @fPreferredDownload@
+    preferredDownload :: !Bool,
+    -- | @pindexBestKnownBlock@: the best block that the peer has
+    bestKnownBlock :: !(Maybe BlockHash),
+    -- | @hashLastUnknownBlock@: an announced block that the node did not know
+    lastUnknownBlock :: !(Maybe BlockHash),
+    -- | @pindexBestHeaderSent@
+    bestHeaderSent :: !(Maybe BlockHash),
+    -- | @fSyncStarted@: the initial @getheaders@ went to this peer
+    syncStarted :: !Bool,
+    -- | @m_headers_sync_timeout@; 'Nothing' for the maximum, never
+    headersSyncTimeout :: !(Maybe Micros),
+    -- | @m_last_getheaders_timestamp@; 'Nothing' for the epoch
+    lastGetHeaders :: !(Maybe Micros),
+    -- | @m_headers_sync@: a low-work headers sync is running from this
+    -- block, the parent of its first header
+    lowWorkSync :: !(Maybe BlockHash),
+    -- | @m_inv_triggered_getheaders_before_sync@
+    invTriggeredGetHeaders :: !Bool,
+    -- | @m_stalling_since@
+    stallingSince :: !(Maybe Micros),
+    -- | @vBlocksInFlight@, oldest first
+    inFlight :: ![InFlight],
+    -- | @m_downloading_since@
+    downloadingSince :: !Micros,
+    -- | @m_prefers_headers@: the peer sent @sendheaders@
+    prefersHeaders :: !Bool,
+    -- | @m_sent_sendheaders@
+    sentSendHeaders :: !Bool,
+    -- | @m_provides_cmpctblocks@: the peer sent @sendcmpct@ of version 2
+    providesCmpct :: !Bool,
+    -- | @m_requested_hb_cmpctblocks@: the peer wants compact blocks pushed
+    requestedHbCmpct :: !Bool,
+    -- | @m_bip152_highbandwidth_to@: the node chose the peer as a
+    -- high-bandwidth compact block peer
+    highBandwidthTo :: !Bool,
+    -- | @m_chain_sync@
+    chainSync :: !ChainSync,
+    -- | @m_last_block_announcement@
+    lastBlockAnnouncement :: !(Maybe Micros),
+    -- | @m_blocks_for_headers_relay@
+    forHeadersRelay :: ![BlockHash],
+    -- | @m_blocks_for_inv_relay@
+    forInvRelay :: ![BlockHash],
+    -- | @m_continuation_block@ of a @getblocks@ answer
+    continuationBlock :: !(Maybe BlockHash)
+  }
+  deriving (Eq, Show, Generic, NFData)
+
+-- | What the node keeps about one peer.
+data State = State
+  { -- | @m_conn_type@
+    connectionType :: !ConnectionType,
+    -- | @m_permission_flags@, expanded by 'expandPermissions'
+    permissions :: !Permissions,
+    -- | address network of the peer
+    peerNetwork :: !AddressNetwork,
+    -- | the transport of the connection (@m_transport@)
+    transport :: !TransportVersion,
+    -- | @addr.IsLocal()@: a local address, or an inbound Tor peer, whose
+    -- address is that of the local proxy
+    isLocal :: !Bool,
+    -- | @m_connected@
+    connectedAt :: !Micros,
+    -- | the randomness of the node for this peer
+    rng :: !Rng,
+    -- | @Peer::m_our_services@: what the node offers to this peer
+    ourServices :: !Word64,
+    -- | @nLocalHostNonce@, the nonce of the node's @version@
+    localNonce :: !Word64,
+    -- | @fDisconnect@
+    disconnected :: !Bool,
+    -- | @m_should_discourage@, with the place of the @Misbehaving@ call
+    shouldDiscourage :: !(Maybe Cite),
+    -- | @m_outbound_version_message_sent@, or for an inbound peer that the
+    -- node answered its @version@
+    versionSent :: !Bool,
+    -- | @CNode::nVersion@: the peer's version, 'Nothing' before its @version@
+    peerVersion :: !(Maybe Int32),
+    -- | @m_greatest_common_version@
+    commonVersion :: !Int32,
+    -- | @Peer::m_their_services@
+    theirServices :: !Word64,
+    -- | @cleanSubVer@
+    peerUserAgent :: !ByteString,
+    -- | @fSuccessfullyConnected@: the peer's @verack@ came
+    successfullyConnected :: !Bool,
+    -- | @m_last_send@; 'Nothing' before the first byte
+    lastSend :: !(Maybe Micros),
+    -- | @m_last_recv@; 'Nothing' before the first byte
+    lastRecv :: !(Maybe Micros),
+    -- | @m_wtxid_relay@
+    wtxidRelay :: !Bool,
+    -- | @m_wants_addrv2@
+    wantsAddrV2 :: !Bool,
+    -- | Erlay registration
+    reconciliation :: !Reconciliation,
+    -- | @m_ping_nonce_sent@, 0 for none
+    pingNonceSent :: !Word64,
+    -- | @m_ping_start@
+    pingStart :: !Micros,
+    -- | @m_ping_queued@
+    pingQueued :: !Bool,
+    -- | @m_last_ping_time@
+    lastPingTime :: !(Maybe Micros),
+    -- | @m_min_ping_time@
+    minPingTime :: !(Maybe Micros),
+    -- | @Peer::m_tx_relay@
+    txRelay :: !(Maybe TxRelay),
+    -- | @CNode::m_relays_txs@
+    relaysTxs :: !Bool,
+    -- | @m_addr_relay_enabled@
+    addrRelay :: !Bool,
+    -- | @m_addr_known@. Upstream a rolling Bloom filter of 5,000 entries;
+    -- here a set of addresses as network, bytes and port.
+    addrKnown :: !(Set (Word8, ByteString, Word16)),
+    -- | @m_addrs_to_send@
+    addrsToSend :: ![NetworkAddressV2],
+    -- | @m_getaddr_sent@
+    getAddrSent :: !Bool,
+    -- | @m_getaddr_recvd@
+    getAddrRecvd :: !Bool,
+    -- | @m_addr_token_bucket@
+    addrTokens :: !Double,
+    -- | @m_addr_token_timestamp@
+    addrTokensAt :: !Micros,
+    -- | @m_next_addr_send@
+    nextAddrSend :: !Micros,
+    -- | @m_next_local_addr_send@
+    nextLocalAddrSend :: !Micros,
+    -- | @m_fee_filter_sent@
+    feeFilterSent :: !Word64,
+    -- | @m_next_send_feefilter@
+    nextFeeFilter :: !Micros,
+    -- | the transaction announced on a private broadcast connection
+    privateTx :: !(Maybe TxHash),
+    -- | the block download
+    blocks :: !BlockState
+  }
+  deriving (Eq, Show, Generic, NFData)
+
+-- | Expand the permissions of a peer as Bitcoin Core does. A bare
+-- @-whitelist@ or @-whitebind@ ('PermImplicit') gives 'PermNoBan',
+-- 'PermMempool', 'PermRelay' unless @-whitelistrelay@ is off, and
+-- 'PermForceRelay' with @-whitelistforcerelay@; the flag 'PermImplicit'
+-- itself is cleared (@AddWhitelistPermissionFlags@, @src\/net.cpp@). Then
+-- the flags that include others are expanded as their bit masks do in
+-- @src\/net_permissions.h@: 'PermForceRelay' includes 'PermRelay', and
+-- 'PermNoBan' includes 'PermDownload'.
+expandPermissions :: Options -> Permissions -> Permissions
+expandPermissions o ps0 = implied (implicit ps0)
+  where
+    relayDefault = case o.whitelistRelay of
+      Just b -> b
+      Nothing -> not o.blocksOnly || o.whitelistForceRelay
+    implicit ps
+      | PermImplicit `Set.member` ps =
+          Set.unions
+            [ Set.delete PermImplicit ps,
+              Set.fromList [PermNoBan, PermMempool],
+              if relayDefault || o.whitelistForceRelay then Set.singleton PermRelay else Set.empty,
+              if o.whitelistForceRelay then Set.singleton PermForceRelay else Set.empty
+            ]
+      | otherwise = ps
+    implied ps =
+      Set.unions
+        [ ps,
+          if PermForceRelay `Set.member` ps then Set.singleton PermRelay else Set.empty,
+          if PermNoBan `Set.member` ps then Set.singleton PermDownload else Set.empty
+        ]
+
+-- | Whether the peer has a permission (@HasPermission@).
+hasPermission :: Permission -> State -> Bool
+hasPermission p s = p `Set.member` s.permissions
+
+-- | The state when a connection opens: what @CNode@'s constructor and
+-- @InitializeNode@ set up. The node offers @NODE_BLOOM@ to a peer with
+-- 'PermBloomFilter' even without @-peerbloomfilters@.
+start :: Options -> Setup -> State
+start o s =
+  let perms = expandPermissions o s.permissions
+      (nonce, g) = nextWord64 (Rng s.seed)
+      ours
+        | PermBloomFilter `Set.member` perms = localServices o .|. nodeBloom
+        | otherwise = localServices o
+      onionInbound = s.connectionType == Inbound && s.peerNetwork `elem` [AddrTorV2, AddrTorV3]
+   in State
+        { connectionType = s.connectionType,
+          permissions = perms,
+          peerNetwork = s.peerNetwork,
+          transport = s.transport,
+          isLocal = s.peerIsLocal || onionInbound,
+          connectedAt = s.openedAt,
+          rng = g,
+          ourServices = ours,
+          localNonce = nonce,
+          disconnected = False,
+          shouldDiscourage = Nothing,
+          versionSent = False,
+          peerVersion = Nothing,
+          commonVersion = initProtoVersion,
+          theirServices = 0,
+          peerUserAgent = "",
+          successfullyConnected = False,
+          lastSend = Nothing,
+          lastRecv = Nothing,
+          wtxidRelay = False,
+          wantsAddrV2 = False,
+          reconciliation = NoReconciliation,
+          pingNonceSent = 0,
+          pingStart = 0,
+          pingQueued = False,
+          lastPingTime = Nothing,
+          minPingTime = Nothing,
+          txRelay = Nothing,
+          relaysTxs = False,
+          addrRelay = False,
+          addrKnown = Set.empty,
+          addrsToSend = [],
+          getAddrSent = False,
+          getAddrRecvd = False,
+          addrTokens = 1,
+          addrTokensAt = s.openedAt,
+          nextAddrSend = 0,
+          nextLocalAddrSend = 0,
+          feeFilterSent = 0,
+          nextFeeFilter = 0,
+          privateTx = Nothing,
+          blocks =
+            BlockState
+              { preferredDownload = False,
+                bestKnownBlock = Nothing,
+                lastUnknownBlock = Nothing,
+                bestHeaderSent = Nothing,
+                syncStarted = False,
+                headersSyncTimeout = Just 0,
+                lastGetHeaders = Nothing,
+                lowWorkSync = Nothing,
+                invTriggeredGetHeaders = False,
+                stallingSince = Nothing,
+                inFlight = [],
+                downloadingSince = 0,
+                prefersHeaders = False,
+                sentSendHeaders = False,
+                providesCmpct = False,
+                requestedHbCmpct = False,
+                highBandwidthTo = False,
+                chainSync = ChainSync 0 Nothing False False,
+                lastBlockAnnouncement = Nothing,
+                forHeadersRelay = [],
+                forInvRelay = [],
+                continuationBlock = Nothing
+              }
+        }
+
+-- | The peer's @verack@ came: the handshake is complete
+-- (@fSuccessfullyConnected@).
+handshakeComplete :: State -> Bool
+handshakeComplete s = s.successfullyConnected
+
+-- | The peer's @version@ was accepted (@nVersion != 0@).
+versionReceived :: State -> Bool
+versionReceived s = isJust s.peerVersion
+
+-- | The node decided to close the connection (@fDisconnect@).
+isDisconnected :: State -> Bool
+isDisconnected s = s.disconnected
+
+-- | The peer misbehaved and the node has not acted on it yet
+-- (@m_should_discourage@), with the place that decided it.
+discouragementPending :: State -> Maybe Cite
+discouragementPending s = s.shouldDiscourage
+
+-- | The blocks requested from the peer and not received, oldest first.
+blocksInFlight :: State -> [BlockHash]
+blocksInFlight s = map (.block) s.blocks.inFlight
+
+-- | A ping waits for its pong: its nonce and when it was sent.
+pingOutstanding :: State -> Maybe (Word64, Micros)
+pingOutstanding s
+  | s.pingNonceSent == 0 = Nothing
+  | otherwise = Just (s.pingNonceSent, s.pingStart)
+
+-- | The node announces transactions to the peer: there is a t'TxRelay' and
+-- its @m_relay_txs@ is set.
+txRelayEnabled :: State -> Bool
+txRelayEnabled s = maybe False (.relayTxs) s.txRelay
+
+-- | The node relays addresses to the peer (@m_addr_relay_enabled@).
+addrRelayEnabled :: State -> Bool
+addrRelayEnabled s = s.addrRelay
diff --git a/src/Haskoin/Network/Protocol/Types.hs b/src/Haskoin/Network/Protocol/Types.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Network/Protocol/Types.hs
@@ -0,0 +1,683 @@
+{-# LANGUAGE DeriveAnyClass #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- |
+-- Module      : Haskoin.Network.Protocol.Types
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- The vocabulary shared by the protocol machines of
+-- "Haskoin.Network.Protocol.BitcoinCore" and
+-- "Haskoin.Network.Protocol.BitcoinCashNode".
+--
+-- A machine is a translation of how one reference node treats one peer. The
+-- node is the side being modelled, and the peer is the other end of the
+-- connection: usually the program that uses this library. The machine is a
+-- pure function from the state that the node keeps about the peer, the
+-- environment of the node and one 'Input', to the next state and the
+-- t'Effect's that the node produces. It opens no socket and reads no clock:
+-- the caller brings the time, the randomness and the answers about the chain
+-- and the mempool in an t'Env'.
+--
+-- Every t'Effect' carries a t'Cite': the place in the upstream source that
+-- produces it, and a short reason. A caller can check what the node would do
+-- and see where in the upstream code it is decided. The upstream versions that
+-- were read are named by t'Upstream'.
+--
+-- The design keeps three things apart:
+--
+-- * the t'Setup' of a connection, fixed when it opens: who opened it, the
+--   permissions of the peer, its address network;
+-- * the t'Env', the answers about the rest of the node that a decision needs,
+--   given again at each step because the chain and the mempool change between
+--   messages;
+-- * the state, private to each machine, which only the machine changes.
+--
+-- The alternatives were rejected for these reasons. A machine that ran in a
+-- monad over the node's own chain store would tie the library to one store.
+-- A machine that returned requests for the environment and waited for the
+-- answers would turn each message into a dialogue and make the tests long.
+-- A pure t'Env' of answers keeps each step one function call, and a test
+-- states the chain it assumes in one record.
+module Haskoin.Network.Protocol.Types
+  ( -- * Upstream code
+    Upstream (..),
+    Cite (..),
+    cite,
+
+    -- * Connections
+    ConnectionType (..),
+    isOutbound,
+    Permission (..),
+    Permissions,
+    TransportVersion (..),
+    Setup (..),
+
+    -- * Time
+    Micros,
+    seconds,
+    millis,
+
+    -- * Inputs
+    Input (..),
+    FrameError (..),
+    Notification (..),
+
+    -- * Outputs
+    Effect (..),
+    Action (..),
+    DisconnectReason (..),
+
+    -- * The environment
+    Env (..),
+    BlockInfo (..),
+    BlockStatus (..),
+    HeadersVerdict (..),
+    BlockVerdict (..),
+    TxVerdict (..),
+    defaultEnv,
+
+    -- * Randomness
+    Rng (..),
+    nextWord64,
+    randomBelow,
+    poissonDelay,
+
+    -- * Verdicts of compact blocks and double-spend proofs
+    CompactVerdict (..),
+    DsProofVerdict (..),
+  )
+where
+
+import Control.DeepSeq (NFData)
+import Data.Bits (shiftR, xor, (.&.))
+import Data.ByteString (ByteString)
+import Data.Int (Int64)
+import Data.Set (Set)
+import Data.Text (Text)
+import Data.Word (Word32, Word64, Word8)
+import GHC.Generics (Generic)
+import Haskoin.Block.Common (Block, BlockHash, BlockHeader, BlockHeight, BlockLocator)
+import Haskoin.Block.Merkle (MerkleBlock)
+import Haskoin.Crypto.Hash (Hash256)
+import Haskoin.Network.BlockFilter
+  ( CFCheckpt,
+    CFHeaders,
+    CFilter,
+    GetCFCheckpt,
+    GetCFHeaders,
+    GetCFilters,
+  )
+import Haskoin.Network.Bloom (BloomFilter)
+import Haskoin.Network.Common (AddressNetwork (..), NetworkAddressV2)
+import Haskoin.Network.CompactBlock (CompactBlock)
+import Haskoin.Network.Message (Message)
+import Haskoin.Transaction.Common (Tx, TxHash)
+
+-- | A release of a reference node whose source a machine translates.
+data Upstream = Upstream
+  { -- | name of the project, such as @Bitcoin Core@
+    project :: !Text,
+    -- | release, such as @32.1@
+    release :: !Text,
+    -- | Git tag of the release
+    tag :: !Text,
+    -- | commit that the tag names, whose source was read
+    commit :: !Text,
+    -- | where the source is published
+    repository :: !Text
+  }
+  deriving (Eq, Show, Read, Generic, NFData)
+
+-- | Where in the upstream source a decision is made, and why. The file is a
+-- path from the root of the repository of the t'Upstream' release, and the line
+-- is the line of that file at its commit.
+data Cite = Cite
+  { file :: !FilePath,
+    line :: !Int,
+    -- | the reason in a few words, often the string that the node logs
+    reason :: !Text
+  }
+  deriving (Eq, Ord, Show, Read, Generic, NFData)
+
+-- | Build a t'Cite'.
+cite :: FilePath -> Int -> Text -> Cite
+cite = Cite
+
+-- | Who opened a connection and why, as the node sees it
+-- (@ConnectionType@ in both nodes). A program that connects to a node is an
+-- 'Inbound' peer of that node. The node opens the other types itself.
+data ConnectionType
+  = -- | the peer connected to the node
+    Inbound
+  | -- | the node connected to relay blocks, transactions and addresses
+    OutboundFullRelay
+  | -- | the node connected because of @-addnode@ or @-connect@, or an RPC
+    Manual
+  | -- | a short connection to test that an address is reachable
+    Feeler
+  | -- | an outbound connection that relays blocks only
+    BlockRelayOnly
+  | -- | a short connection to ask for addresses (@-seednode@)
+    AddrFetch
+  | -- | Bitcoin Core only: a short connection to send one of the node's own
+    -- transactions privately
+    PrivateBroadcast
+  deriving (Eq, Ord, Show, Read, Enum, Bounded, Generic, NFData)
+
+-- | Whether the node opened the connection.
+isOutbound :: ConnectionType -> Bool
+isOutbound Inbound = False
+isOutbound _ = True
+
+-- | Permissions that the node grants a peer because of @-whitelist@ or
+-- @-whitebind@ (@NetPermissionFlags@). A peer that matches neither has none.
+-- The implications between them differ: on Bitcoin Core 'PermNoBan' brings
+-- 'PermDownload', and Bitcoin Cash Node has no 'PermDownload'. Each machine
+-- expands a set of permissions as its node does; see its documentation.
+data Permission
+  = -- | may load a Bloom filter even if the node does not offer them
+    PermBloomFilter
+  | -- | transactions are taken from it even in blocks-only mode
+    PermRelay
+  | -- | its transactions are relayed even when the node already has them
+    PermForceRelay
+  | -- | Bitcoin Core only: may download blocks during initial block download
+    -- and past the upload target
+    PermDownload
+  | -- | is never discouraged, banned or disconnected for misbehaviour
+    PermNoBan
+  | -- | may send a @mempool@ message
+    PermMempool
+  | -- | gets addresses without the address cache, and sends any number
+    PermAddr
+  | -- | the permissions come from a bare @-whitelist@ or @-whitebind@ with no
+    -- list of flags, so that options such as @-whitelistrelay@ apply
+    PermImplicit
+  deriving (Eq, Ord, Show, Read, Enum, Bounded, Generic, NFData)
+
+-- | A set of permissions.
+type Permissions = Set Permission
+
+-- | Transport of a connection. Bitcoin Core speaks the encrypted transport of
+-- BIP 324 when both sides offer it. Bitcoin Cash Node speaks the first one
+-- only. The machine sees messages, not bytes: the transport changes only how
+-- a framing error is handled.
+data TransportVersion
+  = -- | the original framing: magic, command, length and checksum
+    TransportV1
+  | -- | the encrypted transport of BIP 324
+    TransportV2
+  deriving (Eq, Ord, Show, Read, Enum, Bounded, Generic, NFData)
+
+-- | What the node knows about a connection when it opens.
+data Setup = Setup
+  { connectionType :: !ConnectionType,
+    -- | permissions as configured, before the machine expands them
+    permissions :: !Permissions,
+    -- | address network of the peer
+    peerNetwork :: !AddressNetwork,
+    -- | the peer's address is a local one, such as 127.0.0.1
+    peerIsLocal :: !Bool,
+    transport :: !TransportVersion,
+    -- | time when the connection opened
+    openedAt :: !Micros,
+    -- | seed of the randomness of the node for this connection
+    seed :: !Word64
+  }
+  deriving (Eq, Show, Read, Generic, NFData)
+
+-- | Time in microseconds since the Unix epoch, or a length of time in
+-- microseconds. Both nodes keep time in microseconds where it matters to the
+-- protocol, and in seconds elsewhere.
+type Micros = Int64
+
+-- | Microseconds in a number of seconds.
+seconds :: Int64 -> Micros
+seconds = (* 1000000)
+
+-- | Microseconds in a number of milliseconds.
+millis :: Int64 -> Micros
+millis = (* 1000)
+
+-- | Something that happens to a connection.
+data Input
+  = -- | a message from the peer, whole and with a good checksum
+    Receive !Message
+  | -- | bytes from the peer that are not a message the node accepts
+    BadFrame !FrameError
+  | -- | time has passed: the node runs its timers and its sending loop for this
+    -- peer (@SendMessages@), which both nodes run about every 100 ms
+    Tick
+  | -- | something happened in the rest of the node that this peer may hear of
+    Notify !Notification
+  deriving (Eq, Show, Generic)
+
+-- | Ways that bytes from a peer can fail to be a message.
+data FrameError
+  = -- | the header starts with the magic of another network
+    WrongMagic !Word32
+  | -- | the command is not printable ASCII padded with zeros
+    BadCommand !ByteString
+  | -- | the payload is larger than the node accepts for this command
+    Oversized !ByteString !Word32
+  | -- | the checksum does not match the payload
+    BadChecksum !ByteString
+  | -- | the command is known but its payload does not parse
+    BadPayload !ByteString
+  deriving (Eq, Show, Read, Generic, NFData)
+
+-- | News from the rest of the node.
+data Notification
+  = -- | the active chain has a new tip; the blocks are the new ones, oldest
+    -- first, so that the node can announce them
+    NewTip ![BlockHeader]
+  | -- | a transaction entered the mempool and may be announced
+    TxAccepted !Tx
+  | -- | an address that the node relays to some of its peers
+    RelayAddress !NetworkAddressV2
+  | -- | the node chose this peer for high-bandwidth compact blocks, or stopped
+    -- choosing it
+    HighBandwidth !Bool
+  | -- | the node wants this block from this peer
+    RequestBlock !BlockHash
+  | -- | the node wants this transaction from this peer
+    RequestTx !TxHash
+  | -- | an operator asked to disconnect the peer
+    OperatorDisconnect
+  | -- | the download of blocks waits on this peer: it holds the first block
+    -- of the download window and other peers have nothing left to fetch
+    -- (@m_stalling_since@ of Bitcoin Core, @nStallingSince@ of Bitcoin Cash
+    -- Node, set by another peer's download pass)
+    MarkStalling
+  | -- | an operator asked for a ping to this peer (RPC @ping@,
+    -- @m_ping_queued@ of Bitcoin Core, @fPingQueued@ of Bitcoin Cash Node)
+    PingRequested
+  | -- | a block passed its proof of work and merkle checks and extends the
+    -- tip, before full validation (@NewPoWValidBlock@), so that it can be
+    -- announced at once to high-bandwidth compact block peers
+    NewPoWValidBlock !BlockHeader
+  | -- | misbehaviour charged to this peer from outside its own messages, with
+    -- the score and the reason: an orphan transaction it sent turned out
+    -- invalid, an orphan double-spend proof it sent turned out invalid or
+    -- expired (@Misbehaving@ called from the rest of the node)
+    Penalty !Int !Text
+  | -- | a double-spend proof with this id was accepted for this transaction
+    -- and may be announced (@TransactionDoubleSpent@ of Bitcoin Cash Node)
+    NewDoubleSpendProof !Hash256 !Tx
+  | -- | the node chose this peer to make room: inbound eviction, an extra
+    -- outbound peer, or a tx-relaying inbound peer over the limit
+    Evict
+  deriving (Eq, Show, Generic)
+
+-- | Something that the node does, with the place in the source that does it.
+data Effect = Effect
+  { action :: !Action,
+    because :: !Cite
+  }
+  deriving (Eq, Show, Generic)
+
+-- | The things a node can do to a peer.
+data Action
+  = -- | send this message to the peer
+    Send !Message
+  | -- | drop the message without an answer, which is what the peer observes
+    Ignore
+  | -- | add to the ban score of the peer (Bitcoin Cash Node), and the reason
+    Misbehave !Int
+  | -- | mark the peer to be discouraged and disconnected (Bitcoin Core);
+    -- a discouraged address is the first to be evicted when inbound slots run
+    -- out, and the node does not connect to it again
+    Discourage
+  | -- | ban the address of the peer, for the given number of seconds
+    Ban !Int64
+  | -- | close the connection
+    Disconnect !DisconnectReason
+  | -- | hand a block, header or transaction to validation, or another effect
+    -- on the node outside this connection; the peer does not see it
+    Process !Text
+  deriving (Eq, Show, Generic)
+
+-- | Why the node closed a connection.
+data DisconnectReason
+  = -- | the peer broke a rule of the protocol
+    ProtocolViolation
+  | -- | the peer misbehaved and has no permission that protects it
+    Misbehaviour
+  | -- | a timer ran out
+    Timeout
+  | -- | the connection was short-lived by design: a feeler, an address fetch
+    Done
+  | -- | the peer lacks what this kind of connection needs
+    Unsuitable
+  | -- | the operator or the node's own resource limits
+    Resources
+  deriving (Eq, Ord, Show, Read, Enum, Bounded, Generic, NFData)
+
+-- | What the node knows about one block.
+data BlockInfo = BlockInfo
+  { hash :: !BlockHash,
+    height :: !BlockHeight,
+    status :: !BlockStatus,
+    -- | the block is on the active chain
+    inActiveChain :: !Bool,
+    -- | total work of the chain up to this block, @nChainWork@
+    work :: !Integer,
+    -- | time in the header, in seconds
+    time :: !Word32
+  }
+  deriving (Eq, Show, Read, Generic, NFData)
+
+-- | How far the node has got with a block it knows.
+data BlockStatus
+  = -- | the node has the header only
+    HeaderOnly
+  | -- | the node has the whole block
+    HaveData
+  | -- | the block or one of its ancestors is invalid
+    Invalid
+  deriving (Eq, Ord, Show, Read, Enum, Bounded, Generic, NFData)
+
+-- | What validation says of a @headers@ message.
+data HeadersVerdict
+  = -- | they connect and are valid; the last one is now known at this height
+    HeadersAccepted !BlockHeight
+  | -- | the first one does not connect to a header the node knows
+    HeadersUnconnected
+  | -- | they do not follow one another
+    HeadersNonContinuous
+  | -- | one is invalid, with the reason that validation gives
+    HeadersInvalid !Text
+  | -- | they connect but carry too little work to be kept
+    HeadersLowWork
+  | -- | a header fails its own proof of work (@CheckHeadersPoW@)
+    HeadersBadPoW
+  | -- | a header was already known to be invalid (@BLOCK_CACHED_INVALID@)
+    HeadersCachedInvalid
+  | -- | a header has a time too far in the future (@BLOCK_TIME_FUTURE@),
+    -- which may become valid later
+    HeadersTimeFuture
+  | -- | one is invalid, with the misbehaviour score and the reason that
+    -- validation gives (@CValidationState::IsInvalid(nDoS)@)
+    HeadersRejected !Int !Text
+  deriving (Eq, Show, Read, Generic, NFData)
+
+-- | What validation says of a @block@.
+data BlockVerdict
+  = BlockAccepted
+  | -- | the node already had it
+    BlockDuplicate
+  | -- | invalid by consensus; the flag is true when a peer can be blamed
+    -- for it, false for errors such as a mutated block
+    BlockInvalid !Bool !Text
+  | -- | does not connect to a known header
+    BlockMissingParent
+  | -- | its merkle root or witness commitment does not match its
+    -- transactions (@IsBlockMutated@), which may be the fault of the relay
+    -- and not of the block
+    BlockMutated
+  | -- | the block was already known to be invalid (@BLOCK_CACHED_INVALID@)
+    BlockCachedInvalid
+  | -- | invalid, with the reject code, the misbehaviour score and the reason
+    -- that validation gives
+    BlockRejected !Word8 !Int !Text
+  deriving (Eq, Show, Read, Generic, NFData)
+
+-- | What the mempool says of a @tx@.
+data TxVerdict
+  = TxAcceptedToMempool
+  | -- | already in the mempool or confirmed
+    TxAlreadyKnown
+  | -- | a parent is missing: an orphan
+    TxOrphan
+  | -- | refused by policy, not consensus
+    TxPolicyReject !Text
+  | -- | invalid by consensus
+    TxConsensusInvalid !Text
+  | -- | refused, with the reject code, the misbehaviour score and the reason
+    -- that @AcceptToMemoryPool@ gives
+    TxRejected !Word8 !Int !Text
+  deriving (Eq, Show, Read, Generic, NFData)
+
+-- | Answers about the rest of the node that a decision needs. The caller
+-- builds one before each step from its model of the node.
+data Env = Env
+  { -- | the current time
+    now :: !Micros,
+    -- | the tip of the active chain
+    tip :: !BlockInfo,
+    -- | the node is in initial block download
+    initialBlockDownload :: !Bool,
+    -- | a block the node knows, by its hash
+    lookupBlock :: BlockHash -> Maybe BlockInfo,
+    -- | the block of the active chain at a height
+    blockAtHeight :: BlockHeight -> Maybe BlockInfo,
+    -- | a block's header
+    headerOf :: BlockHash -> Maybe BlockHeader,
+    -- | a block's data, if the node has it and has not pruned it
+    blockData :: BlockHash -> Maybe Block,
+    -- | validation of a @headers@ message
+    checkHeaders :: [BlockHeader] -> HeadersVerdict,
+    -- | validation of a @block@ message
+    checkBlock :: Block -> BlockVerdict,
+    -- | the mempool's verdict on a @tx@ message
+    checkTx :: Tx -> TxVerdict,
+    -- | a transaction from the mempool, by txid or wtxid
+    mempoolTx :: TxHash -> Maybe Tx,
+    -- | every transaction in the mempool, for the @mempool@ message
+    mempoolTxs :: [Tx],
+    -- | minimum fee rate of the mempool, in satoshi per 1000 bytes
+    mempoolMinFee :: !Word64,
+    -- | the node is reindexing or importing blocks (@LoadingBlocks@)
+    loadingBlocks :: !Bool,
+    -- | the best header the node knows, which may be ahead of the tip
+    -- (@m_best_header@)
+    bestHeader :: !BlockInfo,
+    -- | a block locator that starts at a block (@GetLocator@)
+    locatorFrom :: BlockHash -> BlockLocator,
+    -- | the nonce is that of one of the node's own outbound connections
+    -- still in its handshake, so the peer is the node itself
+    -- (@CheckIncomingNonce@ fails)
+    ownNonce :: Word64 -> Bool,
+    -- | too many inbound peers relay transactions and none of the others
+    -- can be evicted (@EvictTxPeerIfFull@ fails)
+    txRelayInboundFull :: !Bool,
+    -- | @-maxuploadtarget@ is reached for any block
+    -- (@OutboundTargetReached(false)@)
+    uploadTargetReached :: !Bool,
+    -- | @-maxuploadtarget@ is reached for historical blocks
+    -- (@OutboundTargetReached(true)@)
+    historicalUploadTargetReached :: !Bool,
+    -- | number of other peers that a block is being downloaded from
+    inFlightElsewhere :: BlockHash -> Int,
+    -- | number of blocks in flight from all the other peers
+    -- (@mapBlocksInFlight@ less this peer)
+    otherBlocksInFlight :: !Int,
+    -- | number of other peers with blocks in flight
+    -- (@m_peers_downloading_from@ less this peer)
+    otherPeersDownloading :: !Int,
+    -- | number of other peers with headers sync started (@nSyncStarted@
+    -- less this peer)
+    otherSyncStarted :: !Int,
+    -- | number of other preferred download peers
+    -- (@m_num_preferred_download_peers@)
+    otherPreferredDownload :: !Int,
+    -- | number of other outbound peers protected from chain sync eviction
+    -- (@m_outbound_peers_with_protect_from_disconnect@)
+    otherProtectedOutbound :: !Int,
+    -- | the addresses that answer a @getaddr@; the flag asks for a fresh
+    -- answer instead of the cached one (@GetAddresses@)
+    addressesForPeer :: Bool -> [NetworkAddressV2],
+    -- | the address of the node that it advertises to this peer
+    -- (@GetLocalAddrForPeer@)
+    localAddress :: !(Maybe NetworkAddressV2),
+    -- | the transaction to send on a private broadcast connection
+    -- (@PickTxForSend@)
+    privateBroadcastTx :: !(Maybe Tx),
+    -- | a compact block for a block the node has (@CBlockHeaderAndShortTxIDs@)
+    compactBlockOf :: BlockHash -> Maybe CompactBlock,
+    -- | reconstruction of a compact block from the mempool
+    -- (@PartiallyDownloadedBlock::InitData@)
+    initCompact :: CompactBlock -> CompactVerdict,
+    -- | completion of a compact block with the transactions of a @blocktxn@
+    -- (@PartiallyDownloadedBlock::FillBlock@)
+    fillCompact :: CompactBlock -> [Tx] -> CompactVerdict,
+    -- | a filtered block for a Bloom filter: the @merkleblock@, the matching
+    -- transactions and the filter as the matches updated it
+    filteredBlock :: BloomFilter -> BlockHash -> Maybe (MerkleBlock, [Tx], BloomFilter),
+    -- | fee rate of a transaction of the mempool, in satoshi per 1000 bytes
+    txFeeRate :: TxHash -> Maybe Word64,
+    -- | the filters of a @getcfilters@, if the filter index has them
+    blockFilters :: GetCFilters -> Maybe [CFilter],
+    -- | the answer to a @getcfheaders@, if the filter index has it
+    blockFilterHeaders :: GetCFHeaders -> Maybe CFHeaders,
+    -- | the answer to a @getcfcheckpt@, if the filter index has it
+    blockFilterCheckpoint :: GetCFCheckpt -> Maybe CFCheckpt,
+    -- | how many other peers have blocks in flight with known headers,
+    -- @nPeersWithValidatedDownloads@ without this peer
+    otherValidatedDownloads :: !Int,
+    -- | the size limit of the next block, when it differs from the default
+    -- of the chain (ABLA, @GetNextBlockSizeLimit@)
+    nextBlockSizeLimit :: !(Maybe Word64),
+    -- | the node already has the transaction: mempool, orphan pool, recent
+    -- rejects or the coins of the tip (@AlreadyHave@ for @MSG_TX@)
+    knownTx :: TxHash -> Bool,
+    -- | the transaction is in the filter of recent rejects
+    recentlyRejected :: TxHash -> Bool,
+    -- | a transaction that the node announced to some peer in the last 15
+    -- minutes (@mapRelay@)
+    relayedTx :: TxHash -> Maybe Tx,
+    -- | when a transaction entered the mempool, in seconds
+    mempoolTime :: TxHash -> Maybe Int64,
+    -- | the node has this double-spend proof, or rejected it
+    knownDsProof :: Hash256 -> Bool,
+    -- | the payload of a stored double-spend proof, orphans included
+    dsProof :: Hash256 -> Maybe ByteString,
+    -- | validation of the payload of a @dsproof-beta@ message
+    checkDsProof :: ByteString -> DsProofVerdict,
+    -- | the most recent block that the node validated, @m_most_recent_block@
+    recentBlock :: !(Maybe Block)
+  }
+  deriving (Generic)
+
+-- | An environment of a node that has only the genesis block and an empty
+-- mempool, at the given time, to change with record updates.
+defaultEnv :: BlockInfo -> Block -> Micros -> Env
+defaultEnv genesis block t =
+  Env
+    { now = t,
+      tip = genesis,
+      initialBlockDownload = True,
+      lookupBlock = \h -> if h == genesis.hash then Just genesis else Nothing,
+      blockAtHeight = \n -> if n == 0 then Just genesis else Nothing,
+      headerOf = const Nothing,
+      blockData = \h -> if h == genesis.hash then Just block else Nothing,
+      checkHeaders = const HeadersUnconnected,
+      checkBlock = const BlockMissingParent,
+      checkTx = const TxOrphan,
+      mempoolTx = const Nothing,
+      mempoolTxs = [],
+      mempoolMinFee = 1000,
+      loadingBlocks = False,
+      bestHeader = genesis,
+      locatorFrom = \h -> [h],
+      ownNonce = const False,
+      txRelayInboundFull = False,
+      uploadTargetReached = False,
+      historicalUploadTargetReached = False,
+      inFlightElsewhere = const 0,
+      otherBlocksInFlight = 0,
+      otherPeersDownloading = 0,
+      otherSyncStarted = 0,
+      otherPreferredDownload = 0,
+      otherProtectedOutbound = 0,
+      addressesForPeer = const [],
+      localAddress = Nothing,
+      privateBroadcastTx = Nothing,
+      compactBlockOf = const Nothing,
+      initCompact = const CompactFailed,
+      fillCompact = \_ _ -> CompactInvalid,
+      filteredBlock = \_ _ -> Nothing,
+      txFeeRate = const Nothing,
+      blockFilters = const Nothing,
+      blockFilterHeaders = const Nothing,
+      blockFilterCheckpoint = const Nothing,
+      otherValidatedDownloads = 0,
+      nextBlockSizeLimit = Nothing,
+      knownTx = const False,
+      recentlyRejected = const False,
+      relayedTx = const Nothing,
+      mempoolTime = const Nothing,
+      knownDsProof = const False,
+      dsProof = const Nothing,
+      checkDsProof = const (DsProofInvalid "no validation"),
+      recentBlock = Nothing
+    }
+
+-- | What the mempool says of a double-spend proof
+-- (@DoubleSpendProof::validate@ and the checks before it).
+data DsProofVerdict
+  = -- | valid, and the first proof for its transaction: stored and announced
+    DsProofValid
+  | -- | the transaction that spends the outpoint already has a proof
+    DsProofDuplicate
+  | -- | the coin or the transaction that spends it is missing: kept as an
+    -- orphan proof
+    DsProofOrphan
+  | -- | invalid, or the payload does not parse, with the reason
+    DsProofInvalid !Text
+  deriving (Eq, Show, Read, Generic, NFData)
+
+-- | The randomness of a machine: a SplitMix64 generator, which is small and
+-- fast and good enough for timers and nonces. The upstream nodes use their own
+-- random sources, so the values never match theirs; the distributions do.
+newtype Rng = Rng Word64
+  deriving (Eq, Show, Read, Generic, NFData)
+
+-- | The next 64 random bits.
+nextWord64 :: Rng -> (Word64, Rng)
+nextWord64 (Rng s) =
+  let s' = s + 0x9e3779b97f4a7c15
+      z1 = (s' `xor` (s' `shiftR` 30)) * 0xbf58476d1ce4e5b9
+      z2 = (z1 `xor` (z1 `shiftR` 27)) * 0x94d049bb133111eb
+   in (z2 `xor` (z2 `shiftR` 31), Rng s')
+
+-- | A random number from zero to one less than the bound, which must be more
+-- than zero.
+randomBelow :: Word64 -> Rng -> (Word64, Rng)
+randomBelow n g =
+  let (w, g') = nextWord64 g
+   in (w `mod` n, g')
+
+-- | A delay drawn from an exponential distribution of the given mean, as
+-- @rand_exp_duration@ of Bitcoin Core and @PoissonNextSend@ of Bitcoin Cash
+-- Node, which both nodes use to time the announcements of transactions and
+-- addresses.
+poissonDelay :: Micros -> Rng -> (Micros, Rng)
+poissonDelay mean g =
+  let (w, g') = nextWord64 g
+      -- 48 bits of the word make a number in (0, 1], as upstream does.
+      u = (fromIntegral (w .&. 0xffffffffffff) + 1) / 281474976710656 :: Double
+   in (round (negate (log u) * fromIntegral mean), g')
+
+-- | What the node makes of a compact block when it tries to rebuild the
+-- block from its mempool (@ReadStatus@ of @PartiallyDownloadedBlock@).
+data CompactVerdict
+  = -- | the message is malformed (@READ_STATUS_INVALID@): the peer is at
+    -- fault
+    CompactInvalid
+  | -- | the rebuild failed in a way the peer cannot be blamed for, such as a
+    -- collision of short ids (@READ_STATUS_FAILED@)
+    CompactFailed
+  | -- | the block is whole
+    CompactComplete !Block
+  | -- | these positions of transactions are missing
+    CompactMissing ![Word32]
+  deriving (Eq, Show, Read, Generic, NFData)
diff --git a/src/Haskoin/Script.hs b/src/Haskoin/Script.hs
--- a/src/Haskoin/Script.hs
+++ b/src/Haskoin/Script.hs
@@ -8,14 +8,18 @@
 --
 -- This module provides functions for parsing and evaluating bitcoin
 -- transaction scripts. Data types are provided for building and
--- deconstructing all of the standard input and output script types.
+-- deconstructing all of the standard input and output script types, and for
+-- the token prefix that Bitcoin Cash puts before the script of an output that
+-- holds tokens.
 module Haskoin.Script
   ( module Common,
     module Standard,
     module SigHash,
+    module CashToken,
   )
 where
 
+import Haskoin.Script.CashToken as CashToken
 import Haskoin.Script.Common as Common
 import Haskoin.Script.SigHash as SigHash
 import Haskoin.Script.Standard as Standard
diff --git a/src/Haskoin/Script/CashToken.hs b/src/Haskoin/Script/CashToken.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Script/CashToken.hs
@@ -0,0 +1,367 @@
+{-# LANGUAGE DeriveAnyClass #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE NamedFieldPuns #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- |
+-- Module      : Haskoin.Script.CashToken
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- Tokens of Bitcoin Cash (CashTokens, CHIP-2022-02), as an output carries
+-- them.
+--
+-- Since May 2023 an output of Bitcoin Cash may hold tokens. They have no
+-- field of their own in the transaction: they are written at the front of
+-- the script field of the output, before the script that locks the coin.
+-- That is the token prefix:
+--
+-- @
+-- 0xef | category (32 bytes) | flags (1 byte)
+--      | [commitment length and commitment, if flag 0x40]
+--      | [fungible amount, if flag 0x10]
+--      | locking script
+-- @
+--
+-- The lengths and the amount are compact sizes, in their shortest form only.
+-- Of the flags, 0x80 is reserved and must be zero, 0x40 says there is a
+-- commitment, 0x20 that there is a non-fungible token, 0x10 that there is a
+-- fungible amount. The low four bits are the capability of the non-fungible
+-- token: 0 none, 1 mutable, 2 minting.
+--
+-- Software that does not know about the prefix sees a script that starts
+-- with an undefined opcode and matches no template, so a coin with tokens
+-- seems to have no address. 'splitTokenData' takes the prefix off and reads
+-- it, so that the rest can be decoded as any other script.
+-- 'Haskoin.Address.scriptToAddressBS' does that on the Bitcoin Cash
+-- networks.
+--
+-- The byte 0xef is only a prefix on Bitcoin Cash. On Bitcoin it is an
+-- undefined opcode like any other, and nothing in this module should be
+-- applied to a script of that chain.
+--
+-- t'TokenData' is the decoded prefix, in a form that cannot be written in two
+-- ways: an empty commitment and an amount of zero are what an absent
+-- commitment and an absent amount mean, because the prefix may not encode a
+-- commitment of length zero nor an amount of zero. So 'encodeTokenPrefix'
+-- and 'splitTokenData' are inverses, and two equal values have the same
+-- bytes.
+--
+-- What is not checked here: the rules that depend on the transaction, such
+-- as the category being the id of an input being spent, or the amounts of
+-- the inputs and the outputs adding up, and the limit on the length of a
+-- commitment. That limit is a rule of transaction validation, not of the
+-- prefix, and it has changed between network upgrades, so a commitment of
+-- any length parses.
+module Haskoin.Script.CashToken
+  ( -- * Tokens
+    TokenData (..),
+    NFToken (..),
+    TokenCapability (..),
+    validTokenData,
+    maxTokenAmount,
+
+    -- * Token prefix
+    tokenPrefixByte,
+    hasTokenPrefix,
+    splitTokenData,
+    encodeTokenPrefix,
+  )
+where
+
+import Control.DeepSeq (NFData)
+import Control.Monad (unless, when)
+import Data.Aeson
+  ( FromJSON (parseJSON),
+    ToJSON (toEncoding, toJSON),
+    Value (Number, String),
+    object,
+    pairs,
+    withObject,
+    withText,
+    (.:),
+    (.:?),
+    (.=),
+  )
+import Data.Aeson.Types (Parser)
+import Data.Binary (Binary (..))
+import Data.Bits ((.&.), (.|.))
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as B
+import Data.Bytes.Get (MonadGet (getByteString, getWord8, remaining))
+import Data.Bytes.Put (MonadPut (putByteString, putWord8), runPutS)
+import Data.Bytes.Serial (Serial (..))
+import Data.Char (isDigit, ord)
+import Data.Hashable (Hashable)
+import Data.Maybe (isJust)
+import Data.Scientific (toBoundedInteger)
+import Data.Serialize (Serialize (..))
+import Data.Serialize qualified as S
+import Data.Text qualified as T
+import Data.Word (Word64, Word8)
+import GHC.Generics (Generic)
+import Haskoin.Network.Common (VarInt (VarInt), putVarInt)
+import Haskoin.Transaction.Common (TxHash, txHashToHex)
+import Haskoin.Util.Helpers (decodeHex, encodeHex)
+
+-- | What a non-fungible token allows its holder to do, besides spending it.
+data TokenCapability
+  = -- | An immutable token: its commitment can never change.
+    NoCapability
+  | -- | The holder can replace the commitment, in one new token.
+    MutableCapability
+  | -- | The holder can create any number of new tokens of the category.
+    MintingCapability
+  deriving (Eq, Ord, Show, Read, Enum, Bounded, Generic, Hashable, NFData)
+
+-- | The non-fungible token of an output. An output holds at most one.
+data NFToken = NFToken
+  { capability :: !TokenCapability,
+    -- | Data the token commits to. Empty when there is none.
+    commitment :: !ByteString
+  }
+  deriving (Eq, Ord, Show, Read, Generic, Hashable, NFData)
+
+-- | The tokens that one output holds: all of one category, a fungible
+-- amount, a non-fungible token, or both.
+--
+-- A value is only valid with at least one token and an amount no larger than
+-- 'maxTokenAmount'. The type does not enforce it, so that a record can be
+-- built and taken apart freely. 'validTokenData' checks it, and the JSON
+-- parser, 'splitTokenData' and 'encodeTokenPrefix' only accept or give
+-- valid values.
+data TokenData = TokenData
+  { -- | The category, the id of the transaction whose first input created
+    -- it. It is shown in reverse byte order, as a transaction id.
+    category :: !TxHash,
+    -- | Fungible tokens. Zero when there are none.
+    amount :: !Word64,
+    -- | Non-fungible token, if any.
+    nft :: !(Maybe NFToken)
+  }
+  deriving (Eq, Ord, Show, Read, Generic, Hashable, NFData)
+
+-- | The largest fungible amount an output can hold, the largest signed
+-- 64-bit integer. It is also the largest supply a category can have.
+maxTokenAmount :: Word64
+maxTokenAmount = 0x7fffffffffffffff
+
+-- | A t'TokenData' holds at least one token, and no more than
+-- 'maxTokenAmount' fungible ones.
+validTokenData :: TokenData -> Bool
+validTokenData t =
+  t.amount <= maxTokenAmount && (t.amount > 0 || isJust t.nft)
+
+-- | The first byte of the script field of an output that holds tokens,
+-- @PREFIX_TOKEN@ in the specification.
+tokenPrefixByte :: Word8
+tokenPrefixByte = 0xef
+
+-- | The script field starts with 'tokenPrefixByte'. It says nothing about
+-- the rest being a valid prefix: 'splitTokenData' does.
+hasTokenPrefix :: ByteString -> Bool
+hasTokenPrefix bytes = case B.uncons bytes of
+  Just (b, _) -> b == tokenPrefixByte
+  Nothing -> False
+
+-- | Split the script field of an output of Bitcoin Cash into the tokens it
+-- holds and the locking script after them. A field that does not start with
+-- 'tokenPrefixByte' holds no tokens and is all locking script. A field that
+-- starts with it and has no valid prefix after it is an error: consensus
+-- does not let such an output into the chain.
+--
+-- The locking script is returned as bytes, not parsed, since it may be any
+-- bytes at all, and so it can go to
+-- 'Haskoin.Address.scriptToAddressBS' or 'Haskoin.Util.Marshal.decodeSerial'.
+splitTokenData :: ByteString -> Either String (Maybe TokenData, ByteString)
+splitTokenData bytes
+  | hasTokenPrefix bytes = do
+      (t, rest) <- S.runGetState deserialize bytes 0
+      return (Just t, rest)
+  | otherwise = Right (Nothing, bytes)
+
+-- | The token prefix of an output that holds these tokens, 'tokenPrefixByte'
+-- included. Put the locking script after it to get the script field of the
+-- output. 'Nothing' for a value that 'validTokenData' refuses, since it has
+-- no valid prefix.
+encodeTokenPrefix :: TokenData -> Maybe ByteString
+encodeTokenPrefix t
+  | validTokenData t = Just (runPutS (serialize t))
+  | otherwise = Nothing
+
+-- | Flag bits of the prefix.
+reservedBit, commitmentBit, nftBit, amountBit :: Word8
+reservedBit = 0x80
+commitmentBit = 0x40
+nftBit = 0x20
+amountBit = 0x10
+
+-- | The binary form is the token prefix, 'tokenPrefixByte' included, as it
+-- is on the wire. Writing a value that 'validTokenData' refuses gives bytes
+-- that do not read back: use 'encodeTokenPrefix' to be told.
+instance Serial TokenData where
+  serialize t = do
+    putWord8 tokenPrefixByte
+    serialize t.category
+    putWord8 flags
+    unless (B.null commitment) $ do
+      putVarInt (B.length commitment)
+      putByteString commitment
+    when (t.amount > 0) $ putVarInt t.amount
+    where
+      commitment = maybe B.empty (.commitment) t.nft
+      flags =
+        bit (not (B.null commitment)) commitmentBit
+          .|. bit (isJust t.nft) nftBit
+          .|. bit (t.amount > 0) amountBit
+          .|. maybe 0 (fromIntegral . fromEnum . (.capability)) t.nft
+      bit c b = if c then b else 0
+
+  deserialize = do
+    b <- getWord8
+    unless (b == tokenPrefixByte) $ invalid "does not start with 0xef"
+    category <- deserialize
+    flags <- getWord8
+    let hasCommitment = flags .&. commitmentBit /= 0
+        hasNft = flags .&. nftBit /= 0
+        hasAmount = flags .&. amountBit /= 0
+        cap = flags .&. 0x0f
+    when (flags .&. reservedBit /= 0) $ invalid "reserved bit is set"
+    unless (hasNft || hasAmount) $ invalid "must encode at least one token"
+    when (cap > 2) $ invalid "capability must be none, mutable or minting"
+    when (not hasNft && cap /= 0) $ invalid "capability requires an NFT"
+    when (not hasNft && hasCommitment) $ invalid "commitment requires an NFT"
+    commitment <-
+      if hasCommitment
+        then do
+          VarInt n <- deserialize
+          when (n == 0) $ invalid "commitment length must be greater than 0"
+          left <- remaining
+          when (n > fromIntegral left) $ invalid "commitment is too short"
+          getByteString (fromIntegral n)
+        else return B.empty
+    amount <-
+      if hasAmount
+        then do
+          VarInt n <- deserialize
+          when (n == 0) $ invalid "amount must be greater than 0"
+          when (n > maxTokenAmount) $ invalid "amount is too large"
+          return n
+        else return 0
+    let nft
+          | hasNft = Just NFToken {capability = toEnum (fromIntegral cap), commitment}
+          | otherwise = Nothing
+    return TokenData {category, amount, nft}
+    where
+      invalid msg = fail ("Invalid token prefix: " <> msg)
+
+instance Serialize TokenData where
+  put = serialize
+  get = deserialize
+
+instance Binary TokenData where
+  put = serialize
+  get = deserialize
+
+-- | The names of the CashTokens specification and of the RPC of Bitcoin Cash
+-- Node: @none@, @mutable@, @minting@.
+instance ToJSON TokenCapability where
+  toJSON = String . capabilityName
+
+instance FromJSON TokenCapability where
+  parseJSON = withText "capability" $ \case
+    "none" -> return NoCapability
+    "mutable" -> return MutableCapability
+    "minting" -> return MintingCapability
+    t -> fail ("Unknown token capability: " <> T.unpack t)
+
+capabilityName :: TokenCapability -> T.Text
+capabilityName = \case
+  NoCapability -> "none"
+  MutableCapability -> "mutable"
+  MintingCapability -> "minting"
+
+-- | @{"capability": "none", "commitment": "<hex>"}@.
+instance ToJSON NFToken where
+  toJSON n =
+    object ["capability" .= n.capability, "commitment" .= encodeHex n.commitment]
+  toEncoding n =
+    pairs ("capability" .= n.capability <> "commitment" .= encodeHex n.commitment)
+
+instance FromJSON NFToken where
+  parseJSON = withObject "nft" $ \o -> do
+    capability <- o .: "capability"
+    hex <- o .: "commitment"
+    commitment <- maybe (fail "Commitment is not hex") return (decodeHex hex)
+    return NFToken {capability, commitment}
+
+-- | The form of the CashTokens test vectors and of the RPC of Bitcoin Cash
+-- Node:
+--
+-- @
+-- {"category": "<txid>", "amount": "1000", "nft": {...}}
+-- @
+--
+-- The amount is a string, since it may be larger than a JavaScript number
+-- can hold exactly. @nft@ is absent when there is no non-fungible token. The
+-- parser refuses a value that 'validTokenData' refuses.
+--
+-- The parser reads an amount strictly, so that two programs reading the same
+-- JSON cannot disagree on it. A string must be decimal digits only, with no
+-- sign, space or leading zero, as the test vectors and Bitcoin Cash Node
+-- write it. 'read' would also take @0x10@, @(16)@ or @ 16@. A number must be
+-- a whole number in range. Its exponent is checked before the number is
+-- built, so a short text such as @1e100000000@ is refused at once, where
+-- building it would take seconds and hundreds of megabytes.
+instance ToJSON TokenData where
+  toJSON t =
+    object $
+      [ "category" .= txHashToHex t.category,
+        "amount" .= show t.amount
+      ]
+        <> maybe [] (\n -> ["nft" .= n]) t.nft
+  toEncoding t =
+    pairs $
+      "category" .= txHashToHex t.category
+        <> "amount" .= show t.amount
+        <> maybe mempty ("nft" .=) t.nft
+
+instance FromJSON TokenData where
+  parseJSON = withObject "token data" $ \o -> do
+    category <- o .: "category"
+    amount <- parseAmount =<< o .: "amount"
+    nft <- o .:? "nft"
+    let t = TokenData {category, amount, nft}
+    unless (validTokenData t) $ fail "Invalid token data"
+    return t
+    where
+      parseAmount :: Value -> Parser Word64
+      parseAmount = \case
+        String s
+          | decimal s -> inRange (T.foldl' digit 0 s)
+          | otherwise -> fail "Token amount is not a string of decimal digits"
+        Number n
+          | Just i <- toBoundedInteger n -> inRange i
+          | otherwise -> fail "Token amount is not an integer in range"
+        _ -> fail "Token amount is not a string or a number"
+      -- At most 19 digits, which always fit in a 'Word64'. The largest
+      -- amount has 19.
+      decimal s =
+        not (T.null s)
+          && T.length s <= 19
+          && T.all isDigit s
+          && (s == "0" || T.head s /= '0')
+      digit acc c = acc * 10 + fromIntegral (ord c - ord '0')
+      inRange :: Word64 -> Parser Word64
+      inRange n
+        | n > maxTokenAmount = fail "Token amount out of range"
+        | otherwise = return n
diff --git a/src/Haskoin/Script/Common.hs b/src/Haskoin/Script/Common.hs
--- a/src/Haskoin/Script/Common.hs
+++ b/src/Haskoin/Script/Common.hs
@@ -3,6 +3,7 @@
 {-# LANGUAGE DerivingStrategies #-}
 {-# LANGUAGE DuplicateRecordFields #-}
 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE OverloadedRecordDot #-}
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE PatternSynonyms #-}
 {-# LANGUAGE NoFieldSelectors #-}
@@ -20,6 +21,18 @@
   ( -- * Scripts
     ScriptOp (..),
     pattern OP_CHECKSIGADD,
+    pattern OP_BEGIN,
+    pattern OP_UNTIL,
+    pattern OP_SPLIT,
+    pattern OP_NUM2BIN,
+    pattern OP_BIN2NUM,
+    pattern OP_DEFINE,
+    pattern OP_INVOKE,
+    pattern OP_LSHIFTNUM,
+    pattern OP_RSHIFTNUM,
+    pattern OP_LSHIFTBIN,
+    pattern OP_RSHIFTBIN,
+    opName,
     Script (..),
     PushDataType (..),
     isPushOp,
@@ -43,10 +56,13 @@
 import Data.Bytes.Put
 import Data.Bytes.Serial
 import Data.Hashable
-import Data.Maybe (isJust)
+import Data.Maybe (fromMaybe, isJust)
 import Data.Serialize (Serialize (..))
+import Data.Text (Text)
+import qualified Data.Text as T
 import Data.Word (Word8)
 import GHC.Generics (Generic)
+import Haskoin.Network.Data (Network (..))
 import Haskoin.Util (hexBuilder)
 import Haskoin.Util.Helpers (decodeHex, encodeHex, hexEncoding)
 
@@ -111,6 +127,28 @@
 
 -- | Data type representing an operator allowed inside a 'Script'.
 --
+-- One type serves both chains, with one constructor for each byte. Bitcoin
+-- and Bitcoin Cash split a script into opcodes in the same way: the same
+-- bytes, the same pushes, the same lengths. They differ in the names of
+-- twelve bytes and in what some bytes do when a script runs, which matters
+-- to an interpreter and not to a parser. So a script parses and serializes
+-- without a network, and the chains share every type built on it:
+-- addresses, PSBTs, signature hashes.
+--
+-- * The constructors of those twelve bytes carry the Bitcoin name, but for
+--   0xba, which carries the Bitcoin Cash name 'OP_CHECKDATASIG'. Each has a
+--   pattern synonym for the name of the other chain, such as 'OP_SPLIT' for
+--   'OP_SUBSTR' and 'OP_CHECKSIGADD' for 'OP_CHECKDATASIG': both names build
+--   and match the same value.
+-- * The opcodes that only Bitcoin Cash defines, from 0xbb to 0xd5, have
+--   constructors of their own: their bytes have no name on Bitcoin.
+-- * 'opName' gives the name that the reference node of a network prints.
+--
+-- Separate types for each chain were rejected: they would add a network to
+-- every parse of a script, for names alone. Which opcodes a chain enables, at
+-- which height, and the bytes that make a Tapscript succeed at once belong to
+-- an interpreter, which this library does not have.
+--
 -- An 'OP_PUSHDATA' must carry a payload that fits its 'PushDataType': at most
 -- 75 bytes for 'OPCODE', 255 for 'OPDATA1', 65535 for 'OPDATA2'. Serializing
 -- a push that breaks this invariant fails with an 'error' call, because no
@@ -250,6 +288,31 @@
   | OP_CHECKDATASIGVERIFY
   | -- Bitcoin Cash May 2020 hard fork
     OP_REVERSEBYTES
+  | -- Bitcoin Cash May 2022 hard fork: native introspection, 0xc0 to 0xcd
+    OP_INPUTINDEX
+  | OP_ACTIVEBYTECODE
+  | OP_TXVERSION
+  | OP_TXINPUTCOUNT
+  | OP_TXOUTPUTCOUNT
+  | OP_TXLOCKTIME
+  | OP_UTXOVALUE
+  | OP_UTXOBYTECODE
+  | OP_OUTPOINTTXHASH
+  | OP_OUTPOINTINDEX
+  | OP_INPUTBYTECODE
+  | OP_INPUTSEQUENCENUMBER
+  | OP_OUTPUTVALUE
+  | OP_OUTPUTBYTECODE
+  | -- Bitcoin Cash May 2023 hard fork: introspection of tokens, 0xce to 0xd3
+    OP_UTXOTOKENCATEGORY
+  | OP_UTXOTOKENCOMMITMENT
+  | OP_UTXOTOKENAMOUNT
+  | OP_OUTPUTTOKENCATEGORY
+  | OP_OUTPUTTOKENCOMMITMENT
+  | OP_OUTPUTTOKENAMOUNT
+  | -- Reserved by Bitcoin Cash Node, 0xd4 and 0xd5
+    OP_RESERVED3
+  | OP_RESERVED4
   | -- Other
     OP_PUBKEYHASH
   | OP_PUBKEY
@@ -263,6 +326,131 @@
 pattern OP_CHECKSIGADD :: ScriptOp
 pattern OP_CHECKSIGADD = OP_CHECKDATASIG
 
+-- | Opcode 0x65 as Bitcoin Cash names it: starts a loop (May 2026). It is
+-- 'OP_VERIF' of Bitcoin, the same value.
+pattern OP_BEGIN :: ScriptOp
+pattern OP_BEGIN = OP_VERIF
+
+-- | Opcode 0x66 as Bitcoin Cash names it: ends a loop (May 2026). It is
+-- 'OP_VERNOTIF' of Bitcoin, the same value.
+pattern OP_UNTIL :: ScriptOp
+pattern OP_UNTIL = OP_VERNOTIF
+
+-- | Opcode 0x7f as Bitcoin Cash names it: splits a byte string in two (May 2018). It is
+-- 'OP_SUBSTR' of Bitcoin, the same value.
+pattern OP_SPLIT :: ScriptOp
+pattern OP_SPLIT = OP_SUBSTR
+
+-- | Opcode 0x80 as Bitcoin Cash names it: pads a number to a size (May 2018). It is
+-- 'OP_LEFT' of Bitcoin, the same value.
+pattern OP_NUM2BIN :: ScriptOp
+pattern OP_NUM2BIN = OP_LEFT
+
+-- | Opcode 0x81 as Bitcoin Cash names it: reads a byte string as a minimal number (May 2018). It is
+-- 'OP_RIGHT' of Bitcoin, the same value.
+pattern OP_BIN2NUM :: ScriptOp
+pattern OP_BIN2NUM = OP_RIGHT
+
+-- | Opcode 0x89 as Bitcoin Cash names it: defines a function (May 2026). It is
+-- 'OP_RESERVED1' of Bitcoin, the same value.
+pattern OP_DEFINE :: ScriptOp
+pattern OP_DEFINE = OP_RESERVED1
+
+-- | Opcode 0x8a as Bitcoin Cash names it: calls a function (May 2026). It is
+-- 'OP_RESERVED2' of Bitcoin, the same value.
+pattern OP_INVOKE :: ScriptOp
+pattern OP_INVOKE = OP_RESERVED2
+
+-- | Opcode 0x8d as Bitcoin Cash names it: shifts a number left (May 2026). It is
+-- 'OP_2MUL' of Bitcoin, the same value.
+pattern OP_LSHIFTNUM :: ScriptOp
+pattern OP_LSHIFTNUM = OP_2MUL
+
+-- | Opcode 0x8e as Bitcoin Cash names it: shifts a number right (May 2026). It is
+-- 'OP_2DIV' of Bitcoin, the same value.
+pattern OP_RSHIFTNUM :: ScriptOp
+pattern OP_RSHIFTNUM = OP_2DIV
+
+-- | Opcode 0x98 as Bitcoin Cash names it: shifts a byte string left (May 2026). It is
+-- 'OP_LSHIFT' of Bitcoin, the same value.
+pattern OP_LSHIFTBIN :: ScriptOp
+pattern OP_LSHIFTBIN = OP_LSHIFT
+
+-- | Opcode 0x99 as Bitcoin Cash names it: shifts a byte string right (May 2026). It is
+-- 'OP_RSHIFT' of Bitcoin, the same value.
+pattern OP_RSHIFTBIN :: ScriptOp
+pattern OP_RSHIFTBIN = OP_RSHIFT
+
+-- | The name that the reference node of a network gives an opcode, as its
+-- @GetOpName@ does in @src\/script\/script.cpp@: Bitcoin Core 32.1 on the
+-- Bitcoin networks, Bitcoin Cash Node 29.2.0 on the Bitcoin Cash networks. A
+-- network and its testnets share their names. These are the names that the
+-- @asm@ of a decoded script shows in the RPC of each node, so a program that
+-- prints scripts for one chain prints them as that chain does.
+--
+-- The twelve bytes that the chains name differently get the name of the
+-- chain: 0x7f is @OP_SUBSTR@ on Bitcoin and @OP_SPLIT@ on Bitcoin Cash, and
+-- 0xba is @OP_CHECKSIGADD@ on Bitcoin and @OP_CHECKDATASIG@ on Bitcoin Cash.
+-- A byte that the node does not name is @OP_UNKNOWN@: on Bitcoin, the
+-- opcodes that only Bitcoin Cash defines, and on both chains a direct push
+-- of 1 to 75 bytes and the template bytes 'OP_PUBKEYHASH' and 'OP_PUBKEY'.
+-- As upstream does, 'OP_0', 'OP_1NEGATE' and 'OP_1' to 'OP_16' are named by
+-- their numbers, @0@, @-1@ and @1@ to @16@; 0xff is @OP_INVALIDOPCODE@ on
+-- Bitcoin, and 0xef, the prefix of tokens, is @SPECIAL_TOKEN_PREFIX@ on
+-- Bitcoin Cash.
+--
+-- 'Show' cannot depend on the network, so it prints the name of the
+-- constructor, which is the Bitcoin name for the twelve bytes but 0xba. Use
+-- this function to show an opcode to a user.
+opName :: Network -> ScriptOp -> Text
+opName net op = case op of
+  OP_PUSHDATA _ OPCODE -> "OP_UNKNOWN"
+  OP_PUSHDATA _ OPDATA1 -> "OP_PUSHDATA1"
+  OP_PUSHDATA _ OPDATA2 -> "OP_PUSHDATA2"
+  OP_PUSHDATA _ OPDATA4 -> "OP_PUSHDATA4"
+  OP_0 -> "0"
+  OP_1NEGATE -> "-1"
+  OP_PUBKEYHASH -> "OP_UNKNOWN"
+  OP_PUBKEY -> "OP_UNKNOWN"
+  OP_INVALIDOPCODE b -> invalid b
+  _
+    | Right n <- scriptOpToInt op -> T.pack (show n)
+    | bitcoinCash -> fromMaybe (T.pack (show op)) (lookup op bitcoinCashNames)
+    | op == OP_CHECKDATASIG -> "OP_CHECKSIGADD"
+    | bitcoinCashOnly -> "OP_UNKNOWN"
+    | otherwise -> T.pack (show op)
+  where
+    bitcoinCash = isJust net.sigHashForkId
+    bitcoinCashNames =
+      [ (OP_BEGIN, "OP_BEGIN"),
+        (OP_UNTIL, "OP_UNTIL"),
+        (OP_SPLIT, "OP_SPLIT"),
+        (OP_NUM2BIN, "OP_NUM2BIN"),
+        (OP_BIN2NUM, "OP_BIN2NUM"),
+        (OP_DEFINE, "OP_DEFINE"),
+        (OP_INVOKE, "OP_INVOKE"),
+        (OP_LSHIFTNUM, "OP_LSHIFTNUM"),
+        (OP_RSHIFTNUM, "OP_RSHIFTNUM"),
+        (OP_LSHIFTBIN, "OP_LSHIFTBIN"),
+        (OP_RSHIFTBIN, "OP_RSHIFTBIN")
+      ]
+    -- The opcodes from 0xbb on, which Bitcoin Core does not define.
+    bitcoinCashOnly = B.head (runPutS (serialize op)) >= 0xbb
+    -- A byte without a constructor. One built by hand for a byte that has
+    -- a constructor is named as that constructor.
+    invalid b
+      | b == 0x00 = "0"
+      | b <= 0x4b = "OP_UNKNOWN"
+      | b == 0x4c = "OP_PUSHDATA1"
+      | b == 0x4d = "OP_PUSHDATA2"
+      | b == 0x4e = "OP_PUSHDATA4"
+      | b == 0xff, not bitcoinCash = "OP_INVALIDOPCODE"
+      | b == 0xef, bitcoinCash = "SPECIAL_TOKEN_PREFIX"
+      | Right named <- runGetS deserialize (B.singleton b),
+        named /= OP_INVALIDOPCODE b =
+          opName net named
+      | otherwise = "OP_UNKNOWN"
+
 instance Serial ScriptOp where
   {-# INLINEABLE serialize #-}
   {-# INLINEABLE deserialize #-}
@@ -404,6 +592,29 @@
         | op == 0xbb = return OP_CHECKDATASIGVERIFY
         -- Bitcoin Cash May 2020 hard fork
         | op == 0xbc = return OP_REVERSEBYTES
+        -- Bitcoin Cash May 2022 and May 2023 hard forks
+        | op == 0xc0 = return OP_INPUTINDEX
+        | op == 0xc1 = return OP_ACTIVEBYTECODE
+        | op == 0xc2 = return OP_TXVERSION
+        | op == 0xc3 = return OP_TXINPUTCOUNT
+        | op == 0xc4 = return OP_TXOUTPUTCOUNT
+        | op == 0xc5 = return OP_TXLOCKTIME
+        | op == 0xc6 = return OP_UTXOVALUE
+        | op == 0xc7 = return OP_UTXOBYTECODE
+        | op == 0xc8 = return OP_OUTPOINTTXHASH
+        | op == 0xc9 = return OP_OUTPOINTINDEX
+        | op == 0xca = return OP_INPUTBYTECODE
+        | op == 0xcb = return OP_INPUTSEQUENCENUMBER
+        | op == 0xcc = return OP_OUTPUTVALUE
+        | op == 0xcd = return OP_OUTPUTBYTECODE
+        | op == 0xce = return OP_UTXOTOKENCATEGORY
+        | op == 0xcf = return OP_UTXOTOKENCOMMITMENT
+        | op == 0xd0 = return OP_UTXOTOKENAMOUNT
+        | op == 0xd1 = return OP_OUTPUTTOKENCATEGORY
+        | op == 0xd2 = return OP_OUTPUTTOKENCOMMITMENT
+        | op == 0xd3 = return OP_OUTPUTTOKENAMOUNT
+        | op == 0xd4 = return OP_RESERVED3
+        | op == 0xd5 = return OP_RESERVED4
         -- Constants
         | op == 0xfd = return OP_PUBKEYHASH
         | op == 0xfe = return OP_PUBKEY
@@ -560,6 +771,29 @@
     OP_CHECKDATASIGVERIFY -> putWord8 0xbb
     -- Bitcoin Cash May 2020 hard fork
     OP_REVERSEBYTES -> putWord8 0xbc
+    -- Bitcoin Cash May 2022 and May 2023 hard forks
+    OP_INPUTINDEX -> putWord8 0xc0
+    OP_ACTIVEBYTECODE -> putWord8 0xc1
+    OP_TXVERSION -> putWord8 0xc2
+    OP_TXINPUTCOUNT -> putWord8 0xc3
+    OP_TXOUTPUTCOUNT -> putWord8 0xc4
+    OP_TXLOCKTIME -> putWord8 0xc5
+    OP_UTXOVALUE -> putWord8 0xc6
+    OP_UTXOBYTECODE -> putWord8 0xc7
+    OP_OUTPOINTTXHASH -> putWord8 0xc8
+    OP_OUTPOINTINDEX -> putWord8 0xc9
+    OP_INPUTBYTECODE -> putWord8 0xca
+    OP_INPUTSEQUENCENUMBER -> putWord8 0xcb
+    OP_OUTPUTVALUE -> putWord8 0xcc
+    OP_OUTPUTBYTECODE -> putWord8 0xcd
+    OP_UTXOTOKENCATEGORY -> putWord8 0xce
+    OP_UTXOTOKENCOMMITMENT -> putWord8 0xcf
+    OP_UTXOTOKENAMOUNT -> putWord8 0xd0
+    OP_OUTPUTTOKENCATEGORY -> putWord8 0xd1
+    OP_OUTPUTTOKENCOMMITMENT -> putWord8 0xd2
+    OP_OUTPUTTOKENAMOUNT -> putWord8 0xd3
+    OP_RESERVED3 -> putWord8 0xd4
+    OP_RESERVED4 -> putWord8 0xd5
 
 instance Binary ScriptOp where
   put = serialize
diff --git a/src/Haskoin/Script/SigHash.hs b/src/Haskoin/Script/SigHash.hs
--- a/src/Haskoin/Script/SigHash.hs
+++ b/src/Haskoin/Script/SigHash.hs
@@ -42,6 +42,14 @@
     txSigHash,
     txSigHashForkId,
     txSigHashCashToken,
+
+    -- * Digests of every input of a transaction
+    TxSigHashes,
+    txSigHashes,
+    sigHashesTx,
+    txSigHashWith,
+    txSigHashForkIdWith,
+    txSigHashCashTokenWith,
     splitTokenPrefix,
     TxSignature (..),
     decodeTxSig,
@@ -63,12 +71,15 @@
 import Data.Hashable
 import Data.Maybe
 import Data.Scientific
+import Data.Vector (Vector)
+import Data.Vector qualified as V
 import Data.Word
 import GHC.Generics (Generic)
 import Haskoin.Crypto.Hash
 import Haskoin.Crypto.Signature
 import Haskoin.Network.Common
 import Haskoin.Network.Data
+import Haskoin.Script.CashToken (splitTokenData)
 import Haskoin.Script.Common
 import Haskoin.Transaction.Common
 import Haskoin.Util
@@ -269,6 +280,10 @@
 -- accepts.
 --
 -- Fails when the input index is not an index of the transaction.
+--
+-- This is the function for one digest. For the digests of several inputs
+-- of one transaction, 'txSigHashWith' does not hash the transaction again
+-- for each of them on a network with a fork id.
 txSigHash ::
   Network ->
   -- | transaction to sign
@@ -283,13 +298,35 @@
   SigHash ->
   -- | hash to be signed
   Either String Hash256
-txSigHash net tx out v i sh
-  | i < 0 || i >= length tx.inputs =
+txSigHash net = txSigHashWith net . txSigHashes
+
+-- | 'txSigHash' for the transaction of the t'TxSigHashes'. It gives the
+-- digest that 'txSigHash' gives, and fails as it does.
+--
+-- On a network with a fork id the digest is that of 'txSigHashForkIdWith',
+-- which takes the hashes that the inputs share. Without a fork id nothing
+-- is shared: the legacy digest hashes a copy of the whole transaction for
+-- each input by its design, in Bitcoin Core too.
+txSigHashWith ::
+  Network ->
+  TxSigHashes ->
+  -- | script from output being spent
+  Script ->
+  -- | value of output being spent
+  Word64 ->
+  -- | index of input being signed
+  Int ->
+  -- | what to sign
+  SigHash ->
+  -- | hash to be signed
+  Either String Hash256
+txSigHashWith net hashes out v i sh
+  | i < 0 || i >= V.length hashes.inputs =
       Left "txSigHash: input index out of range"
   | isJust net.sigHashForkId && not (hasForkIdFlag sh) =
       Left "txSigHash: SIGHASH_FORKID is required on this network"
   | isJust net.sigHashForkId =
-      txSigHashForkId net tx out v i sh
+      txSigHashForkIdWith net hashes out v i sh
   | otherwise = do
       let newIn = buildInputs tx.inputs fout i sh
       -- When SigSingle and input index > outputs, then sign integer 1
@@ -300,6 +337,7 @@
           serialize newTx
           putWord32le $ fromIntegral sh
   where
+    tx = hashes.tx
     fout = Script $ filter (/= OP_CODESEPARATOR) out.ops
     one = "0100000000000000000000000000000000000000000000000000000000000000"
 
@@ -362,13 +400,18 @@
 --   token data, and their output script starts with the prefix byte 0xef,
 --   which 'Haskoin.Script.Standard.decodeOutput' does not read. Their
 --   digest is 'txSigHashCashToken', with the prefix that 'splitTokenPrefix'
---   takes off the script.
+--   takes off the script. "Haskoin.Script.CashToken" reads the prefix.
 --
 -- * Schnorr signatures as a 'TxSignature'. They are verified by
 --   'Haskoin.Crypto.Signature.verifyCashSchnorr', and by
 --   'Haskoin.Transaction.Builder.judgeInputs' in an input.
 --
 -- Fails when the input index is not an index of the transaction.
+--
+-- This is the function for one digest. It hashes every input and every
+-- output of the transaction, so the digests of all the inputs take time
+-- by the square of its size: 'txSigHashForkIdWith' is the function for
+-- them.
 txSigHashForkId ::
   Network ->
   -- | transaction to sign
@@ -383,8 +426,27 @@
   SigHash ->
   -- | hash to be signed
   Either String Hash256
-txSigHashForkId net tx = txSigHashCashToken net tx B.empty
+txSigHashForkId net = txSigHashForkIdWith net . txSigHashes
 
+-- | 'txSigHashForkId' for the transaction of the t'TxSigHashes', from the
+-- hashes that the inputs share. It gives the digest that 'txSigHashForkId'
+-- gives, and fails as it does. Its time does not depend on the size of the
+-- transaction.
+txSigHashForkIdWith ::
+  Network ->
+  TxSigHashes ->
+  -- | script from output being spent
+  Script ->
+  -- | value of output being spent
+  Word64 ->
+  -- | index of input being signed
+  Int ->
+  -- | what to sign
+  SigHash ->
+  -- | hash to be signed
+  Either String Hash256
+txSigHashForkIdWith net hashes = txSigHashCashTokenWith net hashes B.empty
+
 -- | 'txSigHashForkId' for a coin of Bitcoin Cash that holds tokens. The
 -- digest of such a coin also covers its token prefix, the bytes that
 -- 'splitTokenPrefix' takes off the front of its output script, which go in
@@ -409,38 +471,53 @@
   SigHash ->
   -- | hash to be signed
   Either String Hash256
-txSigHashCashToken net tx prefix out v i sh
-  | i < 0 || i >= length tx.inputs =
-      Left "txSigHashForkId: input index out of range"
-  | otherwise = Right . doubleSHA256 . runPutS $ do
-      putWord32le tx.version
-      serialize hashPrevouts
-      serialize hashSequence
-      serialize (tx.inputs !! i).outpoint
-      putByteString prefix
-      putScript out
-      putWord64le v
-      putWord32le (tx.inputs !! i).sequence
-      serialize hashOutputs
-      putWord32le tx.locktime
-      putWord32le $ fromIntegral hashType
+txSigHashCashToken net = txSigHashCashTokenWith net . txSigHashes
+
+-- | 'txSigHashCashToken' for the transaction of the t'TxSigHashes', from
+-- the hashes that the inputs share. It gives the digest that
+-- 'txSigHashCashToken' gives, and fails as it does.
+txSigHashCashTokenWith ::
+  Network ->
+  TxSigHashes ->
+  -- | token prefix of the output being spent, or empty
+  ByteString ->
+  -- | script from output being spent, without the prefix
+  Script ->
+  -- | value of output being spent
+  Word64 ->
+  -- | index of input being signed
+  Int ->
+  -- | what to sign
+  SigHash ->
+  -- | hash to be signed
+  Either String Hash256
+txSigHashCashTokenWith net hashes prefix out v i sh = do
+  input <- maybe (Left "txSigHashForkId: input index out of range") Right (hashes.inputs V.!? i)
+  return . doubleSHA256 . runPutS $ do
+    putWord32le hashes.tx.version
+    serialize hashPrevouts
+    serialize hashSequence
+    serialize input.outpoint
+    putByteString prefix
+    putScript out
+    putWord64le v
+    putWord32le input.sequence
+    serialize hashOutputs
+    putWord32le hashes.tx.locktime
+    putWord32le $ fromIntegral hashType
   where
     hashType = case net.sigHashForkId of
       Just forkId -> sigHashAddForkId sh forkId
       Nothing -> sh
     hashPrevouts
-      | not (anyoneCanPay sh) =
-          doubleSHA256 . runPutS $ mapM_ (serialize . (.outpoint)) tx.inputs
+      | not (anyoneCanPay sh) = hashes.hashPrevouts
       | otherwise = zeros
     hashSequence
-      | not (anyoneCanPay sh || isSigHashSingle sh || isSigHashNone sh) =
-          doubleSHA256 . runPutS $ mapM_ (putWord32le . (.sequence)) tx.inputs
+      | not (anyoneCanPay sh || isSigHashSingle sh || isSigHashNone sh) = hashes.hashSequence
       | otherwise = zeros
     hashOutputs
-      | not (isSigHashSingle sh || isSigHashNone sh) =
-          doubleSHA256 . runPutS $ mapM_ serialize tx.outputs
-      | isSigHashSingle sh && i < length tx.outputs =
-          doubleSHA256 . runPutS $ serialize $ tx.outputs !! i
+      | not (isSigHashSingle sh || isSigHashNone sh) = hashes.hashOutputs
+      | isSigHashSingle sh, Just output <- hashes.outputs V.!? i = doubleSHA256 (runPutS (serialize output))
       | otherwise = zeros
     putScript s = do
       let encodedScript = runPutS $ serialize s
@@ -449,62 +526,69 @@
     zeros :: Hash256
     zeros = "0000000000000000000000000000000000000000000000000000000000000000"
 
+-- | A transaction with what the digests of its inputs share: the three
+-- hashes of BIP 143 that are the same for every input (@hashPrevouts@,
+-- @hashSequence@ and @hashOutputs@). They are in the digest of a SegWit
+-- version 0 input on Bitcoin and of every input on Bitcoin Cash.
+--
+-- The three hashes cover every input and every output, so a digest that
+-- computes them again takes time by the size of the transaction, and the
+-- digests of all the inputs by its square. Bitcoin Core computes them once
+-- for a transaction (@PrecomputedTransactionData@), and so does Bitcoin
+-- Cash Node. With a value of this type, a BIP 143 digest takes time by the
+-- size of its own input. t'Haskoin.Transaction.Taproot.TaprootTxHashes' is
+-- the same thing for the digest of a Taproot input.
+--
+-- Make it with 'txSigHashes', which is the only way, so that the hashes
+-- are always those of the transaction. A hash is computed when the first
+-- digest needs it: one with @SIGHASH_ANYONECANPAY@ needs none of the two
+-- over the inputs, and one with @SIGHASH_NONE@ or @SIGHASH_SINGLE@ does not
+-- need the one over all the outputs.
+--
+-- No digest of this module commits to the input scripts nor to the
+-- witnesses of the transaction: BIP 143 leaves them out, and the legacy
+-- digest empties them. So the value stays right while the inputs of the
+-- transaction are signed. After any other change of the transaction, make
+-- it again.
+data TxSigHashes = TxSigHashes
+  { tx :: !Tx,
+    inputs :: !(Vector TxIn),
+    outputs :: !(Vector TxOut),
+    hashPrevouts :: Hash256,
+    hashSequence :: Hash256,
+    hashOutputs :: Hash256
+  }
+
+-- | The transaction with the hashes that the digests of its inputs share
+txSigHashes :: Tx -> TxSigHashes
+txSigHashes tx =
+  TxSigHashes
+    { tx = tx,
+      inputs = V.fromList tx.inputs,
+      outputs = V.fromList tx.outputs,
+      hashPrevouts = hashOf (mapM_ (serialize . (.outpoint)) tx.inputs),
+      hashSequence = hashOf (mapM_ (putWord32le . (.sequence)) tx.inputs),
+      hashOutputs = hashOf (mapM_ serialize tx.outputs)
+    }
+  where
+    hashOf = doubleSHA256 . runPutS
+
+-- | The transaction that the hashes were made from
+sigHashesTx :: TxSigHashes -> Tx
+sigHashesTx hashes = hashes.tx
+
 -- | Split the script field of an output of Bitcoin Cash into its token
 -- prefix and the output script after it. An output without tokens has an
 -- empty prefix. 'Nothing' for a prefix that is not well formed.
 --
--- Since May 2023 an output may hold tokens (CashTokens). They are written
--- at the front of its script field: the byte @0xef@, the 32 bytes of the
--- token category, a byte of flags, and after it a commitment with its
--- length and an amount, each when its flag is set. What follows is the
--- output script that locks the coin.
+-- This gives the prefix as bytes, which is what 'txSigHashCashToken' needs.
+-- 'Haskoin.Script.CashToken.splitTokenData' reads the same prefix into a
+-- t'Haskoin.Script.CashToken.TokenData', and says what is wrong with one that
+-- is not well formed.
 splitTokenPrefix :: ByteString -> Maybe (ByteString, ByteString)
-splitTokenPrefix bytes
-  | B.null bytes || B.head bytes /= 0xef = Just (B.empty, bytes)
-  | B.length bytes < 34 = Nothing
-  | flags .&. 0x80 /= 0 = Nothing
-  -- tokens of some kind, a commitment only with a non-fungible one, and
-  -- a capability of none, mutable or minting, only with one too
-  | not hasNft && not hasAmount = Nothing
-  | not hasNft && (hasCommitment || capability /= 0) = Nothing
-  | capability > 2 = Nothing
-  | otherwise = do
-      afterCommitment <-
-        if hasCommitment
-          then do
-            (n, rest) <- compact afterFlags
-            if n == 0 || fromIntegral (B.length rest) < n then Nothing else Just (B.drop (fromIntegral n) rest)
-          else Just afterFlags
-      afterAmount <-
-        if hasAmount
-          then do
-            (n, rest) <- compact afterCommitment
-            if n == 0 || n > 0x7fffffffffffffff then Nothing else Just rest
-          else Just afterCommitment
-      Just (B.splitAt (B.length bytes - B.length afterAmount) bytes)
-  where
-    flags = B.index bytes 33
-    afterFlags = B.drop 34 bytes
-    hasCommitment = flags .&. 0x40 /= 0
-    hasNft = flags .&. 0x20 /= 0
-    hasAmount = flags .&. 0x10 /= 0
-    capability = flags .&. 0x0f
-    -- a number in the compact form of the protocol, in its shortest
-    -- encoding only
-    compact :: ByteString -> Maybe (Word64, ByteString)
-    compact b = case B.uncons b of
-      Nothing -> Nothing
-      Just (w, rest)
-        | w < 0xfd -> Just (fromIntegral w, rest)
-        | w == 0xfd -> sized 2 0xfd rest
-        | w == 0xfe -> sized 4 0x10000 rest
-        | otherwise -> sized 8 0x100000000 rest
-    sized k least rest
-      | B.length rest < k = Nothing
-      | n < least = Nothing
-      | otherwise = Just (n, B.drop k rest)
-      where
-        n = B.foldr (\w acc -> acc `shiftL` 8 .|. fromIntegral w) 0 (B.take k rest)
+splitTokenPrefix bytes = case splitTokenData bytes of
+  Left _ -> Nothing
+  Right (_, rest) -> Just (B.splitAt (B.length bytes - B.length rest) bytes)
 
 -- | Data type representing a signature together with a 'SigHash'. The 'SigHash'
 -- is serialized as one byte at the end of an ECDSA 'Sig'. All signatures in
@@ -512,7 +596,7 @@
 --
 -- This is the form of a signature that nodes relay. The binary and JSON
 -- forms, and 'decodeTxSig', apply the three signature rules of the standard
--- script flags of Bitcoin Core, and one rule of the network:
+-- script flags of Bitcoin Core, and two rules of the network:
 --
 -- * @DERSIG@: strict DER, as BIP 66 defines it, with r and s between 1 and
 --   the curve order minus 1.
@@ -524,20 +608,37 @@
 -- * The 'SIGHASH_FORKID' flag is set exactly on the networks that have a
 --   fork id.
 --
+-- * On a network that has a fork id, the signature is not 64 bytes long
+--   before its hash type byte ('isCashSchnorrLength'). See below.
+--
 -- Nothing may follow the hash type byte.
 --
--- Only the first rule is a consensus rule, and only since BIP 66. A block
--- can therefore hold signatures that do not decode: one with a high S, one
--- with an undefined hash type byte, and, before BIP 66 activated, one in a
--- looser DER form. An input with such a signature fails
+-- On Bitcoin only the first rule is a consensus rule, and only since BIP 66.
+-- A block can therefore hold signatures that do not decode: one with a high
+-- S, one with an undefined hash type byte, and, before BIP 66 activated, one
+-- in a looser DER form. An input with such a signature fails
 -- 'Haskoin.Script.Standard.decodeInput', and has no
 -- 'Haskoin.Address.inputAddress'. This type is not a parser for the whole
 -- chain history. 'Haskoin.Crypto.Signature.decodeStrictSig' reads a
 -- signature under BIP 66 alone.
 --
 -- On Bitcoin Cash, a signature of 64 bytes followed by the hash type byte is
--- a Schnorr signature, which Bitcoin Cash Node accepts in @OP_CHECKSIG@.
--- This type only holds ECDSA signatures, so those do not decode either.
+-- a Schnorr signature, whatever its bytes. Bitcoin Cash Node verifies it as
+-- one in @OP_CHECKSIG@, and takes no signature of that length in a multisig
+-- that has no field of bits. This type only holds ECDSA signatures, so on a
+-- network with a fork id nothing of 64 bytes decodes: not a Schnorr
+-- signature, and not an ECDSA signature whose DER form has that length.
+--
+-- Such an ECDSA signature exists: its r and s take 58 bytes together, where
+-- they mostly take 64 or 65. It verifies as ECDSA, and no block of Bitcoin
+-- Cash holds it, so to read it as a good signature is to call valid a
+-- transaction that a node refuses and drops its peer for. The specification
+-- of the Schnorr signatures of Bitcoin Cash gives one chance in 2^49 of
+-- making one by accident, but a computer makes one on purpose in a minute.
+-- On Bitcoin it is an ordinary signature, and it decodes. 'encodeTxSig'
+-- writes such a value on every network: on a network with a fork id it is
+-- written and not read back. The signer does not make one there
+-- ('Haskoin.Transaction.Builder.Sign.makeSignature').
 data TxSignature
   = TxSignature
       { sig :: !Sig,
@@ -560,6 +661,8 @@
         sig <- deserialize
         unless (isCanonicalHalfOrder sig) $
           fail "Non-canonical signature: S value is unnecessarily high"
+        when (isJust net.sigHashForkId && isCashSchnorrLength sig) $
+          fail "Non-canonical signature: a signature of 64 bytes is a Schnorr signature on this network"
         sh <- fromIntegral <$> getWord8
         when (isSigHashUnknown sh) $
           fail "Non-canonical signature: unknown hashtype byte"
@@ -586,9 +689,11 @@
 encodeTxSig net = runPutS . marshalPut net
 
 -- | Parse a signature with its hash type byte, under the rules listed at
--- 'TxSignature': strict DER, a low S, a defined hash type, and the fork id
--- flag that the network asks for. The empty string is 'TxSignatureEmpty'. A
--- signature that is valid by consensus alone does not decode.
+-- 'TxSignature': strict DER, a low S, a defined hash type, the fork id
+-- flag that the network asks for, and on a network with a fork id a length
+-- other than 64 bytes, which is a Schnorr signature there. The empty string
+-- is 'TxSignatureEmpty'. A signature that is valid by consensus alone does
+-- not decode.
 decodeTxSig :: Network -> ByteString -> Either String TxSignature
 decodeTxSig net =
   runGetS $ do
diff --git a/src/Haskoin/Script/Standard.hs b/src/Haskoin/Script/Standard.hs
--- a/src/Haskoin/Script/Standard.hs
+++ b/src/Haskoin/Script/Standard.hs
@@ -209,15 +209,31 @@
 -- The counts of a multisig output are @OP_1@ to @OP_16@, or a one-byte push
 -- for 17 to 'maxMultisigKeys', and a key must fill its push exactly.
 --
--- A 'ScriptOutput' describes what a script does, not its bytes. Two kinds of
--- script decode to a value that 'encodeOutput' writes back as other bytes:
--- a multisig whose keys are not direct pushes, and a data carrier whose data
--- is not pushed in the shortest way. Bitcoin Core gives those the same type
--- (@multisig@ and @nulldata@). So never hash or sign the result of
--- @encodeOutput@ in place of a script that came from somewhere else. Hash
--- and sign the bytes of that script. 'decodeInput' refuses a redeem script
--- that would not come back as the same bytes.
+-- The keys of a multisig output must be direct pushes too. Here the match is
+-- stricter than the @Solver@ of Bitcoin Core, which calls a script
+-- @multisig@ also when a key is pushed with @OP_PUSHDATA1@, @2@ or @4@.
+-- Bitcoin Cash Node asks for the shortest push, as this function does. The
+-- reason is the type. A 'ScriptOutput' describes what a script does, not its
+-- bytes: it has no place for the form of a push, and 'encodeOutput' writes
+-- direct pushes. The signature of a multisig input covers the bytes of the
+-- script of its coin. A script read as a 'PayMulSig' and written back with
+-- other pushes is another script, and a signature over it does not open the
+-- coin. So a 'PayMulSig' stands for one script only, and the signers and
+-- verifiers of this library, which take a 'ScriptOutput', sign and verify
+-- the script of the coin. The cost: for this library such a coin is not a
+-- standard output, and its spend is neither signed nor verified. On Bitcoin
+-- a block may hold that spend and nodes do not relay it (the @MINIMALDATA@
+-- rule of the relay policy). On Bitcoin Cash no block holds it. The other
+-- way, a value that keeps the bytes it was read from, would change the type
+-- for every caller, for coins that only a script written by hand makes.
 --
+-- One kind of script still decodes to a value that 'encodeOutput' writes
+-- back as other bytes: a data carrier whose data is not pushed in the
+-- shortest way. Bitcoin Core gives it the same type (@nulldata@). No one
+-- spends such an output, so nothing signs its script. Still, never hash the
+-- result of @encodeOutput@ in place of a script that came from somewhere
+-- else: hash the bytes of that script.
+--
 -- Three kinds of script that the @Solver@ of Bitcoin Core classifies are not
 -- decoded here, because a 'PublicKey' holds a point of the curve:
 --
@@ -233,8 +249,11 @@
 --   Bitcoin Core counts as a push.
 --
 -- On Bitcoin Cash, an output that holds tokens starts with the token prefix
--- byte 0xef and is not decoded. See 'Haskoin.Script.SigHash.txSigHashForkId'
--- for what is not supported on that network.
+-- byte 0xef and is not decoded: the prefix is not a script. Take it off with
+-- 'Haskoin.Script.CashToken.splitTokenData' and decode the rest, or call
+-- 'Haskoin.Address.scriptToAddressBS', which does both on that network. See
+-- 'Haskoin.Script.SigHash.txSigHashForkId' for what else is not supported
+-- there.
 decodeOutput :: Script -> Either String ScriptOutput
 decodeOutput s = case s.ops of
   -- Pay to PubKey
@@ -412,7 +431,8 @@
     size = B.length bytes
 
 -- | Match @[OP_M, PubKey1, ..., PubKeyN, OP_N, OP_CHECKMULTISIG]@ with M and N
--- from 1 to 'maxMultisigKeys' and M at most N.
+-- from 1 to 'maxMultisigKeys', M at most N, and each key a direct push: see
+-- 'decodeOutput' for why no other push of a key is read.
 matchPayMulSig :: Script -> Either String ScriptOutput
 matchPayMulSig (Script ops) = case splitAt (length ops - 2) ops of
   (m : xs, [n, OP_CHECKMULTISIG]) -> do
@@ -424,8 +444,9 @@
     return $ PayMulSig keys intM
   _ -> Left "matchPayMulSig: script did not match output template"
   where
-    key (OP_PUSHDATA bs _) = decodePubKey bs
-    key _ = Left "matchPayMulSig: invalid multisig opcode"
+    -- A key is 33 or 65 bytes, so its direct push is its shortest one
+    key (OP_PUSHDATA bs OPCODE) = decodePubKey bs
+    key _ = Left "matchPayMulSig: a key is not a direct push"
 
 -- | The count that a multisig opcode stands for: @OP_1@ to @OP_16@, or a
 -- one-byte push of 17 to 'maxMultisigKeys'. Bitcoin Core reads the count as a
@@ -589,13 +610,12 @@
 --   alone does not decode. See 'TxSignature'.
 --
 -- * The redeem script must be in the form that 'encodeOutput' writes, byte
---   for byte. Bitcoin Core's @Solver@ also calls a script a multisig when a
---   key is pushed with @OP_PUSHDATA1@, but a 'ScriptOutput' cannot hold the
---   form of a push, so such a script would come back out as other bytes with
---   another hash. It is refused here, so that 'Haskoin.Address.inputAddress'
---   is always the hash of the bytes the input carries, and so that encoding
---   a decoded input never rewrites its redeem script. Spending such a script
---   breaks the @MINIMALDATA@ rule of the relay policy, so no standard
+--   for byte, so that 'Haskoin.Address.inputAddress' is always the hash of
+--   the bytes the input carries, and so that encoding a decoded input never
+--   rewrites its redeem script. A multisig whose keys are pushed with
+--   @OP_PUSHDATA1@ is not in that form, although Bitcoin Core's @Solver@
+--   calls it a multisig: 'decodeOutput' does not read it. Spending such a
+--   script breaks the @MINIMALDATA@ rule of the relay policy, so no standard
 --   transaction has one.
 --
 -- * The witness program of a 'NestedWitnessInput' must be a direct push and
diff --git a/src/Haskoin/Transaction/Builder.hs b/src/Haskoin/Transaction/Builder.hs
--- a/src/Haskoin/Transaction/Builder.hs
+++ b/src/Haskoin/Transaction/Builder.hs
@@ -26,6 +26,7 @@
     signTx,
     signNestedWitnessTx,
     makeSignature,
+    makeSignatureWith,
     signInput,
     signNestedInput,
     signTaprootInput,
@@ -58,7 +59,7 @@
   )
 where
 
-import Control.Monad (foldM, unless, when)
+import Control.Monad (foldM, join, mfilter, unless, when)
 import Control.Monad.Identity (runIdentity)
 import Crypto.Secp256k1
 import Data.Bits (popCount, testBit)
@@ -68,11 +69,13 @@
 import Data.Conduit (ConduitT, Void, await, runConduit, (.|))
 import Data.Conduit.List (sourceList)
 import Data.Either (fromRight, rights)
-import Data.List (nub)
+import Data.List (nub, transpose, zip4)
 import Data.Map.Strict qualified as Map
-import Data.Maybe (catMaybes, isNothing)
+import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing)
 import Data.String.Conversions (cs)
 import Data.Text (Text)
+import Data.Vector (Vector)
+import Data.Vector qualified as V
 import Data.Word (Word64)
 import Haskoin.Address
 import Haskoin.Crypto.Hash (Hash256, addressHash)
@@ -80,7 +83,14 @@
 import Haskoin.Crypto.Signature
 import Haskoin.Network.Data
 import Haskoin.Script
-import Haskoin.Transaction.Builder.Sign (SigInput, buildInput, makeSignature, sigKeys, signTaprootInput)
+import Haskoin.Transaction.Builder.Sign
+  ( SigInput,
+    buildInput,
+    makeSignature,
+    makeSignatureWith,
+    sigKeys,
+    signTaprootInput,
+  )
 import Haskoin.Transaction.Builder.Sign qualified as Sign
 import Haskoin.Transaction.Common
 import Haskoin.Transaction.Segwit
@@ -645,6 +655,15 @@
 -- The witness is not merged: the transactions must have the same one, and
 -- the result keeps it, so that a SegWit input signed before the multisig
 -- signers took their copies stays signed.
+--
+-- __Cost.__ Each input is merged on its own input scripts, and the
+-- transaction is put together once. On a network with a fork id, the
+-- hashes that the digests of the inputs share are computed once
+-- ('txSigHashes'), and the time grows with the size of the transaction.
+-- On Bitcoin the digest of a legacy input hashes a copy of the whole
+-- transaction, in Bitcoin Core too, so the time grows with the square of
+-- the number of inputs. The coins are best given in the order of the
+-- inputs: each input looks for its coin from the start of the list.
 mergeTxs ::
   Network ->
   [Tx] ->
@@ -654,26 +673,40 @@
   [] -> Left "Transaction list is empty"
   [tx] -> return tx
   tx : _
-    | length (nub emptyTxs) /= 1 -> Left "Transactions do not match"
-    | otherwise -> foldM (mergeTxInput net txs) (clearAll tx) (outs tx)
+    | length (nub (map cleared txs)) /= 1 -> Left "Transactions do not match"
+    | otherwise -> do
+        -- No digest commits to an input script, so the hashes of the
+        -- first transaction hold for all of them
+        let merged = mergedInput (txSigHashes tx)
+            -- A left fold, and not 'mapM', which keeps a stack frame for
+            -- each input while it works on the next ones: a call into
+            -- libsecp256k1 takes longer on a deep stack
+            next done item = (: done) <$> merged item
+        inputs <- foldM next [] (zip4 [0 ..] tx.inputs (coinsOf tx) scriptsByInput)
+        return tx {inputs = reverse inputs}
   where
-    zipOp tx = zip (matchTemplate os tx.inputs f) [0 ..]
-    outs tx =
-      [ ((o, v), i)
-      | (Just (o, v, _), i) <- zipOp tx
-      ]
-    f (_, _, o) txin = o == txin.outpoint
-    emptyTxs = map clearAll txs
-    clearAll tx = foldl clearInput tx (outs tx)
-    ins is i = updateIndex i is (\TxIn {..} -> TxIn {script = B.empty, ..})
-    clearInput tx (_, i) =
-      Tx tx.version (ins tx.inputs i) tx.outputs tx.witness tx.locktime
+    -- The coin of each input, when the caller gave one for its outpoint
+    coinsOf tx = matchTemplate os tx.inputs (\(_, _, o) txin -> o == txin.outpoint)
+    -- The transaction without the input scripts that are merged
+    cleared tx = tx {inputs = zipWith (maybe id (const (withScript B.empty))) (coinsOf tx) tx.inputs}
+    -- For each input, its input script in each transaction. The
+    -- transactions match, so they have the same number of inputs.
+    scriptsByInput = transpose (map (map (.script) . (.inputs)) txs)
+    -- An input without coin stays as it is, and an input with a coin that
+    -- nobody signed gets an empty input script
+    mergedInput _ (_, input, Nothing, _) = Right input
+    mergedInput sigHashes (i, input, Just (so, val, _), signed) = do
+      script <- mergeScripts net sigHashes so val i signed
+      return (withScript (fromMaybe B.empty script) input)
 
 -- | Merge input from partially-signed multisig transactions.  This function
 -- does not support segwit and P2SH-segwit inputs. When no transaction has a
 -- script for the input, the input is left as it is. Fails when one of the
 -- transactions has no input at the index. The witness of the transaction
 -- is kept.
+--
+-- This is the function for one input. 'mergeTxs' merges every input of a
+-- transaction and does the work that the inputs share once.
 mergeTxInput ::
   Network ->
   [Tx] ->
@@ -683,16 +716,38 @@
 mergeTxInput net txs tx ((so, val), i) = do
   when (i < 0 || any ((<= i) . length . (.inputs)) (tx : txs)) $
     Left "mergeTxInput: input index out of range"
-  -- Ignore transactions with empty inputs
-  let ins = map ((.script) . (!! i) . (.inputs)) txs
-  sigRes <- mapM extractSigs $ filter (not . B.null) ins
+  merged <- mergeScripts net (txSigHashes tx) so val i (map ((.script) . (!! i) . (.inputs)) txs)
+  return $ case merged of
+    Nothing -> tx
+    Just script -> tx {inputs = updateIndex i tx.inputs (withScript script)}
+
+-- | The input with another input script
+withScript :: B.ByteString -> TxIn -> TxIn
+withScript newScript TxIn {..} = TxIn {script = newScript, ..}
+
+-- | The input script of a multisig input with the signatures of the input
+-- scripts given, which are those of the input in each transaction to
+-- merge. An empty input script is passed over, and there is no result
+-- when all of them are empty. The hashes are those of the transaction
+-- that the signatures sign: see t'TxSigHashes'.
+mergeScripts ::
+  Network ->
+  TxSigHashes ->
+  ScriptOutput ->
+  Word64 ->
+  Int ->
+  [B.ByteString] ->
+  Either String (Maybe B.ByteString)
+mergeScripts net sigHashes so val i scripts = do
+  sigRes <- mapM extractSigs $ filter (not . B.null) scripts
   case sigRes of
-    [] -> return tx
+    [] -> return Nothing
     (_, rdm) : _ -> do
       unless (all ((== rdm) . snd) sigRes) $ Left "Redeem scripts do not match"
-      si <- marshal net <$> go (nub $ concatMap fst sigRes) so rdm
-      let ins' = updateIndex i tx.inputs (\TxIn {..} -> TxIn {script = si, ..})
-      return $ Tx tx.version ins' tx.outputs tx.witness tx.locktime
+      -- The script is computed here, and not when the caller reads it:
+      -- what was read from the scripts to merge is not kept until then
+      merged <- marshal net <$> go (nub $ concatMap fst sigRes) so rdm
+      return $! Just $! merged
   where
     go allSigs out rdmM =
       case out of
@@ -719,7 +774,7 @@
         _ -> Left "Invalid script input type"
     f out (TxSignature x sh) p =
       either (const False) (\h -> verifyHashSig h x p.point) $
-        encodeOutput out >>= \s -> txSigHash net tx s val i sh
+        encodeOutput out >>= \s -> txSigHashWith net sigHashes s val i sh
     f _ TxSignatureEmpty _ = False
 
 {- Tx verification -}
@@ -733,41 +788,74 @@
 --
 -- This is not a script interpreter. It answers 'True' only for the
 -- standard kinds of input listed at 'verifyStdInput', and 'False' for any
--- other script, valid or not. For those kinds it follows consensus: it
--- does not answer 'True' for an input that no block can contain.
+-- other script, valid or not. For those kinds it follows the rules by
+-- which Bitcoin Core relays an input, which are stricter than those of a
+-- block. It does not answer 'True' for an input that no block can
+-- contain, nor for one that a block may hold and that nodes do not relay:
+-- 'verifyStdInput' lists them. A caller that hands a transaction to its
+-- peers needs that answer, and a miner is the only one who can use the
+-- other.
+--
+-- 'True' is still no promise that nodes relay the transaction. The relay
+-- policy also has rules on the whole transaction, such as its size, its
+-- fee and its outputs, that are not looked at here.
+--
+-- __Cost.__ The time grows with the size of the transaction, and not with
+-- its square: each coin is looked up once, and the hashes that the digests
+-- of the inputs share are computed once ('TxSigHashes' for SegWit version 0
+-- and for a network with a fork id, 'TaprootTxHashes' for Taproot). A
+-- legacy input of Bitcoin is the exception: its digest hashes a copy of
+-- the whole transaction, in Bitcoin Core too.
 verifyStdTx ::
   Network -> Tx -> [(ScriptOutput, Word64, OutPoint)] -> Bool
 verifyStdTx net tx coins =
   not (null tx.inputs)
     && Map.size (Map.fromList [(i.outpoint, ()) | i <- tx.inputs]) == length tx.inputs
-    && all (verifyInput net tx spent) [0 .. length tx.inputs - 1]
-    && maybe False (\outs -> toSpend <= sum (map (toInteger . snd) outs)) (sequence spent.coins)
+    && all (verifyInput net spent) [0 .. length tx.inputs - 1]
+    && maybe False (\outs -> toSpend <= sum (fmap (toInteger . snd) outs)) (sequence spent.coins)
   where
     -- The coins are looked up once for the whole transaction
     spent = spentCoins tx coins
     toSpend = sum (map (toInteger . (.value)) tx.outputs)
 
--- | The coin of each input of a transaction, and the outputs that the
--- Taproot digest commits to. 'verifyStdTx' computes this once, so that the
--- time it takes does not grow with the square of the number of inputs.
+-- | The coin of each input of a transaction, what each input gives to
+-- spend it, and the hashes that the digests of its inputs share.
+-- 'verifyStdTx' and 'judgeInputs' compute this once for a transaction:
+-- they look up each coin once, and the digests hash the inputs and the
+-- outputs of the transaction once, and not once for each input. The legacy
+-- digest of Bitcoin shares nothing. An input is read by its index in
+-- constant time, where a list is walked up to it.
 data SpentCoins = SpentCoins
   { -- | the coin of each input, in order, when it is among those given
-    coins :: [Maybe (ScriptOutput, Word64)],
-    -- | the output every input spends, when every coin is given
-    outputs :: Maybe [TxOut]
+    coins :: Vector (Maybe (ScriptOutput, Word64)),
+    -- | the input script and the witness stack of each input, in order
+    spends :: Vector (B.ByteString, WitnessStack),
+    -- | the hashes of the BIP 143 digests: SegWit version 0, and every
+    -- input on a network with a fork id
+    sigHashes :: TxSigHashes,
+    -- | the hashes of the Taproot digests, when every coin is given: the
+    -- digest commits to the output that every input spends
+    taproot :: Maybe TaprootTxHashes
   }
 
 spentCoins :: Tx -> [(ScriptOutput, Word64, OutPoint)] -> SpentCoins
 spentCoins tx given =
   SpentCoins
-    { coins = found,
-      outputs = map (\(so, val) -> TxOut val (encodeSerial so)) <$> sequence found
+    { coins = V.fromList found,
+      spends = V.fromList (Sign.inputSpends tx),
+      sigHashes = txSigHashes tx,
+      taproot = sharedHashes tx . map (\(so, val) -> TxOut val (encodeSerial so)) =<< sequence found
     }
   where
     -- The first coin given for an outpoint is its coin
     byOutPoint = Map.fromListWith (\_ first -> first) [(o, (so, val)) | (so, val, o) <- given]
     found = map (\i -> Map.lookup i.outpoint byOutPoint) tx.inputs
 
+-- | The hashes that the Taproot digests of a transaction share, from the
+-- output that each of its inputs spends
+sharedHashes :: Tx -> [TxOut] -> Maybe TaprootTxHashes
+sharedHashes tx = eitherToMaybe . taprootTxHashes tx
+
 -- | Verify that an input spends one of the coins given with a standard
 -- input that verifies: a signature of the right key and digest for
 -- pay-to-public-key, pay-to-public-key-hash, multisig and pay-to-script-hash
@@ -792,54 +880,97 @@
 --   makes the operation fail.
 -- * The input script of a SegWit program nested in pay-to-script-hash is
 --   the push of the program and nothing else (BIP 141).
+-- * The witness script of a pay-to-witness-script-hash input is, byte for
+--   byte, the script whose hash the coin holds (BIP 141). A multisig
+--   script with the same keys pushed another way is another script:
+--   'decodeWitnessInput' refuses it.
 -- * A redeem script is at most 'maxRedeemScriptSize' bytes, and a witness
 --   script at most 'maxWitnessScriptSize'.
+-- * A multisig of Taproot has at most 999 keys, the limit of @multi_a@ in
+--   BIP 387. 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.
 -- * A network without SegWit has no witness inputs.
+-- * On Bitcoin Cash, the input script pushes each item by the shortest
+--   push that holds it ('isMinimalPush'). Every block must keep the
+--   @MINIMALDATA@ rule there.
+-- * On Bitcoin Cash, no signature is 64 bytes long before its hash type
+--   byte. A node reads that length as a Schnorr signature, also when the
+--   bytes are a valid ECDSA signature in DER, and this function reads no
+--   Schnorr signature ('decodeTxSig'). On Bitcoin a block may hold such an
+--   ECDSA signature, and the answer is 'True' for it.
 --
--- The answer can be 'False' for an input that a block may hold but that
--- nodes do not relay:
+-- The answer is not 'True' either for an input that a block may hold and
+-- that nodes do not relay. The rules are those by which Bitcoin Core 32.1
+-- relays an input: @STANDARD_SCRIPT_VERIFY_FLAGS@ and @IsWitnessStandard@.
+-- Up to version 2.0.1 the answer was 'True' for the last three of this
+-- list:
 --
 -- * A signature is read with 'decodeTxSig', which applies the relay rules:
 --   low S and a defined hash type.
+-- * A key is read with 'decodePubKey': compressed or uncompressed. A key in
+--   the hybrid form, 65 bytes that start with 0x06 or 0x07, is refused. On
+--   Bitcoin a block may hold it, and the @STRICTENC@ rule of the relay
+--   policy does not allow it. On Bitcoin Cash no block holds it.
 -- * A legacy multisig input with an empty item before its signatures
 --   leaves that item on the stack. Consensus allows it outside a witness,
 --   and the @CLEANSTACK@ rule of the relay policy does not.
+-- * A coin that commits to a multisig script whose keys are not direct
+--   pushes, as a redeem script or as a witness script. Its spend breaks
+--   the @MINIMALDATA@ rule of the relay policy. 'decodeInput' and
+--   'decodeWitnessInput' do not read such a script. A coin locked to such
+--   a script itself cannot be given here: 'decodeOutput' does not read it,
+--   so that a 'PayMulSig' is always the script the signatures cover.
+-- * 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 (@MINIMALDATA@).
+-- * A SegWit version 0 input with a signature checked against an
+--   uncompressed key (@WITNESS_PUBKEYTYPE@): the key of a witness key
+--   hash, native or nested, and the key of a witness script. In a
+--   multisig witness script, @OP_CHECKMULTISIG@ tries the keys from the
+--   last one until every signature has its key. So the signatures must
+--   verify against the compressed keys after the last uncompressed one,
+--   and an uncompressed key before the first key that signs is not looked
+--   at, as in Bitcoin Core.
+-- * A Taproot input with an annex, by the key path or by a script path.
+--   BIP 341 gives the annex no meaning yet, and Bitcoin Core does not
+--   relay one (@IsWitnessStandard@).
 --
--- An uncompressed key in a SegWit input is accepted, since a block may
--- hold it, although nodes do not relay it.
+-- 'signInput' can still make a SegWit input with an uncompressed key, for
+-- one who has a miner to hand it to. The answer here is 'False' for it:
+-- 'judgeInputs' tells such an input, 'InputUndecided', from a forged one.
+--
+-- 'True' is still no promise that nodes relay the transaction: the relay
+-- policy also has rules on the whole transaction, such as its size, its
+-- fee and its outputs, that are not looked at here.
 verifyStdInput :: Network -> Tx -> [(ScriptOutput, Word64, OutPoint)] -> Int -> Bool
-verifyStdInput net tx coins = verifyInput net tx (spentCoins tx coins)
+verifyStdInput net tx coins = verifyInput net (spentCoins tx coins)
 
 -- | 'verifyStdInput' on coins that are looked up already
-verifyInput :: Network -> Tx -> SpentCoins -> Int -> Bool
-verifyInput net tx spent i
-  | i < 0 || i >= length tx.inputs = False
-  | otherwise = case spent.coins !! i of
-      Nothing -> False
-      Just (so0, val)
-        | isSegwit so0 ->
-            net.segWit && fromRight False ((B.null inp &&) . verifySegwitInput so0 val <$> wp so0)
-        | isTaproot so0 ->
-            net.segWit && B.null inp && verifyTaprootInput so0
-        | otherwise ->
-            or $
-              rights
-                [ (\si -> null ws && verifyLegacyInput so0 val si) <$> unmarshal net inp,
-                  nestedScriptOutput >>= \so -> verifyNestedInput so0 so val <$> wp so
-                ]
+verifyInput :: Network -> SpentCoins -> Int -> Bool
+verifyInput net spent i = case join (spent.coins V.!? i) of
+  Nothing -> False
+  Just (so0, val)
+    | isSegwit so0 ->
+        net.segWit && fromRight False ((B.null inp &&) . verifySegwitInput so0 val <$> wp so0)
+    | isTaproot so0 ->
+        net.segWit && B.null inp && verifyTaprootInput so0
+    | otherwise ->
+        or $
+          rights
+            [ (\si -> null ws && minimalPushes inp && verifyLegacyInput so0 val si)
+                <$> unmarshal net inp,
+              nestedScriptOutput >>= \so -> verifyNestedInput so0 so val <$> wp so
+            ]
   where
-    inp = (tx.inputs !! i).script
-    theTxSigHash so val = Sign.makeSigHash net tx i so val
+    (inp, ws) = fromMaybe (B.empty, []) (spent.spends V.!? i)
+    theTxSigHash so val = Sign.makeSigHashWith net spent.sigHashes i so val
+    legacyDigest out val = txSigHashWith net spent.sigHashes out val i
 
     -- A signature verifies only when its digest could be computed.
     checkSig :: Either String Hash256 -> Sig -> PubKey -> Bool
     checkSig h sig pub = either (const False) (\m -> verifyHashSig m sig pub) h
 
-    ws :: WitnessStack
-    ws
-      | length tx.witness > i = tx.witness !! i
-      | otherwise = []
-
     wp :: ScriptOutput -> Either String (Maybe ScriptOutput, SimpleInput)
     wp so = decodeWitnessInput net =<< viewWitnessProgram net so ws
 
@@ -870,12 +1001,14 @@
         pubKeyAddr pub == p2pkhAddr h
           && checkSig (theTxSigHash so val sh Nothing) sig pub.point
       (PayMulSig pubs r, RegularInput (SpendMulSig sigs)) ->
-        either (const False) (\out -> multisigVerifies (txSigHash net tx out val i) ((.point) <$> pubs) r sigs) $
+        either (const False) (\out -> multisigVerifies (legacyDigest out val) ((.point) <$> pubs) r sigs) $
           encodeOutput so
       (PayScriptHash h, ScriptHashInput si' rdm) ->
         payToScriptAddress rdm == Right (p2shAddr h) && verifyLegacyInput rdm val (RegularInput si')
       _ -> False
 
+    -- A signature of a SegWit version 0 input verifies against a
+    -- compressed key only: WITNESS_PUBKEYTYPE of the relay policy.
     verifySegwitInput ::
       ScriptOutput -> Word64 -> (Maybe ScriptOutput, SimpleInput) -> Bool
     verifySegwitInput so val (rdm, si) = case (so, rdm, si) of
@@ -883,9 +1016,7 @@
         Nothing,
         SpendPKHash (TxSignature sig sh) pub
         ) ->
-          -- Compare the key hash only. An uncompressed key is non-standard
-          -- here but still valid by consensus, so verification accepts it.
-          let keytest = pubKeyAddr pub == p2pkhAddr h
+          let keytest = pub.compress && pubKeyAddr pub == p2pkhAddr h
               sighash = theTxSigHash so val sh Nothing
               pkpoint = pub.point
               verify = checkSig sighash sig pkpoint
@@ -894,7 +1025,7 @@
         Just rdm'@(PayPK pub),
         SpendPK (TxSignature sig sh)
         ) ->
-          let keytest = payToWitnessScriptAddress rdm' == Right (p2wshAddr h)
+          let keytest = pub.compress && payToWitnessScriptAddress rdm' == Right (p2wshAddr h)
               sighash = theTxSigHash so val sh $ Just rdm'
               pkpoint = pub.point
               verify = checkSig sighash sig pkpoint
@@ -904,7 +1035,7 @@
         SpendPKHash (TxSignature sig sh) pub
         ) ->
           let keytest = payToWitnessScriptAddress rdm' == Right (p2wshAddr h)
-              addrtest = addressHash (encodeSerial pub) == kh
+              addrtest = pub.compress && addressHash (encodeSerial pub) == kh
               pkpoint = pub.point
               sighash = theTxSigHash so val sh $ Just rdm'
               verify = checkSig sighash sig pkpoint
@@ -914,7 +1045,12 @@
         SpendMulSig sigs
         ) ->
           let keytest = payToWitnessScriptAddress rdm' == Right (p2wshAddr h)
-              pkpoints = (.point) <$> pubs
+              -- OP_CHECKMULTISIG tries the keys from the last one, until
+              -- every signature has its key. The relay policy fails the
+              -- script at an uncompressed key that is tried. So the
+              -- signatures must verify against the compressed keys after
+              -- the last uncompressed one.
+              pkpoints = (.point) <$> reverse (takeWhile (.compress) (reverse pubs))
               hashfun sh = theTxSigHash so val sh $ Just rdm'
               verify = multisigVerifies hashfun pkpoints r sigs
            in keytest && verify
@@ -931,22 +1067,25 @@
       outKey <- case so of
         PayWitness 1 program -> maybe (Left "not an output key") Right (importXOnlyPubKey program)
         _ -> Left "not a Taproot output"
-      -- The outputs every input spends, in order, which the Taproot digest
-      -- commits to
-      spentOutputs <- maybe (Left "a spent output is missing") Right spent.outputs
-      let schnorr sigBytes annex leaf = do
+      -- The digest commits to the output that every input spends
+      hashes <- maybe (Left "a spent output is missing") Right spent.taproot
+      spend <- maybe (Left "not a Taproot witness") Right (viewTaprootWitness ws)
+      -- Bitcoin Core does not relay an annex, whatever is in it
+      -- (@IsWitnessStandard@)
+      when (isJust (annexOf spend)) $ Left "nodes do not relay an annex"
+      let schnorr sigBytes leaf = do
             TaprootSignature sig sh <- decodeTaprootSig sigBytes
-            h <- taprootSigHash tx spentOutputs i sh annex leaf
+            h <- taprootSigHashWith hashes i sh Nothing leaf
             return (sig, h)
-      case viewTaprootWitness ws of
-        Just (KeyPathSpend sigBytes annex) -> do
-          (sig, h) <- schnorr sigBytes annex Nothing
+      case spend of
+        KeyPathSpend sigBytes _ -> do
+          (sig, h) <- schnorr sigBytes Nothing
           return (verifySchnorr outKey sig (hashToMsg h))
-        Just (ScriptPathSpend spd) -> case (spd.script.ops, spd.stack) of
+        ScriptPathSpend spd -> case (spd.script.ops, spd.stack) of
           ([OP_PUSHDATA keyBytes OPCODE, OP_CHECKSIG], [sigBytes])
             | spd.leafVersion == tapscriptLeafVersion -> do
                 leafKey <- maybe (Left "not an x-only key") Right (importXOnlyPubKey keyBytes)
-                (sig, h) <- schnorr sigBytes spd.annex (Just (leafHash spd.leafVersion spd.script, 0xffffffff))
+                (sig, h) <- schnorr sigBytes (Just (leafHash spd.leafVersion spd.script, 0xffffffff))
                 return (verifyScriptPathData outKey spd && verifySchnorr leafKey sig (hashToMsg h))
           -- The multisig of Taproot, @multi_a@ of the output descriptors:
           -- a key and OP_CHECKSIG, then a key and OP_CHECKSIGADD for each
@@ -964,15 +1103,18 @@
                       | B.null sigBytes = Right False
                       | otherwise = do
                           key <- maybe (Left "not an x-only key") Right (importXOnlyPubKey keyBytes)
-                          (sig, h) <- schnorr sigBytes spd.annex leaf
+                          (sig, h) <- schnorr sigBytes leaf
                           if verifySchnorr key sig (hashToMsg h)
                             then Right True
                             else Left "a signature that does not verify"
                 signed <- sequence (zipWith signs keys (reverse items))
                 return (verifyScriptPathData outKey spd && length (filter id signed) == asked)
           _ -> Left "script path spends other than key checks are not verified"
-        Nothing -> Left "not a Taproot witness"
 
+    annexOf :: TaprootWitness -> Maybe B.ByteString
+    annexOf (KeyPathSpend _ annex) = annex
+    annexOf (ScriptPathSpend spd) = spd.annex
+
 -- | What can be said of the signature of an input without running its
 -- script.
 data InputVerdict
@@ -984,7 +1126,10 @@
     -- the transaction
     InputForged
   | -- | neither: a script that is not run here, a coin that was not
-    -- given, a hash type other than all, an encoding that is not read
+    -- given, a hash type other than all, an encoding that is not read,
+    -- without a fork id an input that 'verifyStdInput' refuses although
+    -- its signature verifies, and on Bitcoin Cash an input in an encoding
+    -- that no block holds
     InputUndecided
   deriving (Eq, Show)
 
@@ -1004,14 +1149,68 @@
 --   not by a script;
 -- * with exactly the items such an input has, and a hash type of all;
 -- * whose key is not the one the coin names, or whose signature does not
---   verify over the digest.
+--   verify over the digest. An item that an opcode of its own pushes, such
+--   as the empty item of @OP_0@, is not the key either.
 --
+-- To find a forged input, an input that 'verifyStdInput' refuses is read a
+-- second time. Without a fork id that reading takes more than a node
+-- does: any form of push, a signature with a high S, a hybrid key. So it
+-- is not trusted to say that an input is good. On a network without a
+-- fork id, 'InputVerified' is the answer of 'verifyStdInput' and of
+-- nothing else.
+-- An input whose signature verifies and that 'verifyStdInput' refuses is
+-- 'InputUndecided' there: one that a block may hold and that nodes do not
+-- relay, such as a high S, a longer push or an uncompressed key in a
+-- SegWit input, and one that no block holds, such as a witness
+-- program nested in a script hash that is not pushed by its length (BIP
+-- 141). The other way, a guard in the second reading for each such form,
+-- lets a form that was forgotten pass as verified.
+--
 -- On Bitcoin Cash it reads what 'verifyStdInput' does not: a Schnorr
 -- signature ('verifyCashSchnorr'), of one key or in a multisig, bare or in
 -- a script hash, and a coin that holds tokens, whose digest covers them
 -- ('txSigHashCashToken'). Inputs of those kinds are 'InputVerified' here
 -- and not by 'verifyStdInput'. A multisig is never 'InputForged': one
--- that does not verify is 'InputUndecided'.
+-- that does not verify is 'InputUndecided'. The field of bits of a
+-- multisig with Schnorr signatures is read in the shortest push of it,
+-- which is an opcode of its own for the bytes 0x01 to 0x10 and for 0x81
+-- (@OP_1NEGATE@): the first key and the last of eight.
+--
+-- A signature of 64 bytes before its hash type byte is always read as a
+-- Schnorr signature, as a node reads it. A valid ECDSA signature whose DER
+-- form has that length does not verify as one, so the spend of a coin of
+-- one key with it is 'InputForged'.
+--
+-- So on Bitcoin Cash the second reading does say 'InputVerified', and it
+-- must take no more than a block does. Bitcoin Cash applies to every block
+-- three rules of encoding that Bitcoin applies only to what it relays.
+-- They are among the @MANDATORY_SCRIPT_VERIFY_FLAGS@ of Bitcoin Cash Node,
+-- which drops the peer that sends a transaction that breaks one:
+--
+-- * the S of an ECDSA signature is low (@LOW_S@, 'isCanonicalHalfOrder');
+-- * a key is compressed or uncompressed, and not hybrid (@STRICTENC@,
+--   'decodePubKey');
+-- * the input script pushes each item by the shortest push that holds it
+--   (@MINIMALDATA@, 'isMinimalPush').
+--
+-- An input that breaks one of them is 'InputUndecided' on Bitcoin Cash,
+-- also when its signature does not verify. This is the way of the guards
+-- that the paragraph above warns about, and the only one as long as
+-- 'verifyStdInput' does not read these inputs: a kind of input that the
+-- second reading learns must come with the rules that a block of Bitcoin
+-- Cash applies to it.
+--
+-- A coin locked to a multisig script whose keys are not direct pushes, or
+-- to the hash of one, is 'InputUndecided' on every network: 'decodeOutput'
+-- does not read that script. On Bitcoin Cash no block holds a spend of
+-- such a coin.
+--
+-- __Cost.__ The time grows with the size of the transaction, and not with
+-- its square: each coin is looked up once, and the hashes that the digests
+-- of the inputs share are computed once ('TxSigHashes' for SegWit version 0
+-- and for a network with a fork id, 'TaprootTxHashes' for Taproot). A
+-- legacy input of Bitcoin is the exception: its digest hashes a copy of
+-- the whole transaction, in Bitcoin Core too.
 judgeInputs :: Network -> Tx -> [Maybe TxOut] -> [InputVerdict]
 judgeInputs net tx given = zipWith judge [0 ..] decoded
   where
@@ -1027,14 +1226,26 @@
       return (prefix, so, o.value)
     spent =
       SpentCoins
-        { coins = [d >>= \(prefix, so, v) -> if B.null prefix then Just (so, v) else Nothing | d <- decoded],
-          outputs = sequence prevs
+        { coins = V.fromList (map (>>= withoutTokens) decoded),
+          spends = V.fromList (Sign.inputSpends tx),
+          sigHashes = txSigHashes tx,
+          taproot = sharedHashes tx =<< sequence prevs
         }
+    -- 'verifyInput' reads no coin that holds tokens
+    withoutTokens (prefix, so, v) = if B.null prefix then Just (so, v) else Nothing
+    -- What the second reading of an input may answer. Without a fork id
+    -- it does not say verified: 'verifyInput' reads every kind of input
+    -- that is verified there, and the second reading only looks for a
+    -- forged one. It takes forms that 'verifyInput' refuses, and among
+    -- them some that no block holds.
+    secondReading :: InputVerdict -> InputVerdict
+    secondReading InputVerified | not forked = InputUndecided
+    secondReading answer = answer
     judge :: Int -> Maybe (B.ByteString, ScriptOutput, Word64) -> InputVerdict
     judge _ Nothing = InputUndecided
     judge i (Just (prefix, so, val))
-      | B.null prefix && verifyInput net tx spent i = InputVerified
-      | otherwise = case so of
+      | B.null prefix && verifyInput net spent i = InputVerified
+      | otherwise = secondReading $ case so of
           PayPKHash h
             | null ws, Just [sig, pub] <- pushes -> keyed (addressHash pub == h) sig pub legacy
           PayPK pub
@@ -1043,7 +1254,7 @@
             | net.segWit, B.null inp, [sig, pub] <- ws -> keyed (addressHash pub == h) sig pub (segwit so)
           PayScriptHash h
             | net.segWit,
-              Just [program] <- pushes,
+              Just program <- onlyPush,
               addressHash program == h,
               Right nested@(PayWitnessPKHash kh) <- decodeSerial program,
               [sig, pub] <- ws ->
@@ -1062,25 +1273,37 @@
                 cashMultisig redeem keys asked bits sigs
           _ -> InputUndecided
       where
-        inp = (tx.inputs !! i).script
-        ws = if length tx.witness > i then tx.witness !! i else []
-        -- the items of an input script that only pushes data
+        (inp, ws) = fromMaybe (B.empty, []) (spent.spends V.!? i)
+        -- The items of an input script that only pushes data, in a form
+        -- of push that a block holds. The empty item, a number from 1 to
+        -- 16 and the byte 0x81 are each pushed by an opcode of their own
+        -- ('pushOpData'): the field of bits of a multisig can be any of
+        -- the last two.
         pushes = case runGetS deserialize inp of
-          Right (Script ops) -> mapM pushed ops
-          Left _ -> Nothing
-        -- a small number is pushed by an opcode of its own
-        pushed = \case
-          OP_PUSHDATA d _ -> Just d
-          op -> B.singleton . fromIntegral <$> eitherToMaybe (scriptOpToInt op)
+          Right (Script ops) | blockHoldsPushes net inp -> mapM pushOpData ops
+          _ -> Nothing
+        -- the item of an input script that is one push by its length and
+        -- nothing else: the only form that a witness program nested in a
+        -- script hash may take (BIP 141)
+        onlyPush = case runGetS deserialize inp of
+          Right (Script [OP_PUSHDATA d OPCODE]) -> Just d
+          _ -> Nothing
         legacy sh = do
           script <- encodeOutput so
-          if forked then txSigHashCashToken net tx prefix script val i sh else txSigHash net tx script val i sh
-        segwit out sh = Sign.makeSigHash net tx i out val sh Nothing
+          if forked
+            then txSigHashCashTokenWith net spent.sigHashes prefix script val i sh
+            else txSigHashWith net spent.sigHashes script val i sh
+        segwit out sh = Sign.makeSigHashWith net spent.sigHashes i out val sh Nothing
         -- a coin that names the hash of its key: another key does not
         -- open it, whatever it signed
         keyed named sig pub digest
           | not named = InputForged
-          | otherwise = maybe InputUndecided (\k -> signed sig k digest) (importPubKey pub)
+          | otherwise = maybe InputUndecided (\k -> signed sig k digest) (keyOf pub)
+        -- The key of a signature check. Bitcoin takes a hybrid key in a
+        -- block. On Bitcoin Cash no block holds the check of one.
+        keyOf bytes
+          | forked = (.point) <$> eitherToMaybe (decodePubKey bytes)
+          | otherwise = importPubKey bytes
         -- Forged is said of the hash type "all" only. With another hash
         -- type a signature that verifies is verified, and one that does
         -- not is left alone.
@@ -1091,9 +1314,12 @@
               Right m
                 -- on Bitcoin Cash a signature of 64 bytes is a Schnorr one
                 | forked && B.length body == 64 -> sure (verifyCashSchnorr key body m)
-                | otherwise -> maybe InputUndecided (\s -> sure (verifyHashSig m s key)) (decodeStrictSig body)
+                | otherwise -> maybe InputUndecided (\s -> sure (verifyHashSig m s key)) (ecdsaSig body)
           where
             body = B.init sig
+            -- Bitcoin takes a high S in a block. On Bitcoin Cash no block
+            -- holds one, and 'verifyHashSig' verifies it like a low S.
+            ecdsaSig = mfilter (\s -> not forked || isCanonicalHalfOrder s) . decodeStrictSig
             sure ok
               | ok = InputVerified
               | B.last sig == (if forked then 0x41 else 0x01) = InputForged
@@ -1129,18 +1355,47 @@
                   (const False)
                   (verifyCashSchnorr key.point (B.init sig))
                   (encodeOutput script >>= \code -> cashDigest code (fromIntegral (B.last sig)))
-            cashDigest code = txSigHashCashToken net tx prefix code val i
+            cashDigest code = txSigHashCashTokenWith net spent.sigHashes prefix code val i
         taproot program sig = fromRight InputUndecided $ do
           key <- maybe (Left "not a key") Right (importXOnlyPubKey program)
-          outs <- maybe (Left "a spent output is missing") Right spent.outputs
+          hashes <- maybe (Left "a spent output is missing") Right spent.taproot
           TaprootSignature s sh <- decodeTaprootSig sig
           unless (sh == sigHashDefault || sh == sigHashAll) $ Left "another hash type"
-          m <- taprootSigHash tx outs i sh Nothing Nothing
+          m <- taprootSigHashWith hashes i sh Nothing Nothing
           return (verdict (verifySchnorr key s (hashToMsg m)))
         verdict ok = if ok then InputVerified else InputForged
 
+-- | Does an input script only push data, each item by the shortest push
+-- that holds it ('isMinimalPush')? These are the @SIGPUSHONLY@ and
+-- @MINIMALDATA@ rules. Bitcoin Cash applies them to every block. On
+-- Bitcoin they are rules of the relay policy: a block may hold a longer
+-- push, and nodes do not relay it.
+minimalPushes :: B.ByteString -> Bool
+minimalPushes script = case runGetS deserialize script of
+  Right (Script ops) -> all isMinimalPush ops
+  Left _ -> False
+
+-- | Can a block of the network hold an input script that pushes its items
+-- as this one does? On Bitcoin any script passes. On Bitcoin Cash the
+-- script must keep the rules of 'minimalPushes'. A network of Bitcoin
+-- Cash is one whose signatures commit to a fork id.
+blockHoldsPushes :: Network -> B.ByteString -> Bool
+blockHoldsPushes net script = isNothing net.sigHashForkId || minimalPushes script
+
+-- | The most keys that a Taproot multisig script can have and still be
+-- spent: @MAX_PUBKEYS_PER_MULTI_A@ of Bitcoin Core, and the limit of
+-- @multi_a@ in BIP 387. 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: 999 + 1 = 1000. A
+-- limit of 1000 witness items would not do: with 1000 keys the witness is
+-- allowed, and that first push is not.
+maxTaprootMultisigKeys :: Int
+maxTaprootMultisigKeys = 999
+
 -- | The keys of a Taproot multisig script and the number of signatures it
--- asks for, if the script is one: see 'verifyStdInput'.
+-- asks for, if the script is one: see 'verifyStdInput'. A script of more
+-- than 'maxTaprootMultisigKeys' keys is not one, since no block can hold
+-- a spend of it.
 multiA :: [ScriptOp] -> Maybe ([B.ByteString], Int)
 multiA (OP_PUSHDATA first OPCODE : OP_CHECKSIG : rest) = go [first] rest
   where
@@ -1148,6 +1403,7 @@
     go keys [number, OP_NUMEQUAL]
       | Right asked <- scriptOpToInt number,
         asked <= length keys,
+        length keys <= maxTaprootMultisigKeys,
         all ((== 32) . B.length) keys =
           Just (reverse keys, asked)
     go _ _ = Nothing
diff --git a/src/Haskoin/Transaction/Builder/Sign.hs b/src/Haskoin/Transaction/Builder/Sign.hs
--- a/src/Haskoin/Transaction/Builder/Sign.hs
+++ b/src/Haskoin/Transaction/Builder/Sign.hs
@@ -21,12 +21,15 @@
 module Haskoin.Transaction.Builder.Sign
   ( SigInput (..),
     makeSignature,
+    makeSignatureWith,
     makeSigHash,
+    makeSigHashWith,
     signTx,
     findInputIndex,
     signInput,
     signTaprootInput,
     buildInput,
+    inputSpends,
     sigKeys,
   )
 where
@@ -43,7 +46,9 @@
 import Data.Either
 import Data.Hashable
 import Data.List
+import qualified Data.Map.Strict as Map
 import Data.Maybe
+import qualified Data.Vector as V
 import Data.Word
 import GHC.Generics
 import Haskoin.Address
@@ -134,6 +139,15 @@
 -- (@SCRIPT_VERIFY_WITNESS_PUBKEYTYPE@ in Bitcoin Core), although a block
 -- may hold it. 'signInput' signs with the key it is given, in the form it
 -- is given.
+--
+-- An input signed with 'SIGHASH_SINGLE' needs an output at its index, or
+-- the whole call fails: see 'signInput'.
+--
+-- The hashes that the digests of the inputs share are computed once for the
+-- transaction ('TxSigHashes' for SegWit version 0 and for a network with a
+-- fork id, 'TaprootTxHashes' for Taproot), and not once for each input. A
+-- legacy input of Bitcoin shares nothing: its digest hashes a copy of the
+-- whole transaction, in Bitcoin Core too.
 signTx ::
   Network ->
   -- | transaction to sign
@@ -146,31 +160,94 @@
   Either String Tx
 signTx net otx sigis allKeys
   | null ti = Left "signTx: Transaction has no inputs"
-  | otherwise = foldM go otx $ findInputIndex ((.outpoint) . fst) sigis ti
+  | otherwise = do
+      signed <- forM (zip [0 ..] (inputSpends otx)) $ \(i, spend) ->
+        maybe (Right (spend, False)) (go i spend) (Map.lookup i found)
+      let spends = map fst signed
+      return
+        otx
+          { inputs = zipWith (\TxIn {..} (signedScript, _) -> TxIn {script = signedScript, ..}) ti spends,
+            witness = if any snd signed then map snd spends else otx.witness
+          }
   where
     ti = otx.inputs
+    -- The signing parameters of each input, by its index
+    found = Map.fromList [(i, sigi) | (sigi, i) <- findInputIndex ((.outpoint) . fst) sigis ti]
     -- The public keys of the secret keys are derived once for the whole
     -- transaction, not once per input
     index = keyIndex allKeys
-    go tx (sigi@(SigInput so _ _ sh rdmM, _), i) = do
+    -- An input signed with the keys that its coin asks for, and whether
+    -- that gave it a witness. Each input is signed on its own input script
+    -- and witness stack, and the transaction is put together once: its
+    -- lists would be walked up to the input for each signature.
+    go i spend (sigi@(SigInput so _ _ sh rdmM, _)) = do
       keys <- indexedSigKeys index so rdmM
       if isTaprootOutput so
         then do
           unless net.segWit $ Left "signTx: this network has no Taproot"
-          spent <- spentOutputs
-          foldM (\t k -> signTaprootInput t spent i sh k.key) tx keys
-        else foldM (\t k -> signInput net t i sigi k) tx keys
+          (spent, hashes) <- taprootCoins
+          let digest = taprootSigHashWith hashes i sh Nothing Nothing
+              sign (script, _) k = do
+                stack <- digest >>= taprootKeyWitness sh k.key (spent V.! i)
+                when wrongStackCount $ Left "signTaprootInput: Invalid number of witness stacks"
+                return (script, stack)
+          signedSpend <- foldM sign spend keys
+          return (signedSpend, not (null keys))
+        else do
+          let sign s k = do
+                s' <- signSpend net sigHashes i sigi k s
+                when (isSegwit so && wrongStackCount) $ Left "Invalid number of witness stacks"
+                return s'
+          signedSpend <- foldM sign spend keys
+          return (signedSpend, isSegwit so && not (null keys))
+    -- A transaction that has witness stacks must have one for each input
+    wrongStackCount = not (null otx.witness) && length otx.witness /= length ti
+    -- What the digests of the inputs share. No digest commits to an input
+    -- script or to a witness, so the hashes of the unsigned transaction
+    -- hold while its inputs are signed.
+    sigHashes = txSigHashes otx
     -- The outputs every input spends, which a Taproot signature commits
-    -- to: a nested SegWit program is spent as its P2SH wrapper
+    -- to, and the hashes that the digests of the Taproot inputs share.
+    taprootCoins = do
+      spent <- spentOutputs
+      hashes <- taprootTxHashes otx spent
+      return (V.fromList spent, hashes)
+    -- A nested SegWit program is spent as its P2SH wrapper
     spentOutputs =
       forM ti $ \txin ->
-        case find ((== txin.outpoint) . (.outpoint) . fst) sigis of
+        case Map.lookup txin.outpoint parameters of
           Just (s, nested) -> (\so -> TxOut s.value (encodeSerial so)) <$> coinScript s nested
           Nothing -> Left "signTx: a Taproot signature needs the output every input spends"
+    -- The signing parameters of each outpoint: the first given for it
+    parameters = Map.fromListWith (\_ first -> first) [(s.outpoint, (s, nested)) | (s, nested) <- sigis]
     coinScript s nested
       | nested && isSegwit s.script = toP2SH =<< encodeOutput s.script
       | otherwise = Right s.script
 
+-- | The input script and the witness stack of each input of a transaction,
+-- in order: what signing an input changes. The stack is empty when the
+-- transaction has no stack for the input.
+inputSpends :: Tx -> [(B.ByteString, WitnessStack)]
+inputSpends tx = zip (map (.script) tx.inputs) (tx.witness <> repeat [])
+
+-- | The input script and the witness stack of one input. An index that the
+-- transaction does not have gives empty ones: the digest refuses it.
+inputSpend :: Tx -> Int -> (B.ByteString, WitnessStack)
+inputSpend tx i
+  | i < 0 = (B.empty, [])
+  | otherwise = fromMaybe (B.empty, []) (listToMaybe (drop i (inputSpends tx)))
+
+-- | The witness of a transaction with the stack of one input replaced. A
+-- transaction without witness gets an empty stack for every other input.
+-- Fails with the message when it has stacks, and not one for each input.
+withStack :: String -> Tx -> Int -> WitnessStack -> Either String WitnessData
+withStack wrongCount tx i stack
+  | null tx.witness = Right (updateIndex i (replicate n []) (const stack))
+  | length tx.witness /= n = Left wrongCount
+  | otherwise = Right (updateIndex i tx.witness (const stack))
+  where
+    n = length tx.inputs
+
 -- | Whether the output is a Taproot output: a witness program of version 1
 -- that is 32 bytes long
 isTaprootOutput :: ScriptOutput -> Bool
@@ -189,6 +266,10 @@
 -- input spends is not a Taproot output, or when the secret key is not the
 -- key of that output: a signature of another key would make a transaction
 -- that no node accepts.
+--
+-- This signs one input, and its digest hashes the whole transaction
+-- ('taprootSigHash'). 'signTx' signs every input of a transaction with the
+-- hashes that their digests share computed once.
 signTaprootInput ::
   Tx ->
   -- | outputs spent, one per input
@@ -202,18 +283,22 @@
 signTaprootInput tx spent i sh secret = do
   -- The digest checks the index and the number of spent outputs
   h <- taprootSigHash tx spent i sh Nothing Nothing
-  outputKey <- case B.unpack (spent !! i).script of
+  stack <- taprootKeyWitness sh secret (spent !! i) h
+  stacks <- withStack "signTaprootInput: Invalid number of witness stacks" tx i stack
+  return tx {witness = stacks}
+
+-- | The witness of a Taproot input spent by its key path: the signature of
+-- the digest of the input, which the caller computed for the hash type,
+-- by the secret key of the output that the input spends
+taprootKeyWitness :: SigHash -> SecKey -> TxOut -> Hash256 -> Either String WitnessStack
+taprootKeyWitness sh secret coin h = do
+  outputKey <- case B.unpack coin.script of
     0x51 : 0x20 : program | length program == 32 -> Right (B.pack program)
     _ -> Left "signTaprootInput: the output spent is not a Taproot output"
   unless (exportXOnlyPubKey (derivePubKey secret) == outputKey) $
     Left "signTaprootInput: the key is not the key of the output"
   signature <- taprootSignature (signSchnorr secret (hashToMsg h)) sh
-  let stacks
-        | null tx.witness = replicate (length tx.inputs) []
-        | otherwise = tx.witness
-  unless (length stacks == length tx.inputs) $
-    Left "signTaprootInput: Invalid number of witness stacks"
-  return tx {witness = updateIndex i stacks (const [encodeTaprootSig signature])}
+  return [encodeTaprootSig signature]
 
 -- | Sign a single input in a transaction deterministically (RFC-6979).  The
 -- nesting flag only affects the behavior of segwit inputs.
@@ -223,7 +308,17 @@
 -- multisig. Any other key fails, since its signature would make an input
 -- that no node accepts. The key is used in the form given, compressed or
 -- not. That is the way to spend a SegWit coin of an uncompressed key on
--- purpose, which 'signTx' refuses.
+-- purpose, which 'signTx' refuses. Nodes do not relay that spend, so
+-- 'Haskoin.Transaction.Builder.verifyStdInput' answers 'False' for it.
+--
+-- An input signed with 'SIGHASH_SINGLE' at an index that has no output is
+-- refused, whatever its coin. That signature commits to no output, as one
+-- of 'SIGHASH_NONE' does. No BIP has a rule for a signer here, and the
+-- transaction signer of Bitcoin Core makes no such signature
+-- (@SignTransaction@: "Only sign SIGHASH_SINGLE if there's a corresponding
+-- output"), nor does the one of Bitcoin Cash Node. 'makeSignature' gives
+-- the signature of a SegWit coin and of a coin of Bitcoin Cash to a caller
+-- that wants it.
 signInput ::
   Network ->
   Tx ->
@@ -232,23 +327,38 @@
   (SigInput, Bool) ->
   PrivateKey ->
   Either String Tx
-signInput net tx i (sigIn@(SigInput so val _ _ rdmM), nest) key = do
+signInput net tx i sigi@(SigInput so _ _ _ _, _) key = do
+  (signedScript, stack) <- signSpend net (txSigHashes tx) i sigi key (inputSpend tx i)
+  stacks <- if isSegwit so then withStack "Invalid number of witness stacks" tx i stack else Right tx.witness
+  return tx {inputs = updateIndex i tx.inputs (\TxIn {..} -> TxIn {script = signedScript, ..}), witness = stacks}
+
+-- | 'signInput' on the input script and the witness stack of the input,
+-- with what the digests of the inputs share. It gives the two as the
+-- signature leaves them. The hashes are those of the transaction before
+-- any input was signed, which hold for it afterwards: see 'TxSigHashes'.
+signSpend ::
+  Network ->
+  TxSigHashes ->
+  Int ->
+  (SigInput, Bool) ->
+  PrivateKey ->
+  (B.ByteString, WitnessStack) ->
+  Either String (B.ByteString, WitnessStack)
+signSpend net hashes i (sigIn@(SigInput so val _ sh rdmM), nest) key spend@(script, stack) = do
   when (isTaprootOutput so) $
     Left "signInput: a Taproot input is signed with signTaprootInput"
+  when (isSigHashSingle sh && i >= length (sigHashesTx hashes).outputs) $
+    Left "signInput: SIGHASH_SINGLE without an output at the input index"
   let pub = derivePublicKey key
   unless (keyOfCoin so rdmM pub) $
     Left "signInput: the key is not a key of the coin"
-  sig <- makeSignature net tx i sigIn key
-  si <- buildInput net tx i so val rdmM sig pub
-  w <- updatedWitnessData net tx i so si
-  return tx {inputs = nextTxIn so si, witness = w}
-  where
-    f si TxIn {..} = TxIn {script = marshal net si, ..}
-    g so' = f (NestedWitnessInput so')
-    nextTxIn so' si
-      | isSegwit so' && nest = updateIndex i tx.inputs (g so')
-      | isSegwit so' = tx.inputs
-      | otherwise = updateIndex i tx.inputs (f si)
+  sig <- makeSignatureWith net hashes i sigIn key
+  si <- spendInput net hashes i so val rdmM sig pub spend
+  if isSegwit so
+    then do
+      signedStack <- toWitnessStack net <$> calcWitnessProgram net so si
+      return (if nest then marshal net (NestedWitnessInput so) else script, signedStack)
+    else return (marshal net si, stack)
 
 -- | Whether the public key is one that the coin asks a signature of
 keyOfCoin :: ScriptOutput -> Maybe RedeemScript -> PublicKey -> Bool
@@ -263,29 +373,6 @@
   where
     keyHash = addressHash (encodeSerial pub)
 
--- | Add the witness data of the transaction given segwit parameters for an input.
---
--- @since 0.11.0.0
-updatedWitnessData ::
-  Network ->
-  Tx ->
-  Int ->
-  ScriptOutput ->
-  ScriptInput ->
-  Either String WitnessData
-updatedWitnessData net tx i so si
-  | isSegwit so =
-      updateWitness . toWitnessStack net =<< calcWitnessProgram net so si
-  | otherwise =
-      return tx.witness
-  where
-    updateWitness w
-      | null tx.witness = return $ updateIndex i defaultStack (const w)
-      | length tx.witness /= n = Left "Invalid number of witness stacks"
-      | otherwise = return $ updateIndex i tx.witness (const w)
-    defaultStack = replicate n $ toWitnessStack net EmptyWitnessProgram
-    n = length tx.inputs
-
 -- | Associate an input index to each value in a list
 findInputIndex ::
   -- | extract an outpoint
@@ -392,6 +479,23 @@
   Either String ScriptInput
 buildInput net tx i so val rdmM sig pub = do
   when (i < 0 || i >= length tx.inputs) $ Left "buildInput: Invalid input index"
+  spendInput net (txSigHashes tx) i so val rdmM sig pub (inputSpend tx i)
+
+-- | 'buildInput' on the input script and the witness stack of the input,
+-- which hold the signatures that a multisig input has already, with what
+-- the digests of the inputs share: see 'signSpend'
+spendInput ::
+  Network ->
+  TxSigHashes ->
+  Int ->
+  ScriptOutput ->
+  Word64 ->
+  Maybe RedeemScript ->
+  TxSignature ->
+  PublicKey ->
+  (B.ByteString, WitnessStack) ->
+  Either String ScriptInput
+spendInput net hashes i so val rdmM sig pub spend = do
   when (isTaprootOutput so) $ Left "buildInput: a Taproot input has no input script"
   case (so, rdmM) of
     (PayScriptHash _, Just rdm) ->
@@ -409,7 +513,7 @@
       PayPKHash _ -> return $ RegularInput $ SpendPKHash sig pub
       PayMulSig msPubs r -> do
         let mSigs = take r $ catMaybes $ matchTemplate allSigs msPubs f
-            allSigs = nub $ sig : parseExistingSigs net tx so i
+            allSigs = nub $ sig : existingSigs net so spend
         return $ RegularInput $ SpendMulSig mSigs
       _ -> Left "buildInput: Invalid output/redeem script combination"
     buildScriptHashInput rdm = do
@@ -417,25 +521,21 @@
       return $ ScriptHashInput inp.get rdm
     f (TxSignature x sh) p =
       either (const False) (\m -> verifyHashSig m x p.point) $
-        makeSigHash net tx i so val sh rdmM
+        makeSigHashWith net hashes i so val sh rdmM
     f TxSignatureEmpty _ = False
 
--- | Apply heuristics to extract the signatures for a particular input that are
--- embedded in the transaction.
---
--- @since 0.11.0.0
-parseExistingSigs :: Network -> Tx -> ScriptOutput -> Int -> [TxSignature]
-parseExistingSigs net tx so i = insSigs <> witSigs
+-- | Apply heuristics to extract the signatures that an input holds, in its
+-- input script and in its witness stack.
+existingSigs :: Network -> ScriptOutput -> (B.ByteString, WitnessStack) -> [TxSignature]
+existingSigs net so (script, stack) = insSigs <> witSigs
   where
-    insSigs = case unmarshal net scp of
+    insSigs = case unmarshal net script of
       Right (ScriptHashInput (SpendMulSig xs) _) -> xs
       Right (RegularInput (SpendMulSig xs)) -> xs
       _ -> []
-    scp = (tx.inputs !! i).script
     witSigs
       | not $ isSegwit so = []
-      | length tx.witness <= i = []
-      | otherwise = rights $ decodeTxSig net <$> (tx.witness !! i)
+      | otherwise = rights $ decodeTxSig net <$> stack
 
 -- | Produce a structured representation of a deterministic (RFC-6979)
 -- signature over an input. On a network with a fork id, such as Bitcoin
@@ -456,6 +556,12 @@
 --   hash to the coin. The same for a pay-to-witness-script-hash coin and
 --   its witness script, with 'maxWitnessScriptSize'.
 -- * A SegWit coin on a network without SegWit.
+-- * On a network with a fork id, a signature that comes out 64 bytes long
+--   ('isCashSchnorrLength'). Bitcoin Cash reads that length as a Schnorr
+--   signature, so no node takes the transaction. The nonce is that of RFC
+--   6979, so the same key and digest give the same signature again: the
+--   caller changes the transaction, its fee for instance, and signs again.
+--   The specification of Bitcoin Cash gives one chance in 2^49 for this.
 --
 -- A legacy input signed with 'SIGHASH_SINGLE' at an index that has no
 -- output is refused. The digest of that case is the constant 1, which
@@ -464,11 +570,23 @@
 -- in @SignatureHash@, and so does 'txSigHash', since a node must verify
 -- such signatures; a signer has no reason to make one. The BIP 143 digest
 -- of a SegWit input and the fork id digest of Bitcoin Cash commit to the
--- coin in that case, so those are signed.
+-- coin in that case, so those are signed here, as the PSBT signer of
+-- Bitcoin Core signs them. 'signInput' and 'signTx' refuse them too, as
+-- its transaction signer does.
 --
 -- The key is not checked against the coin here: 'signInput' does that.
+--
+-- This is the function for one signature. For the signatures of several
+-- inputs of one transaction, 'makeSignatureWith' does not hash the
+-- transaction again for each of them.
 makeSignature :: Network -> Tx -> Int -> SigInput -> PrivateKey -> Either String TxSignature
-makeSignature net tx i (SigInput so val _ sh rdmM) key = do
+makeSignature net = makeSignatureWith net . txSigHashes
+
+-- | 'makeSignature' for the transaction of the 'TxSigHashes', from the
+-- hashes that the digests of its inputs share. It gives the signature that
+-- 'makeSignature' gives, and fails as it does.
+makeSignatureWith :: Network -> TxSigHashes -> Int -> SigInput -> PrivateKey -> Either String TxSignature
+makeSignatureWith net hashes i (SigInput so val _ sh rdmM) key = do
   when (isSegwit so && not net.segWit) $
     Left "makeSignature: this network has no SegWit"
   when (sh > 0xff) $
@@ -481,10 +599,15 @@
     Left $
       "makeSignature: the hash type " <> shown <> " is not one a node accepts"
   committedScript
-  m <- makeSigHash net tx i so val sh' rdmM
-  when (signsConstantDigest && i >= length tx.outputs) $
+  m <- makeSigHashWith net hashes i so val sh' rdmM
+  when (signsConstantDigest && i >= length (sigHashesTx hashes).outputs) $
     Left "makeSignature: SIGHASH_SINGLE without an output at the input index"
-  return $ TxSignature (signHash key.key m) sh'
+  let sig = signHash key.key m
+  when (isJust net.sigHashForkId && isCashSchnorrLength sig) $
+    Left
+      "makeSignature: the signature is 64 bytes long, which this network reads as a Schnorr signature: \
+      \change the transaction and sign again"
+  return $ TxSignature sig sh'
   where
     shown = show (toInteger sh)
     sh'
@@ -518,15 +641,29 @@
   SigHash ->
   Maybe RedeemScript ->
   Either String Hash256
-makeSigHash net tx i so val sh rdmM = do
+makeSigHash net = makeSigHashWith net . txSigHashes
+
+-- | 'makeSigHash' for the transaction of the 'TxSigHashes', from the
+-- hashes that the digests of its inputs share. It gives the digest that
+-- 'makeSigHash' gives, and fails as it does.
+makeSigHashWith ::
+  Network ->
+  TxSigHashes ->
+  Int ->
+  ScriptOutput ->
+  Word64 ->
+  SigHash ->
+  Maybe RedeemScript ->
+  Either String Hash256
+makeSigHashWith net hashes i so val sh rdmM = do
   when (isTaprootOutput so) $
     Left "makeSigHash: the digest of a Taproot input is taprootSigHash"
   script <- encodeOutput so'
-  h net tx script val i sh
+  h net hashes script val i sh
   where
     so' = case so of
       PayWitnessPKHash h' -> PayPKHash h'
       _ -> fromMaybe so rdmM
     h
-      | isSegwit so = txSigHashForkId
-      | otherwise = txSigHash
+      | isSegwit so = txSigHashForkIdWith
+      | otherwise = txSigHashWith
diff --git a/src/Haskoin/Transaction/Judge.hs b/src/Haskoin/Transaction/Judge.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Transaction/Judge.hs
@@ -0,0 +1,467 @@
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE NamedFieldPuns #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- |
+-- Module      : Haskoin.Transaction.Judge
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- What a program that is no full node can say of a transaction: whether a
+-- node would take it, as far as that can be told without running a script.
+--
+-- = The problem
+--
+-- A full node checks a transaction by running the script of every coin
+-- that it spends. This library has no interpreter of scripts. But most of
+-- what makes a transaction bad needs none: a coin that is not there, more
+-- paid than is held, a lock time that has not passed, tokens made from
+-- nothing, and the signature of a coin that is locked to one key, which
+-- is most coins. A program that indexes the chain, relays transactions or
+-- builds them can check all of that, and say of the rest that it does not
+-- know.
+--
+-- = Two questions
+--
+-- * 'judge': somebody wants to __publish__ this transaction. Would a node
+--   relay it? This holds the transaction to the rules of the chain and to
+--   the rules of relay that have not changed in years, since handing a
+--   node a transaction that it refuses can cost the connection to it.
+--
+-- * 'judgeRelayed': a peer __sent__ this transaction, as one that its
+--   node took. Could a node have taken it? This holds it only to what no
+--   node can take whatever its policy, since the policy of a node is its
+--   own, and a transaction that some node relays must not be refused for
+--   breaking the policy of another.
+--
+-- Both answer in three ways: refused, with the reason ('Refusal'); good,
+-- with every signature verified; or good as far as can be told, with the
+-- first input that could not be judged. The third is not a polite refusal:
+-- a spend of a coin locked by a script is a normal transaction, and only a
+-- full node can say whether it is good. What to do with it is for the
+-- caller to decide, and depends on who vouches for the transaction.
+--
+-- = What this is not
+--
+-- 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. And nothing here looks at a mempool.
+--
+-- The names of this module are not exported by "Haskoin" or by
+-- "Haskoin.Transaction": @Coin@ is already the name of a class there
+-- ("Haskoin.Transaction.Builder"), and names as short as 'Spent' and
+-- 'Missing' are best imported on purpose.
+module Haskoin.Transaction.Judge
+  ( -- * A transaction to publish
+    judge,
+    Rules (..),
+    rulesAt,
+    Coin (..),
+
+    -- * A transaction that a peer sent
+    judgeRelayed,
+
+    -- * Why not
+    Refusal (..),
+
+    -- * The rules of relay
+    maxTxSize,
+    maxStandardSize,
+    isDust,
+
+    -- * The tokens of Bitcoin Cash
+    tokenRules,
+  )
+where
+
+import Control.Monad (forM_, unless, when)
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as B
+import Data.HashMap.Strict qualified as HashMap
+import Data.List (partition)
+import Data.Maybe (isJust, listToMaybe)
+import Data.Serialize (decode, encode)
+import Data.String.Conversions (cs)
+import Data.Word (Word32, Word64, Word8)
+import Haskoin.Block.Common (BlockHeight)
+import Haskoin.Network.Data (Network (..))
+import Haskoin.Script.CashToken (NFToken (..), TokenData (..), splitTokenData)
+import Haskoin.Script.Common (Script (..), isMinimalPush, isPushOp)
+import Haskoin.Transaction.Builder (InputVerdict (..), judgeInputs)
+import Haskoin.Transaction.Common
+  ( OutPoint (..),
+    Tx (..),
+    TxHash,
+    TxIn (..),
+    TxOut (..),
+    nullOutPoint,
+    txHashToHex,
+  )
+
+-- | An output that a transaction spends, as whoever judges it knows it.
+data Coin
+  = -- | it is there to spend, or only an unconfirmed transaction spends
+    -- it
+    Coin
+      { -- | the output, as it is in the transaction that made it
+        output :: !TxOut,
+        -- | the height of the block that confirmed it, if one did
+        mined :: !(Maybe BlockHeight),
+        -- | whether a coinbase made it
+        coinbase :: !Bool
+      }
+  | -- | a confirmed transaction has spent it
+    Spent !TxHash
+  | -- | it is not known
+    Missing
+  deriving (Eq, Show)
+
+-- | Why a transaction is refused. What 'show' says of each is written for
+-- the one who made the transaction.
+data Refusal
+  = TooLarge !Int
+  | NoInputs
+  | NoOutputs
+  | IsCoinbase
+  | DuplicateInput !OutPoint
+  | UnknownOutput !OutPoint
+  | SpentOutput !OutPoint !TxHash
+  | Overspent
+  | Immature !OutPoint
+  | NotFinal !Word32
+  | TooHeavy !Int
+  | Dust !Int
+  | Forged !Int
+  | BadVersion !Word32
+  | NotPushOnly !Int
+  | NotMinimal !Int
+  | BadTokens !Int
+  | TokensUnbacked !String
+  deriving (Eq)
+
+instance Show Refusal where
+  show (TooLarge n) = "The transaction is too large: " <> show n <> " bytes"
+  show NoInputs = "The transaction has no inputs"
+  show NoOutputs = "The transaction has no outputs"
+  show IsCoinbase = "A coinbase transaction cannot be published"
+  show (DuplicateInput o) = "The transaction spends the same output twice: " <> showOutPoint o
+  show (UnknownOutput o) = "The transaction spends an output that this server does not know: " <> showOutPoint o
+  show (SpentOutput o by) =
+    "The transaction spends an output that a confirmed transaction has spent: "
+      <> showOutPoint o
+      <> " by "
+      <> cs (txHashToHex by)
+  show Overspent = "The outputs of the transaction are worth more than its inputs"
+  show (Immature o) = "The transaction spends a coinbase that is not a hundred blocks old: " <> showOutPoint o
+  show (NotFinal lock) = "The lock time of the transaction has not passed: " <> show lock
+  show (TooHeavy n) = "The transaction is larger than nodes relay: " <> show n
+  show (Dust i) = "Output " <> show i <> " is worth less than it costs to spend, and nodes do not relay it"
+  show (Forged i) = "The signature of input " <> show i <> " does not verify"
+  show (BadVersion v) = "Nodes do not take a transaction of version " <> show v
+  show (NotPushOnly i) = "The script of input " <> show i <> " does more than push data"
+  show (NotMinimal i) = "The script of input " <> show i <> " pushes data in a longer form than it needs"
+  show (BadTokens i) = "The tokens of output " <> show i <> " are not written as tokens are"
+  show (TokensUnbacked c) = "The transaction gives tokens of category " <> c <> " that its inputs do not hold"
+
+showOutPoint :: OutPoint -> String
+showOutPoint o = cs (txHashToHex o.hash) <> ":" <> show o.index
+
+-- | The largest transaction that a block of the network can hold, in
+-- bytes. With SegWit a block weighs four million units at most, and a byte
+-- of witness weighs one, so a transaction that is nearly all witness comes
+-- close to four million bytes. Without it, the rule of Bitcoin Cash is a
+-- million bytes for a transaction.
+--
+-- Nodes relay far smaller ones only, a hundred thousand bytes or so. That
+-- rule is theirs to change ('maxStandardSize'): this is the
+-- size past which no node can take the transaction.
+maxTxSize :: Network -> Int
+maxTxSize net
+  | net.segWit = 4000000
+  | otherwise = 1000000
+
+-- | What is known of the chain and the network when a transaction is
+-- looked at.
+data Rules = Rules
+  { net :: !Network,
+    -- | what can be said of the signature of each input, given the
+    -- outputs they spend: 'judgeInputs', as 'rulesAt' sets it. A field,
+    -- so that a test can say what the verdicts are.
+    inputs :: !(Tx -> [TxOut] -> [InputVerdict]),
+    -- | height of the best block
+    height :: !BlockHeight,
+    -- | median of the times of the last eleven blocks, which is the time
+    -- that lock times are held to (BIP 113)
+    medianTime :: !Word64
+  }
+
+-- | What can be said of a transaction that somebody wants to publish,
+-- without a full node: given the coin of each input, in order.
+--
+-- Every check here is one whose answer a node would give too, and that
+-- does not depend on what else is in a mempool:
+--
+-- * __What makes it no transaction__: no inputs or outputs, an input
+--   twice, a coinbase, longer than a block can hold ('maxTxSize').
+-- * __The coins__: each input spends an output that is known, that
+--   no confirmed transaction has spent, and a coinbase only after a
+--   hundred blocks. The outputs are not worth more than the inputs.
+-- * __The lock time__ has passed, by height or by the median time, unless
+--   every input waives it.
+-- * __What nodes do not relay__: more than 'maxStandardSize', and an
+--   output so small that spending it costs more than it holds ('isDust').
+--   These are rules of relay and not of the chain; they are the ones that
+--   have not changed in years.
+-- * __Input scripts__ only push data, each push in its shortest form. On
+--   Bitcoin Cash that is a rule of the chain, and a node drops every
+--   connection of a peer that sends a transaction that breaks it.
+-- * __The version__: 1 or 2 on Bitcoin Cash, a rule of the chain there; 1
+--   to 3 on Bitcoin, which nodes relay.
+-- * __Tokens__ of Bitcoin Cash ('tokenRules'): written as tokens are, and
+--   given only as the inputs hold them. A node drops every connection of a
+--   peer that sends a transaction that breaks them.
+-- * __Signatures__, where there is no script to run: an input that spends
+--   a coin locked to one key with a signature that does not verify
+--   ('judgeInputs'). An input that is a script, or that cannot be read,
+--   is left to a node.
+--
+-- A conflict with an unconfirmed transaction is not a reason to refuse:
+-- whether one may replace the other is for the node to say, and the
+-- mempool of the caller may hold what the network has dropped. The fee is
+-- not checked either: what a node asks for changes with its mempool.
+--
+-- The answer for a transaction that passes says whether every signature
+-- was verified, or names the first input that could not be judged: a
+-- script, a hash type other than all. Such a transaction may be good, and
+-- only a full node can say.
+judge :: Rules -> Tx -> [Coin] -> Either Refusal (Maybe Int)
+judge rules tx coins = do
+  when (size > maxTxSize rules.net) $ Left (TooLarge size)
+  when (null tx.inputs) $ Left NoInputs
+  when (null tx.outputs) $ Left NoOutputs
+  when (any ((== nullOutPoint) . (.outpoint)) tx.inputs) $ Left IsCoinbase
+  mapM_ (Left . DuplicateInput) (firstDuplicate (map (.outpoint) tx.inputs))
+  unless (tx.version `elem` versions) $ Left (BadVersion tx.version)
+  mapM_ pushes (zip [0 ..] tx.inputs)
+  spent <- mapM known (zip (map (.outpoint) tx.inputs) coins)
+  when cash $ tokenRules tx spent
+  -- sums of 64-bit values: compared as integers, which do not wrap
+  unless (sum (map (toInteger . (.value)) spent) >= sum (map (toInteger . (.value)) tx.outputs)) $ Left Overspent
+  mapM_ mature (zip (map (.outpoint) tx.inputs) coins)
+  unless final $ Left (NotFinal tx.locktime)
+  when (heavy > maxStandardSize rules.net) $ Left (TooHeavy heavy)
+  mapM_ (Left . Dust) (take 1 [i | (i, o) <- zip [0 ..] tx.outputs, isDust rules.net o])
+  let verdicts = zip [0 ..] (rules.inputs tx spent)
+  mapM_ (Left . Forged) (take 1 [i | (i, InputForged) <- verdicts])
+  return (listToMaybe [i | (i, InputUndecided) <- verdicts])
+  where
+    cash = isJust rules.net.sigHashForkId
+    -- Bitcoin Cash takes versions 1 and 2 only, by its rules since May
+    -- 2023; Bitcoin Core relays those and version 3
+    versions
+      | cash = [1, 2]
+      | otherwise = [1, 2, 3]
+    -- an input script that only pushes data, each push in its shortest
+    -- form: rules of Bitcoin Cash, relay rules of Bitcoin Core
+    pushes :: (Int, TxIn) -> Either Refusal ()
+    pushes (i, input) = case decode input.script of
+      Right (Script ops)
+        | not (all isPushOp ops) -> Left (NotPushOnly i)
+        | not (all isMinimalPush ops) -> Left (NotMinimal i)
+        | otherwise -> Right ()
+      Left _ -> Left (NotPushOnly i)
+    size = B.length (encode tx)
+    -- what the limit of relay counts: weight with SegWit, bytes without
+    heavy
+      | rules.net.segWit = 3 * B.length (encode (tx {witness = []} :: Tx)) + size
+      | otherwise = size
+    known (_, Coin {output}) = Right output
+    known (o, Spent by) = Left (SpentOutput o by)
+    known (o, Missing) = Left (UnknownOutput o)
+    -- a coinbase can be spent in the hundredth block after its own
+    mature (o, Coin {coinbase = True, mined = Just h})
+      | rules.height + 1 < h + 100 = Left (Immature o)
+    mature _ = Right ()
+    -- IsFinalTx of Bitcoin Core, for the block after the best one
+    final
+      | tx.locktime == 0 = True
+      | tx.locktime < 500000000 = tx.locktime < rules.height + 1 || waived
+      | otherwise = fromIntegral tx.locktime < rules.medianTime || waived
+    waived = all ((== maxBound) . (.sequence)) tx.inputs
+
+-- | The rules at a height and a median time, with the signatures judged
+-- by 'judgeInputs'.
+rulesAt :: Network -> BlockHeight -> Word64 -> Rules
+rulesAt net height medianTime =
+  Rules {net, inputs = \tx -> judgeInputs net tx . map Just, height, medianTime}
+
+-- | What can be said of a transaction that a peer sent as one that its
+-- node took, given the outputs that it spends, in order.
+--
+-- A node relays what its own policy lets it, and the policies of nodes
+-- differ and change: the smallest output, the largest transaction, the
+-- versions. A transaction that breaks one of those rules may be one that
+-- most of the network relays. So this refuses only what no node takes,
+-- whatever its policy, because no block could hold it:
+--
+-- * it has no inputs or no outputs, spends an output twice, or is a
+--   coinbase, which no node relays;
+-- * its outputs are worth more than its inputs;
+-- * on Bitcoin Cash, it breaks the rules of the tokens ('tokenRules');
+-- * the signature of a coin locked to one key does not verify
+--   ('judgeInputs').
+--
+-- The lock time is left out though a node holds a transaction to it: it
+-- is held to the block that the node is at, which is not always the one
+-- that the caller is at.
+--
+-- It answers as 'judge' does: for a transaction that passes, whether
+-- every signature was verified, or the first input that could not be
+-- judged. Whether to take such a transaction depends on who sent it: from
+-- a node of one's own it is as good as any, and from a stranger it is a
+-- claim that nothing here supports.
+--
+-- The outputs must be those that the inputs spend, all of them: what the
+-- caller does not have is not something to judge yet.
+judgeRelayed :: Network -> Tx -> [TxOut] -> Either Refusal (Maybe Int)
+judgeRelayed net tx spent = do
+  when (null tx.inputs) $ Left NoInputs
+  when (null tx.outputs) $ Left NoOutputs
+  when (any ((== nullOutPoint) . (.outpoint)) tx.inputs) $ Left IsCoinbase
+  mapM_ (Left . DuplicateInput) (firstDuplicate (map (.outpoint) tx.inputs))
+  when (isJust net.sigHashForkId) $ tokenRules tx spent
+  unless (sum (map (toInteger . (.value)) spent) >= sum (map (toInteger . (.value)) tx.outputs)) $ Left Overspent
+  let verdicts = zip [0 ..] (judgeInputs net tx (map Just spent))
+  mapM_ (Left . Forged) (take 1 [i | (i, InputForged) <- verdicts])
+  return (listToMaybe [i | (i, InputUndecided) <- verdicts])
+
+-- | The first of some outpoints that comes twice.
+firstDuplicate :: [OutPoint] -> Maybe OutPoint
+firstDuplicate = go HashMap.empty
+  where
+    go _ [] = Nothing
+    go seen (o : os)
+      | HashMap.member o seen = Just o
+      | otherwise = go (HashMap.insert o () seen) os
+
+-- | The most that nodes relay: 400,000 units of weight with SegWit, which
+-- is 100,000 bytes of a transaction without witness, and 100,000 bytes on
+-- Bitcoin Cash.
+maxStandardSize :: Network -> Int
+maxStandardSize net
+  | net.segWit = 400000
+  | otherwise = 100000
+
+-- | Whether an output is dust: worth less than three times what it costs,
+-- at the lowest fee nodes relay, to make it and to spend it. Nodes do not
+-- relay a transaction with one. This is @IsDust@ of Bitcoin Core at its
+-- default of 3,000 satoshi a kilobyte, and of Bitcoin Cash Node: 546
+-- satoshi for an output to a key hash, 294 to a witness key hash.
+--
+-- An output that cannot be spent, which starts with @OP_RETURN@, holds
+-- data and may hold no value.
+isDust :: Network -> TxOut -> Bool
+isDust net o
+  | unspendable = False
+  | otherwise = toInteger o.value < 3 * toInteger (made + spent)
+  where
+    s = o.script
+    unspendable = (not (B.null s) && B.head s == 0x6a) || B.length s > 10000
+    made = 8 + lengthOfLength + B.length s
+    lengthOfLength
+      | B.length s < 0xfd = 1
+      | B.length s <= 0xffff = 3
+      | otherwise = 5
+    -- what an input that spends it adds: less when its signature is in
+    -- the witness
+    spent
+      | net.segWit && witnessProgram = 67
+      | otherwise = 148
+    witnessProgram =
+      B.length s >= 4
+        && B.length s <= 42
+        && (B.head s == 0 || (B.head s >= 0x51 && B.head s <= 0x60))
+        && fromIntegral (B.index s 1) == B.length s - 2
+
+-- | The tokens that an output holds: their category, a non-fungible token
+-- with its capability and commitment, and an amount of fungible ones.
+data Tokens = Tokens
+  { category :: !ByteString,
+    nft :: !(Maybe (Word8, ByteString)),
+    amount :: !Word64
+  }
+
+-- | The tokens at the front of the script of an output, if it has any, or
+-- 'Left' if they are not written as tokens are ('splitTokenData'). The category is in the order of its bytes in the
+-- transaction, as the rules compare it with the outpoints of the inputs.
+readTokens :: ByteString -> Either () (Maybe Tokens)
+readTokens script = case splitTokenData script of
+  Left _ -> Left ()
+  Right (Nothing, _) -> Right Nothing
+  Right (Just t, _) ->
+    Right . Just $
+      Tokens
+        { category = encode t.category,
+          -- capabilities: 0 none, 1 mutable, 2 minting, in the order of
+          -- the constructors
+          nft = (\n -> (fromIntegral (fromEnum n.capability), n.commitment)) <$> t.nft,
+          amount = t.amount
+        }
+
+-- | The rules of the tokens of Bitcoin Cash (CashTokens, since May 2023),
+-- given the outputs that the inputs spend, in order. A node drops every
+-- connection of a peer that sends it a transaction that breaks them, and
+-- no block holds one.
+--
+-- * The tokens of every output are written as tokens are.
+-- * A category is new when it is the id of a transaction whose first
+--   output an input spends: its tokens may be made at will.
+-- * Of any other category, the outputs hold no more fungible tokens than
+--   the inputs, and no more than the largest amount, in all.
+-- * And its non-fungible tokens come from the inputs: any, when an input
+--   holds one that can mint; else each output's equals one of an input
+--   that cannot be changed, or takes the place of one that can be changed,
+--   and none can mint.
+tokenRules :: Tx -> [TxOut] -> Either Refusal ()
+tokenRules tx spent = do
+  outs <- mapM readOut (zip [0 ..] tx.outputs)
+  let ins = [t | Right (Just t) <- map (readTokens . (.script)) spent] :: [Tokens]
+      made = [t | Just t <- outs] :: [Tokens]
+      new = [encode i.outpoint.hash | i <- tx.inputs, i.outpoint.index == 0]
+      categories = HashMap.keys (HashMap.fromList [(t.category, ()) | t <- made])
+  forM_ categories $ \c -> do
+    let given = [t | t <- made, t.category == c] :: [Tokens]
+        held = [t | t <- ins, t.category == c] :: [Tokens]
+        total = sum (map (toInteger . (.amount)) given)
+    when (total > 0x7fffffffffffffff) $ Left (TokensUnbacked (named c))
+    unless (c `elem` new) $ do
+      when (total > sum (map (toInteger . (.amount)) held)) $ Left (TokensUnbacked (named c))
+      unless (nftsBacked [n | Just n <- map (.nft) given] [n | Just n <- map (.nft) held]) $
+        Left (TokensUnbacked (named c))
+  where
+    readOut :: (Int, TxOut) -> Either Refusal (Maybe Tokens)
+    readOut (i, o) = either (const (Left (BadTokens i))) Right (readTokens o.script)
+    -- the id of a category as people write it: the bytes reversed
+    named = concatMap hex . B.unpack . B.reverse
+    hex w = [digits !! fromIntegral (w `div` 16), digits !! fromIntegral (w `mod` 16)]
+    digits = "0123456789abcdef"
+    -- capabilities: 0 none, 1 mutable, 2 minting
+    nftsBacked given held
+      | any ((== 2) . fst) held = True
+      | any ((== 2) . fst) given = False
+      | otherwise =
+          let (fixed, changing) = partition ((== 0) . fst) given
+              left = foldl matched ([n | n <- held, fst n == 0], []) fixed
+              mutable = length (filter ((== 1) . fst) held)
+           in length (snd left) + length changing <= mutable
+    -- an immutable token given takes an equal one held, or waits for a
+    -- mutable one
+    matched (pool, unmatched) n = case break (== n) pool of
+      (before, _ : after) -> (before <> after, unmatched)
+      _ -> (pool, n : unmatched)
diff --git a/src/Haskoin/Transaction/Psbt.hs b/src/Haskoin/Transaction/Psbt.hs
--- a/src/Haskoin/Transaction/Psbt.hs
+++ b/src/Haskoin/Transaction/Psbt.hs
@@ -38,2274 +38,2662 @@
 -- either version has its unsigned transaction, 'unsignedTx': the one of
 -- the global map, or the one the fields describe.
 --
--- The maps are kept as they are read, byte for byte, so that every field
--- passes through, known or not. A map is written with its keys in order, as
--- Bitcoin Core writes it. A PSBT that breaks the spec is refused when it is
--- read: a key out of shape, a key twice in a map, a value that does not
--- decode, a field of the other version, a field version 2 requires
--- missing, bytes after the last map. So is what Bitcoin Core refuses when
--- it reads a PSBT: a key type that is not a compact size integer in its
--- shortest form, a public key that is not a point of the curve, a partial
--- signature that is not in the encoding of BIP 66 with a defined sighash
--- byte, a previous transaction that is not the one its input spends, and
--- a script tree that is not whole.
---
--- The amounts a PSBT states are claims of whoever wrote it, unless the
--- input carries its previous transaction. 'inputCoins' tells which coins
--- are checked, 'psbtFee' gives the fee from checked coins only, and the
--- signers want the previous transaction of a SegWit version 0 coin
--- ('requirePreviousTx'). The derivation records of outputs are claims
--- too: to treat an output as change, derive its key and compare.
---
--- The fields the spec defines are read and written with the functions
--- below, with the Taproot fields of
--- [BIP 371](https://github.com/bitcoin/bips/blob/master/bip-0371.mediawiki).
--- The roles of the spec are here too: a creator ('psbtOf'), a
--- constructor ('addInput', 'addOutput'), a combiner ('combinePsbt'), a
--- signer ('signPsbt'), a finalizer ('finalizePsbt') and a transaction
--- extractor ('psbtTransaction'), which wants every input final. An updater
--- is the functions that insert fields, and 'setInputSequence'.
-module Haskoin.Transaction.Psbt
-  ( -- * A PSBT
-    Psbt (..),
-    PsbtVersion (..),
-    Key (..),
-    PsbtMap,
-    psbtOf,
-    psbtOfMaps,
-    withVersion,
-    psbtId,
-    combinePsbt,
-    psbtTransaction,
-    psbtPartialTransaction,
-
-    -- * The inputs and outputs of version 2
-    addInput,
-    addOutput,
-    setInputSequence,
-    Modifiable (..),
-    txModifiable,
-    insertTxModifiable,
-    deleteTxModifiable,
-    fallbackLockTime,
-    requiredTimeLockTime,
-    insertRequiredTimeLockTime,
-    requiredHeightLockTime,
-    insertRequiredHeightLockTime,
-
-    -- * Bytes and text
-    psbtMagic,
-    isPsbt,
-    encodePsbt,
-    decodePsbt,
-    encodePsbtBase64,
-    decodePsbtBase64,
-
-    -- * The global fields
-    Derivation (..),
-    xpubRecords,
-    insertXpubRecord,
-
-    -- * The fields of an input
-    nonWitnessUtxo,
-    insertNonWitnessUtxo,
-    witnessUtxo,
-    insertWitnessUtxo,
-    partialSignatures,
-    hasPartialSignatures,
-    insertPartialSignature,
-    deletePartialSignatures,
-    sigHashType,
-    insertSigHashType,
-    deleteSigHashType,
-    inputRedeemScript,
-    insertInputRedeemScript,
-    inputWitnessScript,
-    insertInputWitnessScript,
-    inputDerivations,
-    insertInputDerivation,
-    finalScriptSig,
-    insertFinalScriptSig,
-    finalScriptWitness,
-    insertFinalScriptWitness,
-
-    -- * The Taproot fields of an input
-    tapKeySig,
-    insertTapKeySig,
-    tapScriptSigs,
-    insertTapScriptSig,
-    TapLeafScript (..),
-    tapLeafScripts,
-    insertTapLeafScript,
-    TapDerivation (..),
-    inputTapDerivations,
-    insertInputTapDerivation,
-    inputTapInternalKey,
-    insertInputTapInternalKey,
-    inputTapMerkleRoot,
-    insertInputTapMerkleRoot,
-
-    -- * The fields of an output
-    outputRedeemScript,
-    insertOutputRedeemScript,
-    outputWitnessScript,
-    insertOutputWitnessScript,
-    outputDerivations,
-    insertOutputDerivation,
-    outputTapInternalKey,
-    insertOutputTapInternalKey,
-    outputTapTree,
-    insertOutputTapTree,
-    outputTapDerivations,
-    insertOutputTapDerivation,
-
-    -- * Proprietary fields
-    Proprietary (..),
-    proprietaryKey,
-    proprietaryOf,
-    lookupProprietary,
-    insertProprietary,
-
-    -- * The coins of a PSBT
-    InputCoin (..),
-    inputCoins,
-    psbtFee,
-
-    -- * Signing
-    Signer (..),
-    defaultSigHashes,
-    keySigner,
-    xPrvSigner,
-    signPsbt,
-    afterSignature,
-
-    -- * Finalizing
-    finalizePsbt,
-  )
-where
-
-import Control.DeepSeq (NFData)
-import Control.Monad (ap, forM, forM_, guard, replicateM, unless, when, zipWithM)
-import Crypto.Hash (Digest, SHA256, digestFromByteString)
-import Crypto.Secp256k1 (PubKey, SecKey, derivePubKey, exportXOnlyPubKey, importPubKey, importXOnlyPubKey, signSchnorr, verifySchnorr)
-import Data.Base64.Types (extractBase64)
-import Data.Bifunctor (first)
-import Data.Bits (complement, shiftL, testBit, (.&.), (.|.))
-import Data.ByteArray qualified as BA
-import Data.ByteString (ByteString)
-import Data.ByteString qualified as B
-import Data.ByteString.Base64 (decodeBase64Untyped, encodeBase64')
-import Data.Char (toUpper)
-import Data.List (find, nubBy, stripPrefix)
-import Data.Map.Strict (Map)
-import Data.Map.Strict qualified as Map
-import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, listToMaybe, mapMaybe, maybeToList)
-import Data.Serialize qualified as S
-import Data.Word (Word32, Word64, Word8)
-import GHC.Generics (Generic)
-import Haskoin.Crypto.Hash (Hash160, addressHash)
-import Haskoin.Crypto.Keys.Common
-import Haskoin.Crypto.Keys.Extended
-import Haskoin.Crypto.Signature (hashToMsg, verifyHashSig)
-import Haskoin.Network.Common (VarInt (..))
-import Haskoin.Network.Data
-import Haskoin.Script.Common
-import Haskoin.Script.SigHash
-import Haskoin.Script.Standard
-import Haskoin.Transaction.Builder.Sign (SigInput (..), makeSigHash, makeSignature)
-import Haskoin.Transaction.Common hiding (decodeTx)
-import Haskoin.Transaction.Segwit (isSegwit)
-import Haskoin.Transaction.Taproot
-import Haskoin.Util
-import Numeric (showHex)
-import Text.Read (readMaybe)
-
-{- A PSBT -}
-
--- | A key of a map: its type, and the data after the type byte. Most
--- fields have none; a derivation or a signature has the public key it is
--- of. The type of a key is a compact size integer. Every type the spec
--- defines fits one byte. A type from 253 on takes three or five bytes on
--- the wire: its first byte, 0xfd or 0xfe, is the 'keyType' here, and the
--- other bytes of the type are the start of the 'keyData', where
--- 'decodePsbt' requires them to be the shortest form of the type.
-data Key = Key
-  { keyType :: !Word8,
-    keyData :: !ByteString
-  }
-  deriving (Eq, Ord, Show, Read, Generic)
-  deriving anyclass (NFData)
-
--- | A map of a PSBT. It is written with its keys in order, the type first,
--- as Bitcoin Core writes it.
-type PsbtMap = Map Key ByteString
-
--- | The version of a PSBT: 0, the version of BIP 174, whose global map
--- holds the unsigned transaction, or 2, the version of BIP 370, whose maps
--- hold the transaction field by field, so that inputs and outputs can be
--- added. There is no version 1.
-data PsbtVersion = Version0 | Version2
-  deriving (Eq, Ord, Show, Read, Generic)
-  deriving anyclass (NFData)
-
-versionNumber :: PsbtVersion -> Word32
-versionNumber Version0 = 0
-versionNumber Version2 = 2
-
--- | A PSBT: its version, the unsigned transaction, the global map, and the
--- maps of the inputs and of the outputs, one each, in the order of the
--- transaction. In version 0, the global map is kept without the unsigned
--- transaction. In version 2, the maps keep the fields that describe the
--- transaction, and the unsigned transaction is the one they describe, with
--- the lock time they determine.
---
--- In version 2 the record so holds the transaction twice. 'signPsbt' signs
--- 'unsignedTx', and 'encodePsbt' writes the maps. A record update that
--- changes one and not the other gives a PSBT whose bytes describe another
--- transaction than the one that is signed. Change the transaction of such a
--- PSBT with 'addInput', 'addOutput' and 'psbtOfMaps', which keep the two in
--- step.
-data Psbt = Psbt
-  { version :: !PsbtVersion,
-    unsignedTx :: !Tx,
-    globals :: !PsbtMap,
-    inputs :: ![PsbtMap],
-    outputs :: ![PsbtMap]
-  }
-  deriving (Eq, Show, Read, Generic)
-  deriving anyclass (NFData)
-
--- | The PSBT of a transaction, with nothing else, as the creator of the
--- spec makes it, in version 0: the transaction without its input scripts
--- and witness, and an empty map per input and per output. 'withVersion'
--- makes it one of version 2.
-psbtOf :: Tx -> Psbt
-psbtOf tx =
-  Psbt
-    { version = Version0,
-      unsignedTx = Tx tx.version [TxIn input.outpoint B.empty input.sequence | input <- tx.inputs] tx.outputs [] tx.locktime,
-      globals = Map.empty,
-      inputs = Map.empty <$ tx.inputs,
-      outputs = Map.empty <$ tx.outputs
-    }
-
--- | The PSBT whose maps these are, as they are in its bytes: the global
--- map names the version, and holds the unsigned transaction in version 0.
--- The maps are checked against the spec of the version, and in version 2
--- the transaction is read from their fields.
-psbtOfMaps :: PsbtMap -> [PsbtMap] -> [PsbtMap] -> Either String Psbt
-psbtOfMaps globals inputs outputs = do
-  (version, inputCount, outputCount) <- countsOf globals
-  unless (length inputs == inputCount) $
-    Left ("The PSBT has " <> show (length inputs) <> " inputs, and its global map counts " <> show inputCount)
-  unless (length outputs == outputCount) $
-    Left ("The PSBT has " <> show (length outputs) <> " outputs, and its global map counts " <> show outputCount)
-  forM_ (zip [0 :: Int ..] inputs) $ \(i, m) -> checkMap ("input " <> show i) version inputFields m
-  forM_ (zip [0 :: Int ..] outputs) $ \(i, m) -> checkMap ("output " <> show i) version outputFields m
-  tx <- case version of
-    Version0 -> unsignedTxOf globals
-    Version2 -> transactionOf globals inputs outputs
-  forM_ (zip3 [0 :: Int ..] tx.inputs inputs) $ \(i, input, m) ->
-    first (("Input " <> show i <> ": ") <>) (checkPreviousTx input m)
-  return $ Psbt version tx (Map.delete unsignedTxKey globals) inputs outputs
-
--- | The previous transaction of an input, when its map has one, must be
--- the transaction the input spends from and have the output it spends, as
--- Bitcoin Core requires when it reads a PSBT ("Non-witness UTXO does not
--- match outpoint hash", psbt.h)
-checkPreviousTx :: TxIn -> PsbtMap -> Either String ()
-checkPreviousTx input m = do
-  parentM <- nonWitnessUtxo m
-  forM_ parentM (previousOutput input)
-
--- | The output an input spends, from its previous transaction: the
--- transaction must be the one the input names, and have that output
-previousOutput :: TxIn -> Tx -> Either String TxOut
-previousOutput input parent = do
-  unless (txHash parent == input.outpoint.hash) $
-    Left "the previous transaction is not the one the input spends"
-  maybe (Left "the input spends an output its previous transaction does not have") Right $
-    listToMaybe (drop (fromIntegral input.outpoint.index) parent.outputs)
-
--- | The PSBT in the version given, as BIP 370 converts one. To version 2:
--- the transaction goes in the fields of the maps, its lock time as the
--- fallback. To version 0: the fields of version 2 leave the maps, and the
--- transaction keeps the lock time they determined.
-withVersion :: PsbtVersion -> Psbt -> Psbt
-withVersion v psbt
-  | v == psbt.version = psbt
-  | v == Version2 =
-      Psbt
-        Version2
-        tx
-        (withTxFields tx (insertPlainField versionType (word32le 2) psbt.globals))
-        (zipWith withInputFields tx.inputs psbt.inputs)
-        (zipWith withOutputFields tx.outputs psbt.outputs)
-  | otherwise =
-      Psbt
-        Version0
-        tx
-        (without globalV2Types (deletePlainField versionType psbt.globals))
-        (without inputV2Types <$> psbt.inputs)
-        (without outputV2Types <$> psbt.outputs)
-  where
-    tx = psbt.unsignedTx
-    without :: [Word8] -> PsbtMap -> PsbtMap
-    without types = Map.filterWithKey (\key _ -> key.keyType `notElem` types)
-
--- | What identifies a PSBT: the id of its unsigned transaction. In version
--- 2 the sequence of every input is taken as 0 for it, as BIP 370 says,
--- since an updater may change the sequences.
-psbtId :: Psbt -> TxHash
-psbtId psbt = txHash $ case psbt.version of
-  Version0 -> tx
-  Version2 -> Tx tx.version [TxIn input.outpoint input.script 0 | input <- tx.inputs] tx.outputs tx.witness tx.locktime
-  where
-    tx = psbt.unsignedTx
-
--- | The PSBT with the fields of both, as the combiner of the spec makes
--- it. Both must be of the same version and of the same transaction. A
--- field both have, with different values, keeps the value of the first.
--- The flags of version 2 are combined as Bitcoin Core combines them:
--- inputs and outputs stay modifiable only when both say so, and a
--- SIGHASH_SINGLE signature of either is kept.
-combinePsbt :: Psbt -> Psbt -> Either String Psbt
-combinePsbt a b = do
-  unless (a.version == b.version) $ Left "The PSBTs are not of the same version"
-  unless (psbtId a == psbtId b) $ Left "The PSBTs are not of the same transaction"
-  let globals = combinedFlags (Map.union a.globals b.globals)
-      inputs = zipWith Map.union a.inputs b.inputs
-      outputs = zipWith Map.union a.outputs b.outputs
-  case a.version of
-    Version0 -> return $ Psbt Version0 a.unsignedTx globals inputs outputs
-    Version2 -> (\tx -> Psbt Version2 tx globals inputs outputs) <$> transactionOf globals inputs outputs
-  where
-    combinedFlags globals = case (flagsOf a, flagsOf b) of
-      (Nothing, Nothing) -> globals
-      (x, y) ->
-        let fx = fromMaybe noFlags x
-            fy = fromMaybe noFlags y
-         in insertTxModifiable
-              (Modifiable (fx.inputsModifiable && fy.inputsModifiable) (fx.outputsModifiable && fy.outputsModifiable) (fx.hasSigHashSingle || fy.hasSigHashSingle) (fx.undefinedBits .&. fy.undefinedBits))
-              globals
-    flagsOf :: Psbt -> Maybe Modifiable
-    flagsOf psbt = either (const Nothing) id (txModifiable psbt.globals)
-
--- | The transaction of a PSBT whose inputs are all final, with their final
--- scripts and witnesses, as the transaction extractor of the spec builds
--- it. BIP 174 has the extractor check "whether all inputs have complete
--- scriptSigs and scriptWitnesses" first, and Bitcoin Core gives no
--- transaction otherwise (@FinalizeAndExtractPSBT@), so an input that is
--- not final is refused here. 'psbtPartialTransaction' takes such a PSBT.
---
--- The final scripts are taken as they are: nothing runs them. Finalize
--- with 'finalizePsbt', which verifies the signatures it uses, or verify
--- the transaction before it is sent.
-psbtTransaction :: Psbt -> Either String Tx
-psbtTransaction psbt = do
-  forM_ (zip [0 :: Int ..] psbt.inputs) $ \(i, m) ->
-    unless (isFinal m) $ Left ("Input " <> show i <> " is not final")
-  psbtPartialTransaction psbt
-
--- | The transaction of a PSBT with the final script and witness of every
--- input that has them. An input without them stays unsigned, so the
--- transaction may not be valid yet: this is for looking at a PSBT that is
--- still being signed, not for sending. 'psbtTransaction' is the extractor.
-psbtPartialTransaction :: Psbt -> Either String Tx
-psbtPartialTransaction psbt = do
-  finals <- forM (zip psbt.unsignedTx.inputs psbt.inputs) $ \(input, m) -> do
-    stack <- fromMaybe [] <$> finalScriptWitness m
-    let scriptSig = fromMaybe B.empty (finalScriptSig m)
-    return (TxIn input.outpoint scriptSig input.sequence, stack)
-  let stacks = snd <$> finals
-      witness = if all null stacks then [] else stacks
-  return $ Tx psbt.unsignedTx.version (fst <$> finals) psbt.unsignedTx.outputs witness psbt.unsignedTx.locktime
-
-{- The inputs and outputs of version 2 -}
-
--- | The PSBT with an input added at the end, as the constructor of BIP 370
--- adds one: the output it spends and its sequence from the input given,
--- and the fields of the map given, such as the lock time it requires. A
--- PSBT of version 0 takes none, nor one whose inputs are not modifiable.
--- A lock time the input requires must fit the other inputs, and must not
--- change the lock time of the transaction once an input is signed. Added
--- at the end, the input leaves every SIGHASH_SINGLE signature paired with
--- its output. The map is checked against the spec as a map read from
--- bytes is: a field out of shape, or a previous transaction that is not
--- the one the input spends, is refused.
-addInput :: TxIn -> PsbtMap -> Psbt -> Either String Psbt
-addInput input m psbt = do
-  flags <- modifiableOf psbt
-  unless flags.inputsModifiable $ Left "The inputs of the PSBT may not be modified"
-  when (any ((== input.outpoint) . (.outpoint)) psbt.unsignedTx.inputs) $
-    Left "An input of the PSBT spends that output already"
-  let added = withInputFields input m
-      inputs = psbt.inputs <> [added]
-      globals = withCounts (length inputs) (length psbt.outputs) psbt.globals
-      place = "input " <> show (length psbt.inputs)
-  -- The same checks as when a PSBT is read, so that the bytes written are
-  -- bytes 'decodePsbt' reads
-  checkMap place Version2 inputFields added
-  first ((capital place <> ": ") <>) (checkPreviousTx input added)
-  tx <- transactionOf globals inputs psbt.outputs
-  when (any hasSignatures psbt.inputs && tx.locktime /= psbt.unsignedTx.locktime) $
-    Left "An input is signed already: the lock time may not change"
-  return $ Psbt Version2 tx globals inputs psbt.outputs
-
--- | The PSBT with an output added at the end, as the constructor of BIP
--- 370 adds one: its amount and script from the output given, and the
--- fields of the map given. A PSBT of version 0 takes none, nor one whose
--- outputs are not modifiable.
-addOutput :: TxOut -> PsbtMap -> Psbt -> Either String Psbt
-addOutput output m psbt = do
-  flags <- modifiableOf psbt
-  unless flags.outputsModifiable $ Left "The outputs of the PSBT may not be modified"
-  let added = withOutputFields output m
-      outputs = psbt.outputs <> [added]
-      globals = withCounts (length psbt.inputs) (length outputs) psbt.globals
-  checkMap ("output " <> show (length psbt.outputs)) Version2 outputFields added
-  tx <- transactionOf globals psbt.inputs outputs
-  return $ Psbt Version2 tx globals psbt.inputs outputs
-
--- | The flags of a PSBT of version 2, none set when it has no field of
--- them. A PSBT of version 0 takes no input or output.
-modifiableOf :: Psbt -> Either String Modifiable
-modifiableOf psbt = do
-  unless (psbt.version == Version2) $ Left "A PSBT of version 0 takes no input or output: its transaction is fixed"
-  fromMaybe noFlags <$> txModifiable psbt.globals
-
--- | Whether an input has a signature: one that is not final, a Taproot
--- one, or its final script or witness
-hasSignatures :: PsbtMap -> Bool
-hasSignatures m = hasPartialSignatures m || isFinal m || any ((`elem` [tapKeySigType, tapScriptSigType]) . (.keyType)) (Map.keys m)
-
--- | The PSBT with the sequence of the input at the index set, as an
--- updater of BIP 370 may set one. The sequences of a PSBT of version 0
--- are in its unsigned transaction, which is fixed. An input that is
--- signed keeps its sequence, since every signature commits to it.
-setInputSequence :: Int -> Word32 -> Psbt -> Either String Psbt
-setInputSequence i sequence' psbt = do
-  unless (psbt.version == Version2) $ Left "The sequences of a PSBT of version 0 are in its unsigned transaction, which is fixed"
-  unless (i >= 0 && i < length psbt.inputs) $ Left ("The PSBT has no input " <> show i)
-  when (hasSignatures (psbt.inputs !! i)) $ Left ("Input " <> show i <> " is signed already: its sequence may not change")
-  let inputs = [if j == i then insertPlainField sequenceType (word32le sequence') m else m | (j, m) <- zip [0 ..] psbt.inputs]
-  tx <- transactionOf psbt.globals inputs psbt.outputs
-  return $ Psbt Version2 tx psbt.globals inputs psbt.outputs
-
--- | The global map with the fields of version 2 that describe the
--- transaction: its version, its lock time as the fallback, and the number
--- of its inputs and outputs
-withTxFields :: Tx -> PsbtMap -> PsbtMap
-withTxFields tx =
-  insertPlainField txVersionType (word32le tx.version)
-    . insertPlainField fallbackLockTimeType (word32le tx.locktime)
-    . withCounts (length tx.inputs) (length tx.outputs)
-
-withCounts :: Int -> Int -> PsbtMap -> PsbtMap
-withCounts inputCount outputCount =
-  insertPlainField inputCountType (compactSize (fromIntegral inputCount))
-    . insertPlainField outputCountType (compactSize (fromIntegral outputCount))
-
--- | The map of an input with the fields of version 2 that describe it: the
--- id of the transaction it spends from, the index of the output, and its
--- sequence
-withInputFields :: TxIn -> PsbtMap -> PsbtMap
-withInputFields input =
-  insertPlainField prevTxidType (S.encode input.outpoint.hash)
-    . insertPlainField outputIndexType (word32le input.outpoint.index)
-    . insertPlainField sequenceType (word32le input.sequence)
-
--- | The map of an output with the fields of version 2 that describe it:
--- its amount and its script
-withOutputFields :: TxOut -> PsbtMap -> PsbtMap
-withOutputFields output =
-  insertPlainField amountType (word64le output.value)
-    . insertPlainField outScriptType output.script
-
-{- The types of the spec -}
-
-unsignedTxType, xpubType, txVersionType, fallbackLockTimeType, inputCountType, outputCountType, txModifiableType, versionType :: Word8
-unsignedTxType = 0x00
-xpubType = 0x01
-txVersionType = 0x02
-fallbackLockTimeType = 0x03
-inputCountType = 0x04
-outputCountType = 0x05
-txModifiableType = 0x06
-versionType = 0xfb
-
-nonWitnessUtxoType, witnessUtxoType, partialSigType, sigHashTypeType, inRedeemScriptType, inWitnessScriptType, inDerivationType, finalScriptSigType, finalScriptWitnessType, tapKeySigType, tapScriptSigType, tapLeafScriptType, inTapDerivationType, inTapInternalKeyType, tapMerkleRootType :: Word8
-nonWitnessUtxoType = 0x00
-witnessUtxoType = 0x01
-partialSigType = 0x02
-sigHashTypeType = 0x03
-inRedeemScriptType = 0x04
-inWitnessScriptType = 0x05
-inDerivationType = 0x06
-finalScriptSigType = 0x07
-finalScriptWitnessType = 0x08
-tapKeySigType = 0x13
-tapScriptSigType = 0x14
-tapLeafScriptType = 0x15
-inTapDerivationType = 0x16
-inTapInternalKeyType = 0x17
-tapMerkleRootType = 0x18
-
-prevTxidType, outputIndexType, sequenceType, requiredTimeType, requiredHeightType :: Word8
-prevTxidType = 0x0e
-outputIndexType = 0x0f
-sequenceType = 0x10
-requiredTimeType = 0x11
-requiredHeightType = 0x12
-
-outRedeemScriptType, outWitnessScriptType, outDerivationType, amountType, outScriptType, outTapInternalKeyType, outTapTreeType, outTapDerivationType :: Word8
-outRedeemScriptType = 0x00
-outWitnessScriptType = 0x01
-outDerivationType = 0x02
-amountType = 0x03
-outScriptType = 0x04
-outTapInternalKeyType = 0x05
-outTapTreeType = 0x06
-outTapDerivationType = 0x07
-
--- | The types of the fields of version 2, which version 0 excludes, by
--- map
-globalV2Types, inputV2Types, outputV2Types :: [Word8]
-globalV2Types = [txVersionType, fallbackLockTimeType, inputCountType, outputCountType, txModifiableType]
-inputV2Types = [prevTxidType, outputIndexType, sequenceType, requiredTimeType, requiredHeightType]
-outputV2Types = [amountType, outScriptType]
-
--- | The lock times from this value are times, below it heights
-lockTimeThreshold :: Word32
-lockTimeThreshold = 500000000
-
-proprietaryType :: Word8
-proprietaryType = 0xfc
-
--- | The key of the unsigned transaction in the global map
-unsignedTxKey :: Key
-unsignedTxKey = Key unsignedTxType B.empty
-
-{- Bytes -}
-
--- | The five bytes every PSBT starts with: "psbt" and 0xff
-psbtMagic :: ByteString
-psbtMagic = B.pack [0x70, 0x73, 0x62, 0x74, 0xff]
-
--- | Whether the bytes are those of a PSBT, by their first five
-isPsbt :: ByteString -> Bool
-isPsbt = B.isPrefixOf psbtMagic
-
--- | The bytes of a PSBT: the magic, the global map, with the unsigned
--- transaction in version 0, then the maps of the inputs and of the outputs
-encodePsbt :: Psbt -> ByteString
-encodePsbt psbt =
-  B.concat $ psbtMagic : encodeMap globals : (encodeMap <$> psbt.inputs) <> (encodeMap <$> psbt.outputs)
-  where
-    globals = case psbt.version of
-      Version0 -> Map.insert unsignedTxKey (S.encode psbt.unsignedTx) psbt.globals
-      Version2 -> psbt.globals
-
--- | A map: each key and value after its length, the keys in order, then a
--- zero byte
-encodeMap :: PsbtMap -> ByteString
-encodeMap m =
-  B.concat [sized (B.cons key.keyType key.keyData) <> sized value | (key, value) <- Map.toAscList m]
-    <> B.singleton 0
-
--- | Bytes after their length, as a compact size integer
-sized :: ByteString -> ByteString
-sized bytes = compactSize (fromIntegral (B.length bytes)) <> bytes
-
--- | A compact size integer, in its shortest form
-compactSize :: Word64 -> ByteString
-compactSize = S.encode . VarInt
-
--- | A 32-bit integer, little-endian
-word32le :: Word32 -> ByteString
-word32le = S.runPut . S.putWord32le
-
--- | A 64-bit integer, little-endian
-word64le :: Word64 -> ByteString
-word64le = S.runPut . S.putWord64le
-
--- | The PSBT the bytes hold, or why they hold none: not a PSBT, or one that
--- breaks the spec
-decodePsbt :: ByteString -> Either String Psbt
-decodePsbt = parseAll psbtParser "the last map"
-
--- | The text of a PSBT, in base64, as the spec gives it for text
-encodePsbtBase64 :: Psbt -> ByteString
-encodePsbtBase64 = extractBase64 . encodeBase64' . encodePsbt
-
--- | The PSBT of a base64 text, around which spaces and line breaks are
--- left aside
-decodePsbtBase64 :: ByteString -> Either String Psbt
-decodePsbtBase64 text = do
-  bytes <- first (const "Not the base64 text of a PSBT") $ decodeBase64Untyped (B.filter (`notElem` spaces) text)
-  decodePsbt bytes
-  where
-    spaces = [0x20, 0x09, 0x0a, 0x0d]
-
-{- Reading bytes -}
-
--- | A reader of bytes, which stops at the first byte out of place with a
--- sentence saying so
-newtype BytesParser a = BytesParser (ByteString -> Either String (a, ByteString))
-
-instance Functor BytesParser where
-  fmap f (BytesParser p) = BytesParser $ \bytes -> do
-    (a, rest) <- p bytes
-    return (f a, rest)
-
-instance Applicative BytesParser where
-  pure a = BytesParser $ \bytes -> Right (a, bytes)
-  (<*>) = ap
-
-instance Monad BytesParser where
-  BytesParser p >>= f = BytesParser $ \bytes -> do
-    (a, rest) <- p bytes
-    let BytesParser q = f a
-    q rest
-
-refuse :: String -> BytesParser a
-refuse reason = BytesParser $ \_ -> Left reason
-
--- | Read all the bytes with the parser: nothing may follow what it reads
-parseAll :: BytesParser a -> String -> ByteString -> Either String a
-parseAll (BytesParser p) what bytes = do
-  (a, rest) <- p bytes
-  unless (B.null rest) $ Left ("Bytes follow " <> what)
-  return a
-
--- | The next bytes, which must be there. What they are part of names
--- them in the refusal.
-bytesOf :: Int -> String -> BytesParser ByteString
-bytesOf n what = BytesParser $ \bytes ->
-  if B.length bytes < n
-    then Left ("The PSBT ends inside " <> what)
-    else Right (B.splitAt n bytes)
-
--- | All the bytes left
-restOf :: BytesParser ByteString
-restOf = BytesParser $ \bytes -> Right (bytes, B.empty)
-
--- | A compact size integer: one byte below 0xfd, or 0xfd, 0xfe or 0xff and
--- two, four or eight bytes, little-endian, in the shortest form, as
--- Bitcoin Core reads it
-compactSizeOf :: String -> BytesParser Word64
-compactSizeOf what = do
-  first' <- B.head <$> bytesOf 1 what
-  case first' of
-    0xfd -> longer 2 0xfd
-    0xfe -> longer 4 0x10000
-    0xff -> longer 8 0x100000000
-    _ -> return (fromIntegral first')
-  where
-    longer :: Int -> Word64 -> BytesParser Word64
-    longer n least = do
-      value <- B.foldr (\b acc -> acc `shiftL` 8 .|. fromIntegral b) 0 <$> bytesOf n what
-      when (value < least) $ refuse ("A length in " <> what <> " is not in its shortest form")
-      return value
-
--- | A length, which must fit in memory
-lengthOf :: String -> BytesParser Int
-lengthOf what = do
-  n <- compactSizeOf what
-  when (n > fromIntegral (maxBound :: Int)) $ refuse ("A length in " <> what <> " is beyond any PSBT")
-  return (fromIntegral n)
-
--- | Bytes after their length
-sizedBytes :: String -> BytesParser ByteString
-sizedBytes what = lengthOf what >>= (`bytesOf` what)
-
--- | A map: keys and values up to a zero byte, each key once
-mapOf :: String -> BytesParser PsbtMap
-mapOf what = go Map.empty
-  where
-    go m = do
-      keyLength <- lengthOf what
-      if keyLength == 0
-        then return m
-        else do
-          keyBytes <- bytesOf keyLength what
-          either refuse return (checkKeyType what keyBytes)
-          value <- sizedBytes what
-          let key = Key (B.head keyBytes) (B.tail keyBytes)
-          when (Map.member key m) $
-            refuse (capital what <> " has the key " <> showKey key <> " twice")
-          go (Map.insert key value m)
-
--- | The type of a key is a compact size integer at the start of the key.
--- Every type the spec defines is below 0xfd and so is the first byte. A
--- type from 0xfd on takes three, five or nine bytes: it must be whole, in
--- its shortest form, and at most 'maxCompactSize', as Bitcoin Core reads
--- it (@ReadCompactSize@ in serialize.h). Such a key is kept as its first
--- byte and, as its data, the bytes after it.
-checkKeyType :: String -> ByteString -> Either String ()
-checkKeyType what keyBytes = case B.unpack (B.take 1 keyBytes) of
-  [0xfd] -> longer 2 0xfd
-  [0xfe] -> longer 4 0x10000
-  [0xff] -> longer 8 0x100000000
-  _ -> Right ()
-  where
-    longer :: Int -> Word64 -> Either String ()
-    longer n least = do
-      let bytes = B.take n (B.drop 1 keyBytes)
-      unless (B.length bytes == n) $
-        Left (capital what <> " has a key that ends inside its type")
-      let value = B.foldr (\b acc -> acc `shiftL` 8 .|. fromIntegral b) 0 bytes
-      when (value < least) $
-        Left (capital what <> " has a key whose type is not in its shortest form")
-      when (value > maxCompactSize) $
-        Left (capital what <> " has a key whose type is beyond any type")
-
--- | The largest compact size integer Bitcoin Core reads: its @MAX_SIZE@
-maxCompactSize :: Word64
-maxCompactSize = 0x02000000
-
-psbtParser :: BytesParser Psbt
-psbtParser = do
-  magic <- bytesOf 5 "the magic bytes"
-  unless (magic == psbtMagic) $ refuse "Not a PSBT: the bytes do not start with the magic bytes of BIP 174"
-  globals <- mapOf "the global map"
-  (_, inputCount, outputCount) <- either refuse return (countsOf globals)
-  inputs <- forM [0 .. inputCount - 1] $ \i -> mapOf ("input " <> show i)
-  outputs <- forM [0 .. outputCount - 1] $ \i -> mapOf ("output " <> show i)
-  either refuse return (psbtOfMaps globals inputs outputs)
-
--- | The version a global map names, and the number of inputs and of
--- outputs: those of the unsigned transaction in version 0, those the map
--- counts in version 2. The map is checked against the spec of the version
--- first.
-countsOf :: PsbtMap -> Either String (PsbtVersion, Int, Int)
-countsOf globals = do
-  version <- versionOf globals
-  checkMap "the global map" version globalFields globals
-  case version of
-    Version0 -> do
-      tx <- unsignedTxOf globals
-      return (Version0, length tx.inputs, length tx.outputs)
-    Version2 -> do
-      _ <- requiredField "The global map" "transaction version" txVersionType decodeWord32le globals
-      inputCount <- requiredField "The global map" "input count" inputCountType decodeCount globals
-      outputCount <- requiredField "The global map" "output count" outputCountType decodeCount globals
-      return (Version2, inputCount, outputCount)
-
--- | The version the global map names with PSBT_GLOBAL_VERSION: 0 when it
--- names none
-versionOf :: PsbtMap -> Either String PsbtVersion
-versionOf globals = case plainField versionType globals of
-  Nothing -> Right Version0
-  Just bytes -> do
-    n <- first ("The global map: the value of the key 0xfb " <>) (decodeWord32le bytes)
-    case n of
-      0 -> Right Version0
-      2 -> Right Version2
-      _ -> Left ("The PSBT is of version " <> show n <> ": only versions 0 and 2 are supported")
-
--- | The unsigned transaction of the global map of version 0, which must be
--- there, in the serialization without witness, with no input script. It
--- is read with 'parseLegacyTx', as Bitcoin Core reads it without allowing
--- a witness, so that a transaction with no inputs, which the spec allows,
--- is not taken for the extended format of BIP 144.
-unsignedTxOf :: PsbtMap -> Either String Tx
-unsignedTxOf globals = do
-  bytes <- maybe (Left "The global map has no unsigned transaction") Right (Map.lookup unsignedTxKey globals)
-  tx <- case S.runGetState parseLegacyTx bytes 0 of
-    Right (parsed, rest) | B.null rest -> Right parsed
-    _ -> Left "The unsigned transaction does not decode"
-  unless (null tx.witness && S.encode tx == bytes) $
-    Left "The unsigned transaction is not in the serialization without witness"
-  unless (all (B.null . (.script)) tx.inputs) $
-    Left "The unsigned transaction has an input with a script"
-  return tx
-
--- | The transaction the fields of version 2 describe: its version from
--- the global map, the lock time the inputs require or the fallback, an
--- input per input map from the id of the transaction it spends from, the
--- index of the output and the sequence, final when the map has none, and
--- an output per output map from its amount and script
-transactionOf :: PsbtMap -> [PsbtMap] -> [PsbtMap] -> Either String Tx
-transactionOf globals inputs outputs = do
-  version <- requiredField "The global map" "transaction version" txVersionType decodeWord32le globals
-  locktime <- lockTimeOf globals inputs
-  txInputs <- forM (zip [0 :: Int ..] inputs) $ \(i, m) -> do
-    let place = "Input " <> show i
-    hash <- requiredField place "previous transaction id" prevTxidType decodeTxHash m
-    index <- requiredField place "output index" outputIndexType decodeWord32le m
-    sequence' <- fromMaybe 0xffffffff <$> optionalField "The sequence" sequenceType decodeWord32le m
-    return (TxIn (OutPoint hash index) B.empty sequence')
-  txOutputs <- forM (zip [0 :: Int ..] outputs) $ \(i, m) -> do
-    let place = "Output " <> show i
-    value <- requiredField place "amount" amountType decodeWord64le m
-    script <- requiredField place "script" outScriptType Right m
-    return (TxOut value script)
-  return (Tx version txInputs txOutputs [] locktime)
-
--- | The lock time of a PSBT of version 2, as BIP 370 determines it. An
--- input may require a lock time as a height, as a time, or either, with
--- both. When no input requires one, it is the fallback lock time of the
--- global map, 0 without one. Otherwise it is the greatest of the kind every
--- input that requires one takes, a height when every one takes a height.
--- When some inputs take a height only and others a time only, no lock time
--- fits them.
-lockTimeOf :: PsbtMap -> [PsbtMap] -> Either String Word32
-lockTimeOf globals inputs = do
-  fallback <- fromMaybe 0 <$> fallbackLockTime globals
-  required <- forM inputs $ \m -> (,) <$> requiredTimeLockTime m <*> requiredHeightLockTime m
-  let asking = [r | r@(time, height) <- required, isJust time || isJust height]
-      heights = [height | (_, Just height) <- asking]
-      times = [time | (Just time, _) <- asking]
-  case () of
-    _
-      | null asking -> Right fallback
-      | length heights == length asking -> Right (maximum heights)
-      | length times == length asking -> Right (maximum times)
-      | otherwise -> Left "No lock time fits every input: some require a height, others a time"
-
--- | A field a map must have, decoded. Its absence, or a value out of shape,
--- names the map and the field.
-requiredField :: String -> String -> Word8 -> (ByteString -> Either String a) -> PsbtMap -> Either String a
-requiredField what name t decode m = do
-  bytes <- maybe (Left (what <> " has no " <> name)) Right (plainField t m)
-  first ((what <> ": the " <> name <> " ") <>) (decode bytes)
-
--- | A field a map may have, decoded, named in a refusal
-optionalField :: String -> Word8 -> (ByteString -> Either String a) -> PsbtMap -> Either String (Maybe a)
-optionalField name t decode = traverse (first ((name <> " ") <>) . decode) . plainField t
-
--- | A value decoded from all the bytes given, or a refusal naming it
-decodeFully :: (S.Serialize a) => String -> ByteString -> Either String a
-decodeFully what bytes = case S.runGetState S.get bytes 0 of
-  Right (a, rest) | B.null rest -> Right a
-  _ -> Left (what <> " does not decode")
-
--- | A sentence that starts with the words given
-capital :: String -> String
-capital (c : rest) = toUpper c : rest
-capital [] = []
-
--- | A key as a refusal names it: its type in hexadecimal, and its data.
--- Only the first 'maxShownKeyData' bytes of the data are written, then
--- its length, so that whoever writes a PSBT cannot make a refusal as
--- long as they like.
-showKey :: Key -> String
-showKey key =
-  "0x" <> hexByte key.keyType <> (if B.null key.keyData then "" else " with the data " <> shown)
-  where
-    hexByte b = (if b < 16 then "0" else "") <> showHex b ""
-    hexOf = concatMap hexByte . B.unpack
-    shown
-      | B.length key.keyData <= maxShownKeyData = hexOf key.keyData
-      | otherwise = hexOf (B.take maxShownKeyData key.keyData) <> "… (" <> show (B.length key.keyData) <> " bytes)"
-
--- | How many bytes of the data of a key a refusal writes: enough for a
--- compressed public key, which is 33 bytes
-maxShownKeyData :: Int
-maxShownKeyData = 40
-
-{- The shapes of the spec -}
-
--- | The data of a key of the spec: none, a public key, an extended public
--- key, an x-only public key, an x-only public key with a leaf hash, or a
--- control block
-data KeyShape = NoData | PublicKeyData | XpubData | XOnlyKeyData | KeyAndLeafData | ControlBlockData
-
--- | A field the spec defines: the shape of its key, the versions of the
--- PSBT that may hold it, and a check of its value given the data of the
--- key
-data Field = Field
-  { shape :: KeyShape,
-    versions :: [PsbtVersion],
-    checkValue :: ByteString -> ByteString -> Either String ()
-  }
-
--- | The fields the spec defines for a map, by type
-type Fields = Map Word8 Field
-
--- | A field of both versions whose key carries no data
-plain :: (ByteString -> Either String ()) -> Field
-plain = Field NoData [Version0, Version2] . const
-
--- | A field of version 2 only whose key carries no data
-plain2 :: (ByteString -> Either String ()) -> Field
-plain2 = Field NoData [Version2] . const
-
--- | Check every key of a map against the spec: the keys of the fields it
--- defines must be of the version, must have their shape and their values
--- must decode, and a proprietary key must have its identifier and subtype.
--- Other keys are not the spec's to check.
-checkMap :: String -> PsbtVersion -> Fields -> PsbtMap -> Either String ()
-checkMap what version fields m = forM_ (Map.toList m) $ \(key, value) ->
-  first ((capital what <> ": ") <>) $
-    case Map.lookup key.keyType fields of
-      Just field -> do
-        unless (version `elem` field.versions) $
-          Left ("the key " <> showKey key <> " is not of PSBT version " <> show (versionNumber version))
-        checkShape field.shape key
-        first (("the value of the key " <> showKey key <> " ") <>) $ field.checkValue key.keyData value
-      Nothing
-        | key.keyType == proprietaryType -> () <$ proprietaryOf key
-        | otherwise -> return ()
-
-checkShape :: KeyShape -> Key -> Either String ()
-checkShape shape key = case shape of
-  NoData -> unless (B.null key.keyData) $ Left ("the key " <> showKey key <> " carries data")
-  PublicKeyData -> unless (isPublicKeyBytes key.keyData) $ Left ("the key " <> showKey key <> " is not a public key")
-  XpubData -> unless (isXpubBytes key.keyData) $ Left ("the key " <> showKey key <> " is not an extended public key")
-  XOnlyKeyData -> unless (B.length key.keyData == 32) $ Left ("the key " <> showKey key <> " is not an x-only public key")
-  KeyAndLeafData -> unless (B.length key.keyData == 64) $ Left ("the key " <> showKey key <> " is not an x-only public key and a leaf hash")
-  ControlBlockData -> unless (isControlBlockLength (B.length key.keyData)) $ Left ("the key " <> showKey key <> " is not a control block")
-
--- | Whether a control block may have the length: 33 bytes plus 32 per
--- node, with at most 'maxControlBlockNodes' nodes
-isControlBlockLength :: Int -> Bool
-isControlBlockLength len =
-  len >= 33 && (len - 33) `mod` 32 == 0 && (len - 33) `div` 32 <= maxControlBlockNodes
-
--- | Whether the bytes are a public key, compressed or not: they have the
--- length and the first byte of one, and are a point of the curve, as
--- Bitcoin Core requires of the keys of a PSBT (@IsFullyValid@ in psbt.h).
-isPublicKeyBytes :: ByteString -> Bool
-isPublicKeyBytes bytes = shaped && isJust (importPubKey bytes)
-  where
-    shaped = case B.unpack (B.take 1 bytes) of
-      [0x02] -> B.length bytes == 33
-      [0x03] -> B.length bytes == 33
-      [0x04] -> B.length bytes == 65
-      _ -> False
-
--- | Whether the bytes are an extended public key as BIP 32 serializes
--- one: 78 bytes that end with a compressed public key
-isXpubBytes :: ByteString -> Bool
-isXpubBytes bytes = B.length bytes == 78 && B.length key == 33 && isPublicKeyBytes key
-  where
-    key = B.drop 45 bytes
-
--- | Whether the bytes are a signature as a script holds one: in the
--- encoding BIP 66 requires, with its sighash byte last. This is
--- @IsValidSignatureEncoding@ of Bitcoin Core (script/interpreter.cpp),
--- line for line. It checks the shape of the bytes, not the range of the
--- two numbers.
-isSignatureEncoding :: ByteString -> Bool
-isSignatureEncoding sig =
-  -- Minimum and maximum size
-  size >= 9
-    && size <= 73
-    -- A signature is of type 0x30 (compound)
-    && at 0 == 0x30
-    -- The length covers the entire signature, without the sighash byte
-    && fromIntegral (at 1) == size - 3
-    -- The length of the S element is still inside the signature
-    && 5 + lenR < size
-    -- The lengths of the two elements add up to the signature
-    && lenR + lenS + 7 == size
-    -- R is an integer, not empty, not negative, with no needless zero byte
-    && at 2 == 0x02
-    && lenR /= 0
-    && at 4 .&. 0x80 == 0
-    && not (lenR > 1 && at 4 == 0x00 && at 5 .&. 0x80 == 0)
-    -- S is an integer, not empty, not negative, with no needless zero byte
-    && at (lenR + 4) == 0x02
-    && lenS /= 0
-    && at (lenR + 6) .&. 0x80 == 0
-    && not (lenS > 1 && at (lenR + 6) == 0x00 && at (lenR + 7) .&. 0x80 == 0)
-  where
-    size = B.length sig
-    at = B.index sig
-    lenR = fromIntegral (at 3) :: Int
-    lenS = fromIntegral (at (5 + lenR)) :: Int
-
--- The unsigned transaction is checked apart, by 'unsignedTxOf', and the
--- version by 'versionOf'
-globalFields :: Fields
-globalFields =
-  Map.fromList
-    [ (unsignedTxType, Field NoData [Version0] (const anyValue)),
-      (xpubType, Field XpubData [Version0, Version2] xpubValue),
-      (txVersionType, plain2 word32Value),
-      (fallbackLockTimeType, plain2 word32Value),
-      (inputCountType, plain2 countValue),
-      (outputCountType, plain2 countValue),
-      (txModifiableType, plain2 flagsValue),
-      (versionType, plain word32Value)
-    ]
-  where
-    -- The path of an extended key has one index per level of its depth,
-    -- the fifth byte of the key
-    xpubValue keyData value = do
-      derivation <- decodeDerivation value
-      unless (length (pathToList derivation.path) == fromIntegral (B.index keyData 4)) $
-        Left "has a path that is not as deep as the key"
-    countValue value = () <$ decodeCount value
-    flagsValue value = unless (B.length value == 1) $ Left "is not a byte of flags"
-
-inputFields :: Fields
-inputFields =
-  Map.fromList
-    [ (nonWitnessUtxoType, plain txValue),
-      (witnessUtxoType, plain txOutValue),
-      (partialSigType, Field PublicKeyData [Version0, Version2] (const partialSigValue)),
-      (sigHashTypeType, plain word32Value),
-      (inRedeemScriptType, plain scriptValue),
-      (inWitnessScriptType, plain scriptValue),
-      (inDerivationType, Field PublicKeyData [Version0, Version2] (const derivationValue)),
-      (finalScriptSigType, plain anyValue),
-      (finalScriptWitnessType, plain witnessValue),
-      (tapKeySigType, plain tapSigValue),
-      (tapScriptSigType, Field KeyAndLeafData [Version0, Version2] (const tapSigValue)),
-      (tapLeafScriptType, Field ControlBlockData [Version0, Version2] (const leafScriptValue)),
-      (inTapDerivationType, Field XOnlyKeyData [Version0, Version2] (const tapDerivationValue)),
-      (inTapInternalKeyType, plain xOnlyKeyValue),
-      (tapMerkleRootType, plain hashValue),
-      (prevTxidType, plain2 txHashValue),
-      (outputIndexType, plain2 word32Value),
-      (sequenceType, plain2 word32Value),
-      (requiredTimeType, plain2 timeLockValue),
-      (requiredHeightType, plain2 heightLockValue)
-    ]
-  where
-    txValue value = () <$ (decodeTx value :: Either String Tx)
-    -- Bitcoin Core checks a partial signature with the flags DERSIG and
-    -- STRICTENC when it reads a PSBT: the encoding of BIP 66, and a sighash
-    -- byte that is ALL, NONE or SINGLE, with ANYONECANPAY or not. The fork
-    -- id flag is let through here, since the decoder knows no network; the
-    -- signer and the finalizer check it.
-    partialSigValue value =
-      unless (isSignatureEncoding value && not (isSigHashUnknown (fromIntegral (B.last value)))) $
-        Left "is not a signature in the encoding of BIP 66 with a defined sighash byte"
-    txOutValue value = () <$ (decodeTxOut value :: Either String TxOut)
-    witnessValue value = () <$ decodeWitness value
-    txHashValue value = () <$ decodeTxHash value
-    timeLockValue value = do
-      time <- decodeWord32le value
-      unless (time >= lockTimeThreshold) $ Left ("is a time lock below " <> show lockTimeThreshold)
-    heightLockValue value = do
-      height <- decodeWord32le value
-      unless (height > 0 && height < lockTimeThreshold) $ Left ("is not a height between 1 and " <> show (lockTimeThreshold - 1))
-
-outputFields :: Fields
-outputFields =
-  Map.fromList
-    [ (outRedeemScriptType, plain scriptValue),
-      (outWitnessScriptType, plain scriptValue),
-      (outDerivationType, Field PublicKeyData [Version0, Version2] (const derivationValue)),
-      (amountType, plain2 amountValue),
-      (outScriptType, plain2 anyValue),
-      (outTapInternalKeyType, plain xOnlyKeyValue),
-      (outTapTreeType, plain tapTreeValue),
-      (outTapDerivationType, Field XOnlyKeyData [Version0, Version2] (const tapDerivationValue))
-    ]
-  where
-    amountValue value = () <$ decodeWord64le value
-
-tapSigValue :: ByteString -> Either String ()
-tapSigValue value = () <$ first ("is not a Taproot signature: " <>) (decodeTaprootSig value)
-
-leafScriptValue :: ByteString -> Either String ()
-leafScriptValue value = when (B.null value) $ Left "has no leaf version"
-
-tapDerivationValue :: ByteString -> Either String ()
-tapDerivationValue value = () <$ decodeTapDerivation value
-
-xOnlyKeyValue :: ByteString -> Either String ()
-xOnlyKeyValue value = unless (B.length value == 32) $ Left "is not an x-only public key"
-
-hashValue :: ByteString -> Either String ()
-hashValue value = unless (B.length value == 32) $ Left "is not a 32-byte hash"
-
--- | A script tree as Bitcoin Core accepts one when it reads a PSBT: not
--- empty, no leaf deeper than 128, every leaf version even, and the leaves
--- those of one whole tree in depth-first order
-tapTreeValue :: ByteString -> Either String ()
-tapTreeValue value = do
-  leaves <- decodeTapTree value
-  when (null leaves) $ Left "is an empty script tree"
-  when (any ((> maxControlBlockNodes) . fromIntegral . (.depth)) leaves) $
-    Left ("has a leaf deeper than " <> show maxControlBlockNodes)
-  when (any (odd . (.version)) leaves) $ Left "has a leaf with an odd leaf version"
-  when (isNothing (tapTreeFromLeaves leaves)) $ Left "is not a whole script tree"
-
-word32Value :: ByteString -> Either String ()
-word32Value value = () <$ decodeWord32le value
-
-anyValue :: ByteString -> Either String ()
-anyValue _ = Right ()
-
-derivationValue :: ByteString -> Either String ()
-derivationValue value = () <$ decodeDerivation value
-
-scriptValue :: ByteString -> Either String ()
-scriptValue value = () <$ decodeScript value
-
-decodeTx :: ByteString -> Either String Tx
-decodeTx = decodeFully "is not a transaction: it"
-
-decodeTxOut :: ByteString -> Either String TxOut
-decodeTxOut = decodeFully "is not an output: it"
-
-decodeScript :: ByteString -> Either String Script
-decodeScript = decodeFully "is not a script: it"
-
-decodeWord32le :: ByteString -> Either String Word32
-decodeWord32le bytes
-  | B.length bytes == 4 = Right $ B.foldr (\b acc -> acc `shiftL` 8 .|. fromIntegral b) 0 bytes
-  | otherwise = Left "is not a 32-bit integer"
-
-decodeWord64le :: ByteString -> Either String Word64
-decodeWord64le bytes
-  | B.length bytes == 8 = Right $ B.foldr (\b acc -> acc `shiftL` 8 .|. fromIntegral b) 0 bytes
-  | otherwise = Left "is not a 64-bit integer"
-
-decodeTxHash :: ByteString -> Either String TxHash
-decodeTxHash = decodeFully "is not a transaction id: it"
-
--- | A count, as a compact size integer in its shortest form
-decodeCount :: ByteString -> Either String Int
-decodeCount bytes = do
-  n <- first (const "is not a count") (parseAll (compactSizeOf "a count") "a count" bytes)
-  when (n > fromIntegral (maxBound :: Int)) $ Left "is a count beyond any PSBT"
-  return (fromIntegral n)
-
--- | A witness stack: the number of items, then each item after its length
-decodeWitness :: ByteString -> Either String WitnessStack
-decodeWitness = parseAll stack "the final witness"
-  where
-    stack = do
-      count <- lengthOf "the final witness"
-      replicateM count (sizedBytes "the final witness")
-
-encodeWitness :: WitnessStack -> ByteString
-encodeWitness stack = compactSize (fromIntegral (length stack)) <> B.concat (sized <$> stack)
-
-{- Derivations -}
-
--- | How a key derives: the fingerprint of the key the path starts from,
--- the master key's as the spec wants it, and the path from it. A key
--- whose origin is unknown is named by its own fingerprint and an empty
--- path, or by the fingerprint of an ancestor and the path from it.
-data Derivation = Derivation
-  { fingerprint :: !Fingerprint,
-    path :: !DerivPath
-  }
-  deriving (Eq, Show, Read, Generic)
-  deriving anyclass (NFData)
-
-encodeDerivation :: Derivation -> ByteString
-encodeDerivation derivation =
-  S.encode derivation.fingerprint <> B.concat (word32le <$> pathToList derivation.path)
-
--- | A derivation: four bytes of fingerprint, then four per index of the
--- path, little-endian
-decodeDerivation :: ByteString -> Either String Derivation
-decodeDerivation bytes = do
-  unless (B.length bytes >= 4 && (B.length bytes - 4) `mod` 4 == 0) $
-    Left "is not a fingerprint and a path"
-  let (fingerprintBytes, pathBytes) = B.splitAt 4 bytes
-  fingerprint <- decodeFully "is not a fingerprint: it" fingerprintBytes
-  indices <- mapM decodeWord32le (chunksOf 4 pathBytes)
-  return $ Derivation fingerprint (listToPath indices)
-
-chunksOf :: Int -> ByteString -> [ByteString]
-chunksOf n bytes
-  | B.null bytes = []
-  | otherwise = let (chunk, rest) = B.splitAt n bytes in chunk : chunksOf n rest
-
--- | The records of the type whose keys are public keys, in the order of
--- the map, with their values decoded
-publicKeyRecords :: Word8 -> (ByteString -> Either String a) -> PsbtMap -> Either String [(PublicKey, a)]
-publicKeyRecords t decodeValue m =
-  forM [(key, value) | (key, value) <- Map.toAscList m, key.keyType == t] $ \(key, value) -> do
-    public <- first (const ("The key " <> showKey key <> " is not a public key")) (decodeSerial key.keyData)
-    decoded <- first (("The value of the key " <> showKey key <> " ") <>) (decodeValue value)
-    return (public, decoded)
-
-derivationsOf :: Word8 -> PsbtMap -> Either String [(PublicKey, Derivation)]
-derivationsOf t = publicKeyRecords t decodeDerivation
-
-insertDerivation :: Word8 -> PublicKey -> Derivation -> PsbtMap -> PsbtMap
-insertDerivation t public derivation = Map.insert (Key t (encodeSerial public)) (encodeDerivation derivation)
-
--- | The derivations of the keys of an input: PSBT_IN_BIP32_DERIVATION
-inputDerivations :: PsbtMap -> Either String [(PublicKey, Derivation)]
-inputDerivations = derivationsOf inDerivationType
-
-insertInputDerivation :: PublicKey -> Derivation -> PsbtMap -> PsbtMap
-insertInputDerivation = insertDerivation inDerivationType
-
--- | The derivations of the keys of an output: PSBT_OUT_BIP32_DERIVATION.
--- A record is a claim of whoever wrote the PSBT. To treat an output as
--- change, derive the key and compare it with the script of the output.
-outputDerivations :: PsbtMap -> Either String [(PublicKey, Derivation)]
-outputDerivations = derivationsOf outDerivationType
-
-insertOutputDerivation :: PublicKey -> Derivation -> PsbtMap -> PsbtMap
-insertOutputDerivation = insertDerivation outDerivationType
-
--- | The extended public keys of the global map, with their derivations:
--- PSBT_GLOBAL_XPUB. Those of another network, by their version bytes, are
--- left aside.
-xpubRecords :: Network -> PsbtMap -> Either String [(XPubKey, Derivation)]
-xpubRecords net m =
-  fmap catMaybes . forM [(key, value) | (key, value) <- Map.toAscList m, key.keyType == xpubType] $ \(key, value) -> do
-    derivation <- first (("The value of the key " <> showKey key <> " ") <>) (decodeDerivation value)
-    return $ (\xpub -> (xpub, derivation)) <$> eitherToMaybe (unmarshal net key.keyData)
-
-insertXpubRecord :: Network -> XPubKey -> Derivation -> PsbtMap -> PsbtMap
-insertXpubRecord net xpub derivation = Map.insert (Key xpubType (marshal net xpub)) (encodeDerivation derivation)
-
-{- The fields of an input and of an output -}
-
--- | The field of a type whose key carries no data, if the map has it
-plainField :: Word8 -> PsbtMap -> Maybe ByteString
-plainField t = Map.lookup (Key t B.empty)
-
-insertPlainField :: Word8 -> ByteString -> PsbtMap -> PsbtMap
-insertPlainField t = Map.insert (Key t B.empty)
-
-deletePlainField :: Word8 -> PsbtMap -> PsbtMap
-deletePlainField t = Map.delete (Key t B.empty)
-
--- | The whole transaction the input spends from: PSBT_IN_NON_WITNESS_UTXO
-nonWitnessUtxo :: PsbtMap -> Either String (Maybe Tx)
-nonWitnessUtxo = traverse (first ("The previous transaction " <>) . decodeTx) . plainField nonWitnessUtxoType
-
-insertNonWitnessUtxo :: Tx -> PsbtMap -> PsbtMap
-insertNonWitnessUtxo = insertPlainField nonWitnessUtxoType . S.encode
-
--- | The output the input spends, alone: PSBT_IN_WITNESS_UTXO
-witnessUtxo :: PsbtMap -> Either String (Maybe TxOut)
-witnessUtxo = traverse (first ("The witness output " <>) . decodeTxOut) . plainField witnessUtxoType
-
-insertWitnessUtxo :: TxOut -> PsbtMap -> PsbtMap
-insertWitnessUtxo = insertPlainField witnessUtxoType . S.encode
-
--- | The signatures of the input that are not final, by the public key each
--- is of, in the order of the map: PSBT_IN_PARTIAL_SIG. A signature is as
--- it goes in a script, with its sighash byte last.
-partialSignatures :: PsbtMap -> Either String [(PublicKey, ByteString)]
-partialSignatures = publicKeyRecords partialSigType Right
-
--- | Whether the input carries a signature that is not final
-hasPartialSignatures :: PsbtMap -> Bool
-hasPartialSignatures = any ((== partialSigType) . (.keyType)) . Map.keys
-
-insertPartialSignature :: PublicKey -> ByteString -> PsbtMap -> PsbtMap
-insertPartialSignature public = Map.insert (Key partialSigType (encodeSerial public))
-
--- | The map without its signatures that are not final, as a finalizer
--- leaves it
-deletePartialSignatures :: PsbtMap -> PsbtMap
-deletePartialSignatures = Map.filterWithKey (\key _ -> key.keyType /= partialSigType)
-
--- | The sighash the input is to be signed with: PSBT_IN_SIGHASH_TYPE
-sigHashType :: PsbtMap -> Either String (Maybe SigHash)
-sigHashType = traverse (fmap fromIntegral . first ("The sighash type " <>) . decodeWord32le) . plainField sigHashTypeType
-
-insertSigHashType :: SigHash -> PsbtMap -> PsbtMap
-insertSigHashType = insertPlainField sigHashTypeType . word32le . fromIntegral
-
--- | The map without the sighash the input was to be signed with, as a
--- finalizer leaves it
-deleteSigHashType :: PsbtMap -> PsbtMap
-deleteSigHashType = deletePlainField sigHashTypeType
-
--- | The script of a type whose key carries no data, if the map has it
-scriptField :: Word8 -> String -> PsbtMap -> Either String (Maybe Script)
-scriptField t what = traverse (first ((what <> " ") <>) . decodeScript) . plainField t
-
-insertScriptField :: Word8 -> Script -> PsbtMap -> PsbtMap
-insertScriptField t = insertPlainField t . S.encode
-
--- | The redeem script of the P2SH coin an input spends:
--- PSBT_IN_REDEEM_SCRIPT
-inputRedeemScript :: PsbtMap -> Either String (Maybe Script)
-inputRedeemScript = scriptField inRedeemScriptType "The redeem script"
-
-insertInputRedeemScript :: Script -> PsbtMap -> PsbtMap
-insertInputRedeemScript = insertScriptField inRedeemScriptType
-
--- | The witness script of the P2WSH coin an input spends:
--- PSBT_IN_WITNESS_SCRIPT
-inputWitnessScript :: PsbtMap -> Either String (Maybe Script)
-inputWitnessScript = scriptField inWitnessScriptType "The witness script"
-
-insertInputWitnessScript :: Script -> PsbtMap -> PsbtMap
-insertInputWitnessScript = insertScriptField inWitnessScriptType
-
--- | The input script of a signed input: PSBT_IN_FINAL_SCRIPTSIG
-finalScriptSig :: PsbtMap -> Maybe ByteString
-finalScriptSig = plainField finalScriptSigType
-
-insertFinalScriptSig :: ByteString -> PsbtMap -> PsbtMap
-insertFinalScriptSig = insertPlainField finalScriptSigType
-
--- | The witness of a signed input: PSBT_IN_FINAL_SCRIPTWITNESS
-finalScriptWitness :: PsbtMap -> Either String (Maybe WitnessStack)
-finalScriptWitness = traverse decodeWitness . plainField finalScriptWitnessType
-
-insertFinalScriptWitness :: WitnessStack -> PsbtMap -> PsbtMap
-insertFinalScriptWitness = insertPlainField finalScriptWitnessType . encodeWitness
-
--- | The redeem script of a P2SH output: PSBT_OUT_REDEEM_SCRIPT
-outputRedeemScript :: PsbtMap -> Either String (Maybe Script)
-outputRedeemScript = scriptField outRedeemScriptType "The redeem script"
-
-insertOutputRedeemScript :: Script -> PsbtMap -> PsbtMap
-insertOutputRedeemScript = insertScriptField outRedeemScriptType
-
--- | The witness script of a P2WSH output: PSBT_OUT_WITNESS_SCRIPT
-outputWitnessScript :: PsbtMap -> Either String (Maybe Script)
-outputWitnessScript = scriptField outWitnessScriptType "The witness script"
-
-insertOutputWitnessScript :: Script -> PsbtMap -> PsbtMap
-insertOutputWitnessScript = insertScriptField outWitnessScriptType
-
-{- The Taproot fields of BIP 371 -}
-
--- | The key path signature of a Taproot input: PSBT_IN_TAP_KEY_SIG
-tapKeySig :: PsbtMap -> Either String (Maybe TaprootSignature)
-tapKeySig = optionalField "The key path signature" tapKeySigType decodeTaprootSig
-
-insertTapKeySig :: TaprootSignature -> PsbtMap -> PsbtMap
-insertTapKeySig = insertPlainField tapKeySigType . encodeTaprootSig
-
--- | The script path signatures of a Taproot input, each by the x-only key
--- and the leaf hash it is for: PSBT_IN_TAP_SCRIPT_SIG
-tapScriptSigs :: PsbtMap -> Either String [((PubKey, Digest SHA256), TaprootSignature)]
-tapScriptSigs m =
-  forM [(key, value) | (key, value) <- Map.toAscList m, key.keyType == tapScriptSigType] $ \(key, value) -> do
-    let (keyBytes, leafBytes) = B.splitAt 32 key.keyData
-    leafKey <- maybe (Left ("The key " <> showKey key <> " is not an x-only public key and a leaf hash")) Right $ importXOnlyPubKey keyBytes
-    leaf <- maybe (Left ("The key " <> showKey key <> " is not an x-only public key and a leaf hash")) Right $ digestOf leafBytes
-    signature <- first (("The value of the key " <> showKey key <> " ") <>) (decodeTaprootSig value)
-    return ((leafKey, leaf), signature)
-
-insertTapScriptSig :: PubKey -> Digest SHA256 -> TaprootSignature -> PsbtMap -> PsbtMap
-insertTapScriptSig leafKey leaf signature =
-  Map.insert (Key tapScriptSigType (exportXOnlyPubKey leafKey <> BA.convert leaf)) (encodeTaprootSig signature)
-
--- | A leaf script a Taproot input may be spent with, and the control
--- block that commits it to the output key: PSBT_IN_TAP_LEAF_SCRIPT
-data TapLeafScript = TapLeafScript
-  { controlBlock :: !ByteString,
-    script :: !Script,
-    leafVersion :: !TapLeafVersion
-  }
-  deriving (Eq, Show, Read, Generic)
-  deriving anyclass (NFData)
-
--- | The leaf scripts of a Taproot input, with their control blocks:
--- PSBT_IN_TAP_LEAF_SCRIPT
-tapLeafScripts :: PsbtMap -> Either String [TapLeafScript]
-tapLeafScripts m =
-  forM [(key, value) | (key, value) <- Map.toAscList m, key.keyType == tapLeafScriptType] $ \(key, value) -> do
-    _ <- first (const ("The key " <> showKey key <> " is not a control block")) (decodeControlBlock key.keyData)
-    when (B.null value) $ Left ("The value of the key " <> showKey key <> " has no leaf version")
-    script <- first (("The value of the key " <> showKey key <> " ") <>) (decodeScript (B.init value))
-    return (TapLeafScript key.keyData script (B.last value))
-
-insertTapLeafScript :: TapLeafScript -> PsbtMap -> PsbtMap
-insertTapLeafScript leaf =
-  Map.insert (Key tapLeafScriptType leaf.controlBlock) (S.encode leaf.script <> B.singleton leaf.leafVersion)
-
--- | How an x-only key of a Taproot input or output derives, and the
--- leaves it appears in: the value of PSBT_IN_TAP_BIP32_DERIVATION and
--- PSBT_OUT_TAP_BIP32_DERIVATION. The internal key has no leaf.
-data TapDerivation = TapDerivation
-  { leafHashes :: ![Digest SHA256],
-    derivation :: !Derivation
-  }
-  deriving (Eq, Show, Generic)
-
-encodeTapDerivation :: TapDerivation -> ByteString
-encodeTapDerivation d =
-  compactSize (fromIntegral (length d.leafHashes)) <> B.concat (BA.convert <$> d.leafHashes) <> encodeDerivation d.derivation
-
--- | A Taproot derivation: the number of leaf hashes, the hashes, then the
--- fingerprint and the path
-decodeTapDerivation :: ByteString -> Either String TapDerivation
-decodeTapDerivation = parseAll record "a Taproot derivation"
-  where
-    record = do
-      count <- lengthOf "a Taproot derivation"
-      hashes <- replicateM count (bytesOf 32 "a Taproot derivation")
-      leaves <- maybe (refuse "is not a Taproot derivation") return (mapM digestOf hashes)
-      rest <- restOf
-      derivation <- either refuse return (decodeDerivation rest)
-      return (TapDerivation leaves derivation)
-
-tapDerivationsOf :: Word8 -> PsbtMap -> Either String [(PubKey, TapDerivation)]
-tapDerivationsOf t m =
-  forM [(key, value) | (key, value) <- Map.toAscList m, key.keyType == t] $ \(key, value) -> do
-    public <- maybe (Left ("The key " <> showKey key <> " is not an x-only public key")) Right (importXOnlyPubKey key.keyData)
-    decoded <- first (("The value of the key " <> showKey key <> " ") <>) (decodeTapDerivation value)
-    return (public, decoded)
-
-insertTapDerivation :: Word8 -> PubKey -> TapDerivation -> PsbtMap -> PsbtMap
-insertTapDerivation t public d = Map.insert (Key t (exportXOnlyPubKey public)) (encodeTapDerivation d)
-
--- | The derivations of the x-only keys of a Taproot input, each with the
--- leaves it appears in: PSBT_IN_TAP_BIP32_DERIVATION. The key is the
--- point of even y with that x coordinate.
-inputTapDerivations :: PsbtMap -> Either String [(PubKey, TapDerivation)]
-inputTapDerivations = tapDerivationsOf inTapDerivationType
-
-insertInputTapDerivation :: PubKey -> TapDerivation -> PsbtMap -> PsbtMap
-insertInputTapDerivation = insertTapDerivation inTapDerivationType
-
--- | The derivations of the x-only keys of a Taproot output:
--- PSBT_OUT_TAP_BIP32_DERIVATION. A record is a claim of whoever wrote the
--- PSBT, as for 'outputDerivations'.
-outputTapDerivations :: PsbtMap -> Either String [(PubKey, TapDerivation)]
-outputTapDerivations = tapDerivationsOf outTapDerivationType
-
-insertOutputTapDerivation :: PubKey -> TapDerivation -> PsbtMap -> PsbtMap
-insertOutputTapDerivation = insertTapDerivation outTapDerivationType
-
-xOnlyKeyField :: Word8 -> String -> PsbtMap -> Either String (Maybe PubKey)
-xOnlyKeyField t what = optionalField what t (maybe (Left "is not an x-only public key") Right . importXOnlyPubKey)
-
-insertXOnlyKeyField :: Word8 -> PubKey -> PsbtMap -> PsbtMap
-insertXOnlyKeyField t = insertPlainField t . exportXOnlyPubKey
-
--- | The internal key of the Taproot coin an input spends:
--- PSBT_IN_TAP_INTERNAL_KEY. The key is the point of even y with that x
--- coordinate.
-inputTapInternalKey :: PsbtMap -> Either String (Maybe PubKey)
-inputTapInternalKey = xOnlyKeyField inTapInternalKeyType "The internal key"
-
-insertInputTapInternalKey :: PubKey -> PsbtMap -> PsbtMap
-insertInputTapInternalKey = insertXOnlyKeyField inTapInternalKeyType
-
--- | The root of the script tree of the Taproot coin an input spends:
--- PSBT_IN_TAP_MERKLE_ROOT
-inputTapMerkleRoot :: PsbtMap -> Either String (Maybe (Digest SHA256))
-inputTapMerkleRoot = optionalField "The Merkle root" tapMerkleRootType (maybe (Left "is not a 32-byte hash") Right . digestOf)
-
-insertInputTapMerkleRoot :: Digest SHA256 -> PsbtMap -> PsbtMap
-insertInputTapMerkleRoot = insertPlainField tapMerkleRootType . BA.convert
-
--- | The internal key of a Taproot output: PSBT_OUT_TAP_INTERNAL_KEY
-outputTapInternalKey :: PsbtMap -> Either String (Maybe PubKey)
-outputTapInternalKey = xOnlyKeyField outTapInternalKeyType "The internal key"
-
-insertOutputTapInternalKey :: PubKey -> PsbtMap -> PsbtMap
-insertOutputTapInternalKey = insertXOnlyKeyField outTapInternalKeyType
-
--- | The script tree of a Taproot output, as its leaves depth first:
--- PSBT_OUT_TAP_TREE. 'tapTreeFromLeaves' builds the tree.
-outputTapTree :: PsbtMap -> Either String (Maybe [TapLeaf])
-outputTapTree = optionalField "The script tree" outTapTreeType decodeTapTree
-
-insertOutputTapTree :: [TapLeaf] -> PsbtMap -> PsbtMap
-insertOutputTapTree leaves = insertPlainField outTapTreeType (B.concat (encodeLeaf <$> leaves))
-  where
-    encodeLeaf :: TapLeaf -> ByteString
-    encodeLeaf leaf = B.pack [leaf.depth, leaf.version] <> sized (S.encode leaf.script)
-
--- | A script tree: for each leaf, its depth, its leaf version and its
--- script after its length
-decodeTapTree :: ByteString -> Either String [TapLeaf]
-decodeTapTree = parseAll leaves "a script tree"
-  where
-    leaves = do
-      rest <- restOf
-      if B.null rest
-        then return []
-        else do
-          BytesParser (\_ -> Right ((), rest)) -- put the bytes back
-          depth <- B.head <$> bytesOf 1 "a script tree"
-          version <- B.head <$> bytesOf 1 "a script tree"
-          scriptBytes <- sizedBytes "a script tree"
-          script <- either refuse return (decodeScript scriptBytes)
-          (TapLeaf depth version script :) <$> leaves
-
--- | A 32-byte hash as a digest
-digestOf :: ByteString -> Maybe (Digest SHA256)
-digestOf = digestFromByteString
-
-{- The fields of version 2 -}
-
--- | The flags of PSBT_GLOBAL_TX_MODIFIABLE: whether inputs may be added,
--- whether outputs may be added, and whether an input is signed with
--- SIGHASH_SINGLE, which pairs it with the output at its index. The other
--- bits of the byte are not defined; they are kept as they are.
-data Modifiable = Modifiable
-  { inputsModifiable :: !Bool,
-    outputsModifiable :: !Bool,
-    hasSigHashSingle :: !Bool,
-    undefinedBits :: !Word8
-  }
-  deriving (Eq, Show, Read, Generic)
-  deriving anyclass (NFData)
-
--- | No flag set
-noFlags :: Modifiable
-noFlags = Modifiable False False False 0
-
--- | The flags of the global map, if it has the field: PSBT_GLOBAL_TX_MODIFIABLE
-txModifiable :: PsbtMap -> Either String (Maybe Modifiable)
-txModifiable = optionalField "The modifiable flags" txModifiableType decodeFlags
-  where
-    decodeFlags value = case B.unpack value of
-      [byte] -> Right $ Modifiable (testBit byte 0) (testBit byte 1) (testBit byte 2) (byte .&. 0xf8)
-      _ -> Left "are not one byte"
-
-insertTxModifiable :: Modifiable -> PsbtMap -> PsbtMap
-insertTxModifiable flags = insertPlainField txModifiableType (B.singleton byte)
-  where
-    byte = bit 0 flags.inputsModifiable .|. bit 1 flags.outputsModifiable .|. bit 2 flags.hasSigHashSingle .|. (flags.undefinedBits .&. 0xf8)
-    bit :: Int -> Bool -> Word8
-    bit n set = if set then 1 `shiftL` n else 0
-
--- | The global map without the flags, which a constructor may remove once
--- nothing is to be added
-deleteTxModifiable :: PsbtMap -> PsbtMap
-deleteTxModifiable = deletePlainField txModifiableType
-
--- | The lock time of the transaction when no input requires one:
--- PSBT_GLOBAL_FALLBACK_LOCKTIME
-fallbackLockTime :: PsbtMap -> Either String (Maybe Word32)
-fallbackLockTime = optionalField "The fallback lock time" fallbackLockTimeType decodeWord32le
-
--- | The least time, as a Unix timestamp, the input requires as the lock
--- time of the transaction: PSBT_IN_REQUIRED_TIME_LOCKTIME
-requiredTimeLockTime :: PsbtMap -> Either String (Maybe Word32)
-requiredTimeLockTime = optionalField "The required time lock time" requiredTimeType decodeWord32le
-
-insertRequiredTimeLockTime :: Word32 -> PsbtMap -> PsbtMap
-insertRequiredTimeLockTime = insertPlainField requiredTimeType . word32le
-
--- | The least block height the input requires as the lock time of the
--- transaction: PSBT_IN_REQUIRED_HEIGHT_LOCKTIME
-requiredHeightLockTime :: PsbtMap -> Either String (Maybe Word32)
-requiredHeightLockTime = optionalField "The required height lock time" requiredHeightType decodeWord32le
-
-insertRequiredHeightLockTime :: Word32 -> PsbtMap -> PsbtMap
-insertRequiredHeightLockTime = insertPlainField requiredHeightType . word32le
-
-{- Proprietary fields -}
-
--- | A proprietary field, of type 0xFC: the identifier of the software it
--- belongs to, its subtype under that identifier, and the data after the
--- subtype, none for most
-data Proprietary = Proprietary
-  { identifier :: !ByteString,
-    subtype :: !Word64,
-    extra :: !ByteString
-  }
-  deriving (Eq, Show, Read, Generic)
-  deriving anyclass (NFData)
-
--- | The key of a proprietary field: the type 0xFC, the identifier after
--- its length, the subtype as a compact size integer, and the data
-proprietaryKey :: Proprietary -> Key
-proprietaryKey p =
-  Key proprietaryType (sized p.identifier <> compactSize p.subtype <> p.extra)
-
--- | The proprietary field a key is, if it is one: nothing for a key of
--- another type, a refusal for a proprietary key without its identifier
--- and subtype
-proprietaryOf :: Key -> Either String (Maybe Proprietary)
-proprietaryOf key
-  | key.keyType /= proprietaryType = Right Nothing
-  | otherwise =
-      first (const ("the proprietary key " <> showKey key <> " has no identifier and subtype")) $
-        Just <$> parseAll (Proprietary <$> sizedBytes what <*> compactSizeOf what <*> restOf) what key.keyData
-  where
-    what = "a proprietary key"
-
--- | The value of the proprietary field of the identifier and subtype,
--- with no data after the subtype, if the map has it
-lookupProprietary :: ByteString -> Word64 -> PsbtMap -> Maybe ByteString
-lookupProprietary identifier subtype = Map.lookup (proprietaryKey (Proprietary identifier subtype B.empty))
-
-insertProprietary :: ByteString -> Word64 -> ByteString -> PsbtMap -> PsbtMap
-insertProprietary identifier subtype = Map.insert (proprietaryKey (Proprietary identifier subtype B.empty))
-
-{- Signing -}
-
--- | Where a signer gets its private keys: by a derivation record naming a
--- public key, or by the hash of a public key when the input has no record
--- for it. A key that is not held is 'Nothing'. The signer also says which
--- sighash types it agrees to sign with, and whether it wants the previous
--- transaction of a SegWit version 0 coin.
-data Signer = Signer
-  { -- | the private key of the public key a derivation record names
-    keyOfRecord :: PublicKey -> Derivation -> Maybe SecKey,
-    -- | the private key whose public key, compressed or not, has the hash
-    keyOfHash :: Hash160 -> Maybe PrivateKey,
-    -- | the sighash types the signer signs with. An input that asks for
-    -- another type is refused, as BIP 174 asks of a signer. The fork id
-    -- flag does not count, since the network decides it.
-    acceptedSigHashes :: [SigHash],
-    -- | whether a SegWit version 0 coin (P2WPKH or P2WSH, nested in P2SH
-    -- or not) is signed only when the input carries its previous
-    -- transaction. A BIP 143 signature commits to the amount of its own
-    -- coin and to no other. With the witness output alone, whoever writes
-    -- the PSBT can lie about the amount of one coin of the signer in each
-    -- of two signing rounds, keep the valid signature of each round, and
-    -- make a transaction that pays the difference as fee
-    -- (CVE-2020-14199). BIP 174 lets a signer "fail to sign a segwit
-    -- input if a non-witness UTXO is not provided" for this reason. A
-    -- Taproot signature commits to the amount of every coin and needs no
-    -- such care.
-    requirePreviousTx :: Bool
-  }
-
--- | The sighash types a signer accepts unless told otherwise:
--- 'sigHashDefault', which a Taproot input uses when it asks for none, and
--- 'sigHashAll'. The other types leave part of the transaction out of the
--- signature, so a PSBT written by someone else may not ask for them on its
--- own; a signer that agrees to them lists them, for example
--- @(keySigner key) {acceptedSigHashes = sigHashNone : defaultSigHashes}@.
-defaultSigHashes :: [SigHash]
-defaultSigHashes = [sigHashDefault, sigHashAll]
-
--- | Whether the signer accepts the sighash type: it is one of its types,
--- the fork id flag aside
-acceptsSigHash :: Signer -> SigHash -> Bool
-acceptsSigHash signer sighash =
-  withoutForkId sighash `elem` map withoutForkId signer.acceptedSigHashes
-  where
-    withoutForkId = (.&. complement forkIdBit)
-    forkIdBit = fromIntegral (fromEnum SIGHASH_FORKID)
-
--- | A signer that holds one private key, for the records of its public
--- key and for the hash of its public key in either form. It wants the
--- previous transaction of a SegWit version 0 coin ('requirePreviousTx').
--- A caller that has checked the amounts of its coins another way, for
--- example against its own records, turns that off with
--- @(keySigner key) {requirePreviousTx = False}@.
-keySigner :: SecKey -> Signer
-keySigner secret =
-  Signer
-    { keyOfRecord = \public _ -> do
-        guard (public.point == derivePubKey secret)
-        return secret,
-      keyOfHash = \h -> find ((== h) . addressHash . encodeSerial . derivePublicKey) [PrivateKey secret True, PrivateKey secret False],
-      acceptedSigHashes = defaultSigHashes,
-      requirePreviousTx = True
-    }
-
--- | A signer that derives from an extended private key. A record names a
--- key it derives by the fingerprint of the extended key and the path from
--- it, or, when the origin of the extended key is given, by the
--- fingerprint of that origin and the path from it, which starts with the
--- path of the extended key. A path the key cannot follow, such as one
--- deeper than the 255 levels of BIP 32 or one with a hardened step
--- below a key that cannot derive it, names no key. It has no key for a
--- hash, since it cannot know which path to derive. Like 'keySigner', it
--- wants the previous transaction of a SegWit version 0 coin.
-xPrvSigner :: XPrvKey -> Maybe Derivation -> Signer
-xPrvSigner xprv originM =
-  Signer
-    { keyOfRecord = \public derivation -> do
-        path <- relative derivation
-        secret <- (.key) <$> eitherToMaybe (tryDerivePath path xprv)
-        guard (public.point == derivePubKey secret)
-        return secret,
-      keyOfHash = const Nothing,
-      acceptedSigHashes = defaultSigHashes,
-      requirePreviousTx = True
-    }
-  where
-    own = xPubFP (deriveXPubKey xprv)
-    relative :: Derivation -> Maybe DerivPath
-    relative derivation
-      | derivation.fingerprint == own = Just derivation.path
-      | Just origin <- originM,
-        derivation.fingerprint == origin.fingerprint =
-          listToPath <$> stripPrefix (pathToList origin.path) (pathToList derivation.path)
-      | otherwise = Nothing
-
--- | Sign every input the signer has keys for, as the signer of the spec
--- does. An input is signed against the coin it spends, from its previous
--- transaction, whose id must be the one the input spends, or from its
--- witness output alone, which only a witness signature may use, as BIP
--- 174 requires.
---
--- The keys are those the script that is signed names: the script of the
--- coin, its redeem script or its witness script. The signer is asked for
--- the key of a derivation record only when that script names the key of
--- the record, and for the key of each hash the script names. A key that
--- the script does not name gets no signature, whatever the records say,
--- and a P2SH coin without its redeem script or a P2WSH coin without its
--- witness script gets none either, as BIP 174 has it: "If a Signer cannot
--- sign a transaction, it must not add a Partial Signature."
---
--- The sighash is the one the input asks for. When it asks for none it is
--- SIGHASH_ALL, with the fork id flag on a network that has one. A type no
--- node accepts, or one the signer does not accept ('acceptedSigHashes'),
--- is refused on any input that has its coin, as Bitcoin Core refuses a
--- PSBT with a sighash type the caller did not ask for.
---
--- An input the signer holds a key for is refused, with the reason, when:
---
--- * its redeem script does not hash to the coin, or its witness script to
---   the witness program;
--- * it is a legacy coin known from its witness output only;
--- * it is a SegWit version 0 coin known from its witness output only and
---   the signer wants the previous transaction ('requirePreviousTx');
--- * the key is uncompressed and the coin is a SegWit version 0 one, which
---   no node relays and Bitcoin Core does not sign;
--- * it is a legacy coin asked to sign SIGHASH_SINGLE with no output at its
---   index, as 'makeSignature' explains.
---
--- A Taproot coin is signed by its key path when the input has its internal
--- key, which with the Merkle root must give the output key, and by each of
--- its leaf scripts that is a single key check (@<key> OP_CHECKSIG@) and
--- that its control block commits to the output key, with 'sigHashDefault'
--- when the input asks for no sighash. The BIP 341 digest commits to the
--- output every input spends, so every input must have its coin then.
---
--- An input without its coin, with a final script already, with a coin,
--- redeem script or witness script that is no standard template, or for
--- which the signer holds no key, is left as it is.
-signPsbt :: Network -> Signer -> Psbt -> Either String Psbt
-signPsbt net signer psbt = do
-  coins <- spentOutputs psbt
-  let allCoins = mapM (fmap fst) coins
-  signed <- forM (zip3 [0 ..] (zip tx.inputs psbt.inputs) coins) $ \(i, (input, m), coinM) ->
-    first (("Input " <> show i <> ": ") <>) $ case coinM of
-      Just (coin, witnessOnly)
-        | not (isFinal m),
-          Right coinScript <- decodeSerial coin.script -> do
-            sighashM <- sigHashType m
-            if isTaprootCoin coinScript
-              then signTaproot i m coinScript sighashM allCoins
-              else signEcdsa i input m coin coinScript witnessOnly sighashM
-      _ -> return (m, [])
-  return $ foldr afterSignature (Psbt psbt.version tx psbt.globals (fst <$> signed) psbt.outputs) (concatMap snd signed)
-  where
-    tx = psbt.unsignedTx
-
-    -- A signature per key the signer holds among those the script names,
-    -- for a coin signed with ECDSA
-    signEcdsa i input m coin coinScript witnessOnly sighashM = do
-      let sighash = fromMaybe (defaultEcdsaSigHash net) sighashM
-      checkEcdsaSigHash net sighash
-      unless (acceptsSigHash signer sighash) $
-        Left (notAcceptedSigHash sighash)
-      scriptsM <- inputScripts coinScript m
-      case scriptsM of
-        Nothing -> return (m, [])
-        Just scripts -> do
-          keys <- heldKeys m (maybe [] scriptKeyHashes scripts.signedScript)
-          if null keys
-            then return (m, [])
-            else do
-              forM_ scripts.mismatch Left
-              let witnessCoin = isSegwit scripts.program
-              when (witnessOnly && not witnessCoin) $
-                Left "the coin is given as a witness output only, which may not be signed with a non-witness signature"
-              when (witnessOnly && witnessCoin && signer.requirePreviousTx) $
-                Left "the coin is given as a witness output only, and the signer requires the previous transaction of a SegWit version 0 coin"
-              when (witnessCoin && not (all (.compress) keys)) $
-                Left "a SegWit version 0 coin may not be signed with an uncompressed key"
-              let sigInput = signingInput input coin sighash scripts
-              signatures <- forM keys $ \key -> do
-                signature <- makeSignature net tx i sigInput key
-                return (derivePublicKey key, encodeTxSig net signature)
-              return (foldr (\(public, sig) -> insertPartialSignature public sig) m signatures, [sighash])
-
-    -- The keys the signer holds among those whose hashes the script that
-    -- is signed names. The signer is asked for the key of a derivation
-    -- record only when the hash of the key of the record is one of them,
-    -- so the work it does is bounded by the script, however many records
-    -- the PSBT carries. A key the signer gives is kept only when it is the
-    -- key that was asked for.
-    heldKeys :: PsbtMap -> [Hash160] -> Either String [PrivateKey]
-    heldKeys m named = do
-      let namedRecords = [(key, value) | (key, value) <- Map.toAscList m, key.keyType == inDerivationType, addressHash key.keyData `elem` named]
-      recordKeys <- forM namedRecords $ \(key, value) -> do
-        public <- first (const ("The key " <> showKey key <> " is not a public key")) (decodeSerial key.keyData)
-        derivation <- first (("The value of the key " <> showKey key <> " ") <>) (decodeDerivation value)
-        return [PrivateKey secret public.compress | Just secret <- [signer.keyOfRecord public derivation], derivePubKey secret == public.point]
-      let hashKeys = [key | h <- named, Just key <- [signer.keyOfHash h], addressHash (encodeSerial (derivePublicKey key)) == h]
-      return $ nubBy (\a b -> derivePublicKey a == derivePublicKey b) (concat recordKeys <> hashKeys)
-
-    -- A key path signature, and one per leaf that is a single key check,
-    -- for a Taproot coin
-    signTaproot i m coinScript sighashM allCoins = do
-      let sighash = fromMaybe sigHashDefault sighashM
-      unless (isTaprootSigHash sighash) $
-        Left ("the sighash type " <> show (fromIntegral sighash :: Word32) <> " is not one a Taproot signature may use")
-      unless (acceptsSigHash signer sighash) $
-        Left (notAcceptedSigHash sighash)
-      spent <- maybe (Left "a Taproot signature needs the output every input spends") Right allCoins
-      program <- taprootProgram coinScript
-      internalM <- inputTapInternalKey m
-      rootM <- inputTapMerkleRoot m
-      records <- inputTapDerivations m
-      leaves <- tapLeafScripts m
-      -- The secret key of an x-only key, by a record of that key which
-      -- the test accepts, or by the hash of the key. A key the signer
-      -- gives is kept only when it is the key that was asked for.
-      let heldXOnly accepts public =
-            listToMaybe . filter (sameX public . derivePubKey) . catMaybes $
-              [signer.keyOfRecord (PublicKey candidate True) d.derivation | (recordKey, d) <- records, sameX recordKey public, accepts d, candidate <- bothParities public]
-                <> [(.key) <$> signer.keyOfHash (addressHash (encodeSerial (PublicKey candidate True))) | candidate <- bothParities public]
-      keySig <- case internalM of
-        Nothing -> return []
-        Just internal -> do
-          let expected = taprootOutputKey (TaprootOutput internal (MASTCommitment <$> rootM))
-          unless (exportXOnlyPubKey expected == program) $
-            Left "the internal key and the Merkle root do not give the output key of the coin"
-          -- Any record of the internal key will do: BIP 371 lists in a
-          -- record the leaves the key is in, and the internal key may be
-          -- in a leaf too
-          case heldXOnly (const True) internal of
-            Nothing -> return []
-            Just secret -> do
-              tweaked <- maybe (Left "the key cannot be tweaked") Right (taprootOutputSecKey secret (MASTCommitment <$> rootM))
-              h <- taprootSigHash tx spent i sighash Nothing Nothing
-              signature <- taprootSignature (signSchnorr tweaked (hashToMsg h)) sighash
-              return [insertTapKeySig signature]
-      scriptSigs <- fmap concat . forM leaves $ \leaf -> case singleKeyLeaf leaf of
-        Just leafKey
-          -- Only a leaf of the coin is signed: its control block must
-          -- commit it to the output key
-          | Just outKey <- importXOnlyPubKey program,
-            commitsLeaf outKey leaf,
-            Just secret <- heldXOnly ((hashOfLeaf `elem`) . (.leafHashes)) leafKey -> do
-              h <- taprootSigHash tx spent i sighash Nothing (Just (hashOfLeaf, 0xffffffff))
-              signature <- taprootSignature (signSchnorr secret (hashToMsg h)) sighash
-              return [insertTapScriptSig leafKey hashOfLeaf signature]
-          where
-            hashOfLeaf = leafHash leaf.leafVersion leaf.script
-        _ -> return []
-      let inserts = keySig <> scriptSigs
-      return (foldr ($) m inserts, [sighash | not (null inserts)])
-
-    sameX a b = exportXOnlyPubKey a == exportXOnlyPubKey b
-    -- The two points with the x coordinate of the key
-    bothParities public =
-      mapMaybe (\prefix -> (.point) <$> eitherToMaybe (decodeSerial (B.cons prefix (exportXOnlyPubKey public)) :: Either String PublicKey)) [0x02, 0x03]
-
--- | The sighash type of an ECDSA signature for an input that asks for
--- none: SIGHASH_ALL, with the fork id flag on a network that has one
-defaultEcdsaSigHash :: Network -> SigHash
-defaultEcdsaSigHash net
-  | isJust net.sigHashForkId = setForkIdFlag sigHashAll
-  | otherwise = sigHashAll
-
--- | The hashes of the keys a script names: the keys a coin of that script
--- is signed with
-scriptKeyHashes :: ScriptOutput -> [Hash160]
-scriptKeyHashes = \case
-  PayPK public -> [addressHash (encodeSerial public)]
-  PayPKHash h -> [h]
-  PayWitnessPKHash h -> [h]
-  PayMulSig publics _ -> map (addressHash . encodeSerial) publics
-  _ -> []
-
--- | The leaf key of a leaf script that is a single key check, @<key>
--- OP_CHECKSIG@ of leaf version 0xc0
-singleKeyLeaf :: TapLeafScript -> Maybe PubKey
-singleKeyLeaf leaf = case leaf.script.ops of
-  [OP_PUSHDATA keyBytes OPCODE, OP_CHECKSIG]
-    | leaf.leafVersion == tapscriptLeafVersion -> importXOnlyPubKey keyBytes
-  _ -> Nothing
-
--- | Whether the control block of a leaf script commits the leaf to the
--- output key of the coin
-commitsLeaf :: PubKey -> TapLeafScript -> Bool
-commitsLeaf outKey leaf = case decodeControlBlock leaf.controlBlock of
-  Right (v, internalKey, proof) ->
-    verifyScriptPathData outKey (ScriptPathData Nothing [] leaf.script (odd v) (v .&. 0xfe) internalKey proof Nothing)
-  Left _ -> False
-
--- | The error for a sighash type the signer does not accept
-notAcceptedSigHash :: SigHash -> String
-notAcceptedSigHash sighash =
-  "the sighash type " <> show (fromIntegral sighash :: Word32) <> " is not one the signer accepts"
-
--- | A sighash type an ECDSA signature may carry on the network: one of
--- ALL, NONE and SINGLE, with ANYONECANPAY or not, and the fork id flag
--- exactly on the networks with a fork id
-checkEcdsaSigHash :: Network -> SigHash -> Either String ()
-checkEcdsaSigHash net sighash = do
-  when (isSigHashUnknown sighash) $
-    Left ("the sighash type " <> show (fromIntegral sighash :: Word32) <> " is not one a node accepts")
-  when (isJust net.sigHashForkId && not (hasForkIdFlag sighash)) $
-    Left "the sighash type lacks the fork id flag the network requires"
-  when (isNothing net.sigHashForkId && hasForkIdFlag sighash) $
-    Left "the sighash type has a fork id flag the network does not use"
-
--- | Whether a coin is a Taproot output, and its program
-isTaprootCoin :: ScriptOutput -> Bool
-isTaprootCoin = either (const False) (const True) . taprootProgram
-
-taprootProgram :: ScriptOutput -> Either String ByteString
-taprootProgram = \case
-  PayWitness 1 program | B.length program == 32 -> Right program
-  _ -> Left "not a Taproot output"
-
--- | The PSBT after a signature with the sighash was added, as the signer
--- of BIP 370 leaves the flags of version 2: inputs may no longer be added
--- unless the sighash has ANYONECANPAY, outputs no longer unless it is
--- NONE, and the PSBT has a SIGHASH_SINGLE signature when it is SINGLE. A
--- PSBT of version 0 has no flags.
-afterSignature :: SigHash -> Psbt -> Psbt
-afterSignature sighash psbt = case psbt.version of
-  Version0 -> psbt
-  Version2
-    | isJust beforeM || after /= noFlags -> Psbt Version2 psbt.unsignedTx (insertTxModifiable after psbt.globals) psbt.inputs psbt.outputs
-    | otherwise -> psbt
-  where
-    beforeM = either (const Nothing) id (txModifiable psbt.globals)
-    before = fromMaybe noFlags beforeM
-    after =
-      before
-        { inputsModifiable = before.inputsModifiable && anyoneCanPay sighash,
-          outputsModifiable = before.outputsModifiable && isSigHashNone sighash,
-          hasSigHashSingle = before.hasSigHashSingle || isSigHashSingle sighash
-        }
-
--- | Whether an input has its final script or witness
-isFinal :: PsbtMap -> Bool
-isFinal m = any (`Map.member` m) [Key finalScriptSigType B.empty, Key finalScriptWitnessType B.empty]
-
-{- The coins of a PSBT -}
-
--- | The coin an input of a PSBT spends, as the PSBT gives it
-data InputCoin = InputCoin
-  { -- | the output the input spends: its amount and its script
-    coin :: !TxOut,
-    -- | 'True' when the coin is the output of the previous transaction of
-    -- the input, whose id the input names, so that it cannot be made up.
-    -- 'False' when the PSBT gives the output alone (PSBT_IN_WITNESS_UTXO):
-    -- its amount is then a claim of whoever wrote the PSBT.
-    fromPreviousTx :: !Bool
-  }
-  deriving (Eq, Show, Read, Generic)
-  deriving anyclass (NFData)
-
--- | The coin every input of a PSBT spends, 'Nothing' for an input that
--- carries none. A previous transaction must be the one its input spends
--- and have the output it spends, and a witness output given with it must
--- be that output.
---
--- An amount with 'fromPreviousTx' is checked. Another is only checked by a
--- signature that commits to it: a SegWit version 0 signature commits to
--- the amount of its own coin, and a Taproot signature to the amount of
--- every coin of the transaction. Show a user amounts and a fee from
--- checked coins only, or from a PSBT in which the user signs a Taproot
--- input.
-inputCoins :: Psbt -> Either String [Maybe InputCoin]
-inputCoins psbt = map (fmap (\(output, witnessOnly) -> InputCoin output (not witnessOnly))) <$> spentOutputs psbt
-
--- | The fee of the transaction of a PSBT: what its coins hold above what
--- its outputs pay. Every input must carry its previous transaction, so
--- that no amount is a claim ('inputCoins' tells which are). A PSBT whose
--- outputs pay more than its coins hold has no fee.
-psbtFee :: Psbt -> Either String Word64
-psbtFee psbt = do
-  coins <- inputCoins psbt
-  amounts <- forM (zip [0 :: Int ..] coins) $ \(i, coinM) -> case coinM of
-    Nothing -> Left ("Input " <> show i <> " has no coin")
-    Just found
-      | found.fromPreviousTx -> Right (toInteger found.coin.value)
-      | otherwise -> Left ("Input " <> show i <> ": the coin is given as a witness output only, so its amount is not checked")
-  let fee = sum amounts - sum (toInteger . (.value) <$> psbt.unsignedTx.outputs)
-  when (fee < 0) $ Left "The outputs pay more than the coins hold"
-  return (fromInteger fee)
-
--- | The output every input spends, from the fields of each input, and
--- whether it is known from the witness output alone
-spentOutputs :: Psbt -> Either String [Maybe (TxOut, Bool)]
-spentOutputs psbt =
-  forM (zip3 [0 :: Int ..] psbt.unsignedTx.inputs psbt.inputs) $ \(i, input, m) ->
-    first (("Input " <> show i <> ": ") <>) (spentOutput input m)
-
--- | The output an input spends, from the fields of the input: the output
--- of its previous transaction, which must be the transaction the input
--- spends from, or else its witness output alone. With both, the witness
--- output must be that output. The flag tells when the witness output
--- alone is known, which only a witness signature may rely on.
-spentOutput :: TxIn -> PsbtMap -> Either String (Maybe (TxOut, Bool))
-spentOutput input m = do
-  witnessM <- witnessUtxo m
-  parentM <- nonWitnessUtxo m
-  case (parentM, witnessM) of
-    (Just parent, _) -> do
-      output <- previousOutput input parent
-      forM_ witnessM $ \witnessCoin ->
-        unless (witnessCoin == output) $
-          Left "the witness output of the input is not the output of its previous transaction"
-      return (Just (output, False))
-    (Nothing, Just output) -> return (Just (output, True))
-    (Nothing, Nothing) -> return Nothing
-
--- | What the scripts of an input say about how its coin is signed
-data InputScripts = InputScripts
-  { -- | the script the coin is signed against: the script of the coin, or
-    -- the witness program its redeem script is when it is nested in P2SH
-    program :: ScriptOutput,
-    -- | the script that names the keys: the script of the coin, its
-    -- redeem script or its witness script. 'Nothing' when the input does
-    -- not have the redeem or witness script its coin needs.
-    signedScript :: Maybe ScriptOutput,
-    -- | why a redeem or witness script of the input does not fit its coin
-    mismatch :: Maybe String
-  }
-
--- | The scripts of an input, from the script of its coin and its redeem
--- and witness scripts. A redeem script must hash to the coin, and a
--- witness script to the witness program, as BIP 174 requires of a signer:
--- one that does not is reported in 'mismatch'. 'Nothing' when the script
--- that names the keys is no standard template: the library cannot sign or
--- finalize such an input, and leaves it to others.
-inputScripts :: ScriptOutput -> PsbtMap -> Either String (Maybe InputScripts)
-inputScripts coinScript m = do
-  redeemM <- inputRedeemScript m
-  witnessM <- inputWitnessScript m
-  let redeemOutM = decodeOutput <$> redeemM
-      witnessOutM = decodeOutput <$> witnessM
-      -- A SegWit coin, nested in P2SH or not, is signed against its witness
-      -- program; any other against its own script
-      program = case redeemOutM of
-        Just (Right redeem) | not (isSegwit coinScript), isSegwit redeem -> redeem
-        _ -> coinScript
-      redeemMismatch = case redeemM of
-        Just redeem
-          | not (isPayScriptHash coinScript) -> Just "the input has a redeem script, but its coin is not pay-to-script-hash"
-          | toP2SH redeem /= Right coinScript -> Just "the redeem script of the input does not hash to its coin"
-        _ -> Nothing
-      witnessMismatch = case witnessM of
-        Just witness
-          | not (isPayWitnessScriptHash program) -> Just "the input has a witness script, but its coin is not pay-to-witness-script-hash"
-          | toP2WSH witness /= Right program -> Just "the witness script of the input does not hash to its witness program"
-        _ -> Nothing
-      -- The script that names the keys, as it decodes
-      naming = case program of
-        PayWitnessScriptHash _ -> witnessOutM
-        PayScriptHash _ -> redeemOutM
-        _ -> Just (Right program)
-  return $ case naming of
-    Just (Left _) -> Nothing
-    _ ->
-      Just
-        InputScripts
-          { program = program,
-            signedScript = naming >>= eitherToMaybe,
-            mismatch = listToMaybe (catMaybes [redeemMismatch, witnessMismatch])
-          }
-
--- | What an input is signed against, as 'makeSignature' wants it: the
--- script of its coin or its witness program, with the redeem script of a
--- P2SH coin or the witness script of a P2WSH coin
-signingInput :: TxIn -> TxOut -> SigHash -> InputScripts -> SigInput
-signingInput input output sighash scripts =
-  SigInput
-    { script = scripts.program,
-      value = output.value,
-      outpoint = input.outpoint,
-      sighash = sighash,
-      redeem = case scripts.program of
-        PayWitnessScriptHash _ -> scripts.signedScript
-        PayScriptHash _ -> scripts.signedScript
-        _ -> Nothing
-    }
-
-{- Finalizing -}
-
--- | Finalize every input whose signatures suffice for the coin it spends,
--- as the finalizer of the spec does: the final script and witness go in
--- the input, and its partial signatures, sighash type, redeem script,
--- witness script, derivation records and Taproot fields go, as Bitcoin
--- Core clears them. Its coin and the keys the spec does not define stay.
---
--- Only the signatures of the keys the script of the coin names are
--- looked at. Each one is verified first, against the digest of the coin,
--- which is computed once per sighash type. A signature that does not
--- verify, or is of an uncompressed key on a SegWit version 0 coin, is
--- refused, as @PSBTInputSignedAndVerified@ and the standard script flags
--- refuse it in Bitcoin Core. Every signature of the input must use the
--- sighash type the input names, and SIGHASH_ALL when it names none
--- (SIGHASH_DEFAULT for a Taproot coin, and with the fork id flag on a
--- network that has one), as Bitcoin Core requires.
---
--- The coins finalized are those of P2PK, P2PKH and multisig scripts, P2SH
--- coins with their redeem script, P2WPKH coins, P2WSH coins with their
--- witness script, nested in P2SH or not, and Taproot coins by their key
--- path signature or by a leaf script that is a single key check. Any
--- other input stays as it is: one without enough signatures, one whose
--- scripts are no standard template, and a legacy coin known from its
--- witness output only, which Bitcoin Core does not finalize either.
-finalizePsbt :: Network -> Psbt -> Either String Psbt
-finalizePsbt net psbt = do
-  coins <- spentOutputs psbt
-  let allCoins = mapM (fmap fst) coins
-  inputs <- forM (zip3 [0 ..] (zip tx.inputs psbt.inputs) coins) $ \(i, (input, m), coinM) ->
-    first (("Input " <> show i <> ": ") <>) $ case coinM of
-      Just (output :: TxOut, witnessOnly)
-        | not (isFinal m),
-          Right coinScript <- decodeSerial output.script -> do
-            finals <-
-              if isTaprootCoin coinScript
-                then finalTaprootScripts tx allCoins i m coinScript
-                else finalScripts net tx i input output witnessOnly coinScript m
-            return $ case finals of
-              Just (scriptSig, stack) ->
-                foldr ($) (cleared m) $
-                  [insertFinalScriptSig scriptSig | not (B.null scriptSig)]
-                    <> [insertFinalScriptWitness stack | not (null stack)]
-              Nothing -> m
-      _ -> return m
-  return $ Psbt psbt.version tx psbt.globals inputs psbt.outputs
-  where
-    tx = psbt.unsignedTx
-    cleared = Map.filterWithKey (\key _ -> key.keyType `notElem` clearedTypes)
-    clearedTypes =
-      [partialSigType, sigHashTypeType, inRedeemScriptType, inWitnessScriptType, inDerivationType, tapKeySigType, tapScriptSigType, tapLeafScriptType, inTapDerivationType, inTapInternalKeyType, tapMerkleRootType]
-
--- | The final script and witness of an input signed with ECDSA, from the
--- partial signatures of the keys its script names, when they suffice.
--- Each of those signatures is verified first.
-finalScripts :: Network -> Tx -> Int -> TxIn -> TxOut -> Bool -> ScriptOutput -> PsbtMap -> Either String (Maybe (ByteString, WitnessStack))
-finalScripts net tx i input output witnessOnly coinScript m = do
-  sighashM <- sigHashType m
-  scriptsM <- inputScripts coinScript m
-  case scriptsM of
-    Nothing -> return Nothing
-    Just scripts
-      -- Only a witness signature may rely on a witness output
-      | witnessOnly && not (isSegwit scripts.program) -> return Nothing
-      | otherwise -> do
-          forM_ scripts.mismatch Left
-          let asked = fromMaybe (defaultEcdsaSigHash net) sighashM
-              otherType keyBytes =
-                Left $
-                  "the signature of the key " <> quoted keyBytes <> case sighashM of
-                    Just _ -> " does not use the sighash type of the input"
-                    Nothing -> " does not use SIGHASH_ALL, and the input names no sighash type"
-              sigInput = signingInput input output asked scripts
-              named = maybe [] (namedSignatures m) scripts.signedScript
-          -- The signatures of the keys the script names: each is a
-          -- signature, of the sighash type asked, by a key the coin may be
-          -- spent with
-          checked <- forM named $ \(public, bytes) -> do
-            (sig, sh) <- case decodeTxSig net bytes of
-              Right (TxSignature sig sh) -> return (sig, sh)
-              _ -> Left ("the signature of the key " <> quoted (encodeSerial public) <> " is not a valid signature")
-            unless (sh == asked) $ otherType (encodeSerial public)
-            when (isSegwit scripts.program && not public.compress) $
-              Left ("the signature of the key " <> quoted (encodeSerial public) <> " is of an uncompressed key, which a SegWit version 0 coin may not be spent with")
-            return (public, sig)
-          -- Every other signature of the input uses that sighash type too:
-          -- its last byte tells, and nothing else of it is looked at
-          forM_ [(key, sig) | (key, sig) <- Map.toAscList m, key.keyType == partialSigType] $ \(key, sig) ->
-            unless (not (B.null sig) && B.last sig == fromIntegral (asked .&. 0xff)) $ otherType key.keyData
-          if null checked
-            then return Nothing
-            else do
-              -- One digest serves every signature, since all use one type
-              digest <- makeSigHash net tx i sigInput.script output.value asked sigInput.redeem
-              forM_ checked $ \(public, sig) ->
-                unless (verifyHashSig digest sig public.point) $
-                  Left ("the signature of the key " <> quoted (encodeSerial public) <> " does not verify")
-              return (assemble scripts named)
-  where
-    quoted = show . encodeHex
-    -- The final script and witness, from the signatures of the keys the
-    -- script names
-    assemble :: InputScripts -> [(PublicKey, ByteString)] -> Maybe (ByteString, WitnessStack)
-    assemble scripts named = case coinScript of
-      PayScriptHash _ -> do
-        redeem <- either (const Nothing) id (inputRedeemScript m)
-        if isSegwit scripts.program
-          then (scriptOf [S.encode redeem],) <$> witnessOf scripts named
-          else (\found -> (scriptOf (found <> [S.encode redeem]), [])) <$> (items named =<< scripts.signedScript)
-      _
-        | isSegwit coinScript -> (B.empty,) <$> witnessOf scripts named
-        | otherwise -> (\found -> (scriptOf found, [])) <$> (items named =<< scripts.signedScript)
-    -- The witness of a SegWit coin: the items of its program, with the
-    -- witness script last for P2WSH
-    witnessOf :: InputScripts -> [(PublicKey, ByteString)] -> Maybe [ByteString]
-    witnessOf scripts named = case scripts.program of
-      PayWitnessScriptHash _ -> do
-        witnessScript <- either (const Nothing) id (inputWitnessScript m)
-        (<> [S.encode witnessScript]) <$> (items named =<< scripts.signedScript)
-      _ -> items named =<< scripts.signedScript
-    -- The items a script is spent with: the pushes of an input script,
-    -- or the items of a witness
-    items :: [(PublicKey, ByteString)] -> ScriptOutput -> Maybe [ByteString]
-    items named = \case
-      PayPK public -> (: []) <$> lookup public named
-      PayPKHash h -> withKey <$> ofHash named h
-      PayMulSig keys n -> (B.empty :) <$> enough named keys n
-      PayWitnessPKHash h -> withKey <$> ofHash named h
-      _ -> Nothing
-    ofHash :: [(PublicKey, ByteString)] -> Hash160 -> Maybe (PublicKey, ByteString)
-    ofHash named h = listToMaybe [(public, signature) | (public, signature) <- named, addressHash (encodeSerial public) == h]
-    enough :: [(PublicKey, ByteString)] -> [PublicKey] -> Int -> Maybe [ByteString]
-    enough named keys n = let found = mapMaybe (`lookup` named) keys in if length found >= n then Just (take n found) else Nothing
-    withKey :: (PublicKey, ByteString) -> [ByteString]
-    withKey (public, signature) = [signature, encodeSerial public]
-    scriptOf = S.encode . Script . map opPushData
-
--- | The partial signatures of an input whose keys the script names, in
--- the order of the map. A key is named by a script of public keys when it
--- is one of them, and by a script of a key hash when it has that hash.
--- The others are not looked at, so their number costs nothing.
-namedSignatures :: PsbtMap -> ScriptOutput -> [(PublicKey, ByteString)]
-namedSignatures m script =
-  [ (public, sig)
-  | (key, sig) <- Map.toAscList m,
-    key.keyType == partialSigType,
-    addressHash key.keyData `elem` named,
-    Right public <- [decodeSerial key.keyData]
-  ]
-  where
-    named = scriptKeyHashes script
-
--- | The final witness of a Taproot input: its key path signature, or the
--- signature of the first leaf script that is a single key check with the
--- script and its control block. Every signature is verified first,
--- against the output key and the digest of its leaf. A signature must
--- use the sighash type the input names, and SIGHASH_DEFAULT when it names
--- none, as Bitcoin Core requires.
-finalTaprootScripts :: Tx -> Maybe [TxOut] -> Int -> PsbtMap -> ScriptOutput -> Either String (Maybe (ByteString, WitnessStack))
-finalTaprootScripts tx allCoins i m coinScript = do
-  program <- taprootProgram coinScript
-  outKey <- maybe (Left "the coin is not a Taproot output") Right (importXOnlyPubKey program)
-  sighashM <- sigHashType m
-  keySigM <- tapKeySig m
-  scriptSigs <- tapScriptSigs m
-  leaves <- tapLeafScripts m
-  let sameType :: TaprootSignature -> Either String ()
-      sameType signature = case sighashM of
-        Just asked -> unless (signature.hash == asked) $ Left "a Taproot signature does not use the sighash type of the input"
-        Nothing -> unless (signature.hash == sigHashDefault) $ Left "a Taproot signature does not use SIGHASH_DEFAULT, and the input names no sighash type"
-  -- Every signature of the input, used or not, as Bitcoin Core checks them
-  mapM_ sameType (maybeToList keySigM <> map snd scriptSigs)
-  case keySigM of
-    Just signature -> do
-      spent <- maybe (Left "a Taproot signature needs the output every input spends") Right allCoins
-      digest <- taprootSigHash tx spent i signature.hash Nothing Nothing
-      unless (verifySchnorr outKey signature.sig (hashToMsg digest)) $
-        Left "the key path signature does not verify"
-      return (Just (B.empty, [encodeTaprootSig signature]))
-    Nothing -> do
-      let candidates =
-            [ (leaf, leafKey, signature)
-            | leaf <- leaves,
-              Just leafKey <- [singleKeyLeaf leaf],
-              Just signature <- [lookup (leafKey, leafHash leaf.leafVersion leaf.script) [((k, h), sig) | ((k, h), sig) <- scriptSigs, sameX k leafKey]]
-            ]
-      case candidates of
-        [] -> return Nothing
-        (leaf, leafKey, signature) : _ -> do
-          spent <- maybe (Left "a Taproot signature needs the output every input spends") Right allCoins
-          unless (commitsLeaf outKey leaf) $
-            Left "the control block of the leaf does not commit it to the output key"
-          digest <- taprootSigHash tx spent i signature.hash Nothing (Just (leafHash leaf.leafVersion leaf.script, 0xffffffff))
-          unless (verifySchnorr leafKey signature.sig (hashToMsg digest)) $
-            Left "the script path signature does not verify"
-          return (Just (B.empty, [encodeTaprootSig signature, S.encode leaf.script, leaf.controlBlock]))
-  where
-    sameX a b = exportXOnlyPubKey a == exportXOnlyPubKey b
+-- __The order of the rules.__ Where the BIPs decide, the module does what
+-- they say. Where they are silent or leave a choice open, it does what
+-- Bitcoin Core does, checked against Bitcoin Core 32.1 on regtest. Where
+-- neither decides, it takes the safer choice for the user. The few places
+-- where it does not do as Bitcoin Core are named where they are: in
+-- 'decodePsbt', 'signPsbt', 'finalizePsbt', 'combinePsbt' and
+-- 'psbtTransaction'.
+--
+-- The maps are kept as they are read, byte for byte, so that every field
+-- passes through, known or not. A map is written with its keys in the
+-- order of their bytes, the type first. BIP 174 fixes no order, and
+-- Bitcoin Core writes another one, so the two write the same PSBT with
+-- other bytes, and each reads the bytes of the other. 'decodePsbt' tells
+-- what is refused when a PSBT is read.
+--
+-- The signer and the finalizer take one input at a time, as Bitcoin Core
+-- does: an input that cannot be signed or finalized stays as it is, and
+-- the others go on. 'signPsbt' and 'finalizePsbt' give the rules.
+--
+-- The amounts a PSBT states are claims of whoever wrote it, unless the
+-- input carries its previous transaction. 'inputCoins' tells which coins
+-- are checked, 'psbtFee' gives the fee from checked coins only, and the
+-- signers want the previous transaction of a SegWit version 0 coin
+-- ('requirePreviousTx'). The derivation records of outputs are claims
+-- too: to treat an output as change, derive its key and compare.
+--
+-- The fields the spec defines are read and written with the functions
+-- below, with the Taproot fields of
+-- [BIP 371](https://github.com/bitcoin/bips/blob/master/bip-0371.mediawiki).
+-- The hash preimages of BIP 174 and the MuSig2 fields of
+-- [BIP 373](https://github.com/bitcoin/bips/blob/master/bip-0373.mediawiki)
+-- are checked when a PSBT is read, and kept: the module does not sign with
+-- them.
+-- The roles of the spec are here too: a creator ('psbtOf'), a
+-- constructor ('addInput', 'addOutput'), a combiner ('combinePsbt'), a
+-- signer ('signPsbt'), a finalizer ('finalizePsbt') and a transaction
+-- extractor ('psbtTransaction'), which wants every input final. An updater
+-- is the functions that insert fields, and 'setInputSequence'.
+module Haskoin.Transaction.Psbt
+  ( -- * A PSBT
+    Psbt (..),
+    PsbtVersion (..),
+    Key (..),
+    PsbtMap,
+    psbtOf,
+    psbtOfMaps,
+    withVersion,
+    psbtId,
+    combinePsbt,
+    psbtTransaction,
+    psbtPartialTransaction,
+
+    -- * The inputs and outputs of version 2
+    addInput,
+    addOutput,
+    setInputSequence,
+    Modifiable (..),
+    txModifiable,
+    insertTxModifiable,
+    deleteTxModifiable,
+    fallbackLockTime,
+    requiredTimeLockTime,
+    insertRequiredTimeLockTime,
+    requiredHeightLockTime,
+    insertRequiredHeightLockTime,
+
+    -- * Bytes and text
+    psbtMagic,
+    isPsbt,
+    encodePsbt,
+    decodePsbt,
+    encodePsbtBase64,
+    decodePsbtBase64,
+
+    -- * The global fields
+    Derivation (..),
+    xpubRecords,
+    insertXpubRecord,
+
+    -- * The fields of an input
+    nonWitnessUtxo,
+    insertNonWitnessUtxo,
+    witnessUtxo,
+    insertWitnessUtxo,
+    partialSignatures,
+    hasPartialSignatures,
+    insertPartialSignature,
+    deletePartialSignatures,
+    sigHashType,
+    insertSigHashType,
+    deleteSigHashType,
+    inputRedeemScript,
+    insertInputRedeemScript,
+    inputWitnessScript,
+    insertInputWitnessScript,
+    inputDerivations,
+    insertInputDerivation,
+    finalScriptSig,
+    insertFinalScriptSig,
+    finalScriptWitness,
+    insertFinalScriptWitness,
+
+    -- * The Taproot fields of an input
+    tapKeySig,
+    insertTapKeySig,
+    tapScriptSigs,
+    insertTapScriptSig,
+    TapLeafScript (..),
+    tapLeafScripts,
+    insertTapLeafScript,
+    TapDerivation (..),
+    inputTapDerivations,
+    insertInputTapDerivation,
+    inputTapInternalKey,
+    insertInputTapInternalKey,
+    inputTapMerkleRoot,
+    insertInputTapMerkleRoot,
+
+    -- * The fields of an output
+    outputRedeemScript,
+    insertOutputRedeemScript,
+    outputWitnessScript,
+    insertOutputWitnessScript,
+    outputDerivations,
+    insertOutputDerivation,
+    outputTapInternalKey,
+    insertOutputTapInternalKey,
+    outputTapTree,
+    insertOutputTapTree,
+    outputTapDerivations,
+    insertOutputTapDerivation,
+
+    -- * Proprietary fields
+    Proprietary (..),
+    proprietaryKey,
+    proprietaryOf,
+    lookupProprietary,
+    insertProprietary,
+
+    -- * The coins of a PSBT
+    InputCoin (..),
+    inputCoins,
+    psbtFee,
+
+    -- * Signing
+    Signer (..),
+    defaultSigHashes,
+    keySigner,
+    xPrvSigner,
+    signPsbt,
+    afterSignature,
+
+    -- * Finalizing
+    finalizePsbt,
+  )
+where
+
+import Control.Applicative ((<|>))
+import Control.DeepSeq (NFData)
+import Control.Monad (ap, forM, forM_, guard, mfilter, replicateM, unless, when, zipWithM)
+import Crypto.Hash (Digest, SHA256, digestFromByteString)
+import Crypto.Secp256k1 (PubKey, SecKey, derivePubKey, exportXOnlyPubKey, importPubKey, importXOnlyPubKey, signSchnorr, verifySchnorr)
+import Data.Base64.Types (extractBase64)
+import Data.Bifunctor (first)
+import Data.Bits (complement, shiftL, testBit, (.&.), (.|.))
+import Data.ByteArray qualified as BA
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as B
+import Data.ByteString.Base64 (decodeBase64Untyped, encodeBase64')
+import Data.Char (toUpper)
+import Data.List (find, minimumBy, nubBy, stripPrefix)
+import Data.Map.Strict (Map)
+import Data.Map.Strict qualified as Map
+import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, listToMaybe, mapMaybe, maybeToList)
+import Data.Ord (comparing)
+import Data.Serialize qualified as S
+import Data.Word (Word32, Word64, Word8)
+import GHC.Generics (Generic)
+import Haskoin.Crypto.Hash (Hash160, addressHash, doubleSHA256, ripemd160, sha256)
+import Haskoin.Crypto.Keys.Common
+import Haskoin.Crypto.Keys.Extended
+import Haskoin.Crypto.Signature (hashToMsg, verifyHashSig)
+import Haskoin.Network.Common (VarInt (..))
+import Haskoin.Network.Data
+import Haskoin.Script.Common
+import Haskoin.Script.SigHash
+import Haskoin.Script.Standard
+import Haskoin.Transaction.Builder.Sign (SigInput (..), makeSigHashWith, makeSignatureWith)
+import Haskoin.Transaction.Common hiding (decodeTx)
+import Haskoin.Transaction.Segwit (isSegwit)
+import Haskoin.Transaction.Taproot
+import Haskoin.Util
+import Numeric (showHex)
+import Text.Read (readMaybe)
+
+{- A PSBT -}
+
+-- | A key of a map: its type, and the data after the type byte. Most
+-- fields have none; a derivation or a signature has the public key it is
+-- of. The type of a key is a compact size integer. Every type the spec
+-- defines fits one byte. A type from 253 on takes three or five bytes on
+-- the wire: its first byte, 0xfd or 0xfe, is the 'keyType' here, and the
+-- other bytes of the type are the start of the 'keyData', where
+-- 'decodePsbt' requires them to be the shortest form of the type.
+data Key = Key
+  { keyType :: !Word8,
+    keyData :: !ByteString
+  }
+  deriving (Eq, Ord, Show, Read, Generic)
+  deriving anyclass (NFData)
+
+-- | A map of a PSBT. It is written with its keys in the order of their
+-- bytes, the type first. BIP 174 fixes no order. Bitcoin Core writes
+-- another one: the fields in the order of its code, a partial signature
+-- by the hash of its key, the fields of version 2 after the Taproot
+-- fields. So the bytes of the library and those of Bitcoin Core differ
+-- for the same PSBT.
+type PsbtMap = Map Key ByteString
+
+-- | The version of a PSBT: 0, the version of BIP 174, whose global map
+-- holds the unsigned transaction, or 2, the version of BIP 370, whose maps
+-- hold the transaction field by field, so that inputs and outputs can be
+-- added. There is no version 1.
+data PsbtVersion = Version0 | Version2
+  deriving (Eq, Ord, Show, Read, Generic)
+  deriving anyclass (NFData)
+
+versionNumber :: PsbtVersion -> Word32
+versionNumber Version0 = 0
+versionNumber Version2 = 2
+
+-- | A PSBT: its version, the unsigned transaction, the global map, and the
+-- maps of the inputs and of the outputs, one each, in the order of the
+-- transaction. In version 0, the global map is kept without the unsigned
+-- transaction. In version 2, the maps keep the fields that describe the
+-- transaction, and the unsigned transaction is the one they describe, with
+-- the lock time they determine.
+--
+-- In version 2 the record so holds the transaction twice. 'signPsbt' signs
+-- 'unsignedTx', and 'encodePsbt' writes the maps. A record update that
+-- changes one and not the other gives a PSBT whose bytes describe another
+-- transaction than the one that is signed. Change the transaction of such a
+-- PSBT with 'addInput', 'addOutput' and 'psbtOfMaps', which keep the two in
+-- step.
+data Psbt = Psbt
+  { version :: !PsbtVersion,
+    unsignedTx :: !Tx,
+    globals :: !PsbtMap,
+    inputs :: ![PsbtMap],
+    outputs :: ![PsbtMap]
+  }
+  deriving (Eq, Show, Read, Generic)
+  deriving anyclass (NFData)
+
+-- | The PSBT of a transaction, with nothing else, as the creator of the
+-- spec makes it, in version 0: the transaction without its input scripts
+-- and witness, and an empty map per input and per output. 'withVersion'
+-- makes it one of version 2.
+psbtOf :: Tx -> Psbt
+psbtOf tx =
+  Psbt
+    { version = Version0,
+      unsignedTx = Tx tx.version [TxIn input.outpoint B.empty input.sequence | input <- tx.inputs] tx.outputs [] tx.locktime,
+      globals = Map.empty,
+      inputs = Map.empty <$ tx.inputs,
+      outputs = Map.empty <$ tx.outputs
+    }
+
+-- | The PSBT whose maps these are, as they are in its bytes: the global
+-- map names the version, and holds the unsigned transaction in version 0.
+-- The maps are checked against the spec of the version, and in version 2
+-- the transaction is read from their fields.
+psbtOfMaps :: PsbtMap -> [PsbtMap] -> [PsbtMap] -> Either String Psbt
+psbtOfMaps globals inputs outputs = do
+  (version, inputCount, outputCount) <- countsOf globals
+  unless (length inputs == inputCount) $
+    Left ("The PSBT has " <> show (length inputs) <> " inputs, and its global map counts " <> show inputCount)
+  unless (length outputs == outputCount) $
+    Left ("The PSBT has " <> show (length outputs) <> " outputs, and its global map counts " <> show outputCount)
+  forM_ (zip [0 :: Int ..] inputs) $ \(i, m) -> checkMap ("input " <> show i) version inputFields m
+  forM_ (zip [0 :: Int ..] outputs) $ \(i, m) -> checkMap ("output " <> show i) version outputFields m
+  tx <- case version of
+    Version0 -> unsignedTxOf globals
+    Version2 -> transactionOf globals inputs outputs
+  forM_ (zip3 [0 :: Int ..] tx.inputs inputs) $ \(i, input, m) ->
+    first (("Input " <> show i <> ": ") <>) (checkPreviousTx input m)
+  return $ Psbt version tx (Map.delete unsignedTxKey globals) inputs outputs
+
+-- | The previous transaction of an input, when its map has one, must be
+-- the transaction the input spends from and have the output it spends, as
+-- Bitcoin Core requires when it reads a PSBT ("Non-witness UTXO does not
+-- match outpoint hash", psbt.h)
+checkPreviousTx :: TxIn -> PsbtMap -> Either String ()
+checkPreviousTx input m = do
+  parentM <- nonWitnessUtxo m
+  forM_ parentM (previousOutput input)
+
+-- | The output an input spends, from its previous transaction: the
+-- transaction must be the one the input names, and have that output
+previousOutput :: TxIn -> Tx -> Either String TxOut
+previousOutput input parent = do
+  unless (txHash parent == input.outpoint.hash) $
+    Left "the previous transaction is not the one the input spends"
+  maybe (Left "the input spends an output its previous transaction does not have") Right $
+    listToMaybe (drop (fromIntegral input.outpoint.index) parent.outputs)
+
+-- | The PSBT in the version given, as BIP 370 converts one. To version 2:
+-- the transaction goes in the fields of the maps, its lock time as the
+-- fallback. To version 0: the fields of version 2 leave the maps, and the
+-- transaction keeps the lock time they determined.
+withVersion :: PsbtVersion -> Psbt -> Psbt
+withVersion v psbt
+  | v == psbt.version = psbt
+  | v == Version2 =
+      Psbt
+        Version2
+        tx
+        (withTxFields tx (insertPlainField versionType (word32le 2) psbt.globals))
+        (zipWith withInputFields tx.inputs psbt.inputs)
+        (zipWith withOutputFields tx.outputs psbt.outputs)
+  | otherwise =
+      Psbt
+        Version0
+        tx
+        (without globalV2Types (deletePlainField versionType psbt.globals))
+        (without inputV2Types <$> psbt.inputs)
+        (without outputV2Types <$> psbt.outputs)
+  where
+    tx = psbt.unsignedTx
+    without :: [Word8] -> PsbtMap -> PsbtMap
+    without types = Map.filterWithKey (\key _ -> key.keyType `notElem` types)
+
+-- | What identifies a PSBT: the id of its unsigned transaction. In version
+-- 2 the sequence of every input is taken as 0 for it, as BIP 370 says,
+-- since an updater may change the sequences.
+psbtId :: Psbt -> TxHash
+psbtId psbt = txHash $ case psbt.version of
+  Version0 -> tx
+  Version2 -> Tx tx.version [TxIn input.outpoint input.script 0 | input <- tx.inputs] tx.outputs tx.witness tx.locktime
+  where
+    tx = psbt.unsignedTx
+
+-- | The PSBT with the fields of both, as the combiner of the spec makes
+-- it. Both must be of the same version and of the same transaction. A
+-- field both have, with different values, keeps the value of the first.
+-- Every field of both is kept, as BIP 174 asks: "The resulting PSBT must
+-- contain all of the key-value pairs from each of the PSBTs". Bitcoin Core
+-- drops the fields of the signers from an input that is final, which
+-- 'finalizePsbt' does here.
+-- The flags of version 2 are combined as Bitcoin Core combines them:
+-- inputs and outputs stay modifiable only when both say so, and a
+-- SIGHASH_SINGLE signature of either is kept.
+combinePsbt :: Psbt -> Psbt -> Either String Psbt
+combinePsbt a b = do
+  unless (a.version == b.version) $ Left "The PSBTs are not of the same version"
+  unless (psbtId a == psbtId b) $ Left "The PSBTs are not of the same transaction"
+  let globals = combinedFlags (Map.union a.globals b.globals)
+      inputs = zipWith Map.union a.inputs b.inputs
+      outputs = zipWith Map.union a.outputs b.outputs
+  case a.version of
+    Version0 -> return $ Psbt Version0 a.unsignedTx globals inputs outputs
+    Version2 -> (\tx -> Psbt Version2 tx globals inputs outputs) <$> transactionOf globals inputs outputs
+  where
+    combinedFlags globals = case (flagsOf a, flagsOf b) of
+      (Nothing, Nothing) -> globals
+      (x, y) ->
+        let fx = fromMaybe noFlags x
+            fy = fromMaybe noFlags y
+         in insertTxModifiable
+              (Modifiable (fx.inputsModifiable && fy.inputsModifiable) (fx.outputsModifiable && fy.outputsModifiable) (fx.hasSigHashSingle || fy.hasSigHashSingle) (fx.undefinedBits .&. fy.undefinedBits))
+              globals
+    flagsOf :: Psbt -> Maybe Modifiable
+    flagsOf psbt = either (const Nothing) id (txModifiable psbt.globals)
+
+-- | The transaction of a PSBT whose inputs are all final, with their final
+-- scripts and witnesses, as the transaction extractor of the spec builds
+-- it. BIP 174 has the extractor check "whether all inputs have complete
+-- scriptSigs and scriptWitnesses" first, and Bitcoin Core gives no
+-- transaction otherwise (@FinalizeAndExtractPSBT@), so an input that is
+-- not final is refused here. 'psbtPartialTransaction' takes such a PSBT.
+-- The check is the one of BIP 174, "by checking for the presence of" the
+-- final fields: an input needs no coin for it. Bitcoin Core also wants
+-- the coin of each input, to run its final script.
+--
+-- The final scripts are taken as they are: nothing runs them. Finalize
+-- with 'finalizePsbt', which verifies the signatures it uses, or verify
+-- the transaction before it is sent.
+psbtTransaction :: Psbt -> Either String Tx
+psbtTransaction psbt = do
+  forM_ (zip [0 :: Int ..] psbt.inputs) $ \(i, m) ->
+    unless (isFinal m) $ Left ("Input " <> show i <> " is not final")
+  psbtPartialTransaction psbt
+
+-- | The transaction of a PSBT with the final script and witness of every
+-- input that has them. An input without them stays unsigned, so the
+-- transaction may not be valid yet: this is for looking at a PSBT that is
+-- still being signed, not for sending. 'psbtTransaction' is the extractor.
+psbtPartialTransaction :: Psbt -> Either String Tx
+psbtPartialTransaction psbt = do
+  finals <- forM (zip psbt.unsignedTx.inputs psbt.inputs) $ \(input, m) -> do
+    stack <- fromMaybe [] <$> finalScriptWitness m
+    let scriptSig = fromMaybe B.empty (finalScriptSig m)
+    return (TxIn input.outpoint scriptSig input.sequence, stack)
+  let stacks = snd <$> finals
+      witness = if all null stacks then [] else stacks
+  return $ Tx psbt.unsignedTx.version (fst <$> finals) psbt.unsignedTx.outputs witness psbt.unsignedTx.locktime
+
+{- The inputs and outputs of version 2 -}
+
+-- | The PSBT with an input added at the end, as the constructor of BIP 370
+-- adds one: the output it spends and its sequence from the input given,
+-- and the fields of the map given, such as the lock time it requires. A
+-- PSBT of version 0 takes none, nor one whose inputs are not modifiable.
+-- A lock time the input requires must fit the other inputs, and must not
+-- change the lock time of the transaction once an input is signed. Added
+-- at the end, the input leaves every SIGHASH_SINGLE signature paired with
+-- its output. The map is checked against the spec as a map read from
+-- bytes is: a field out of shape, or a previous transaction that is not
+-- the one the input spends, is refused.
+addInput :: TxIn -> PsbtMap -> Psbt -> Either String Psbt
+addInput input m psbt = do
+  flags <- modifiableOf psbt
+  unless flags.inputsModifiable $ Left "The inputs of the PSBT may not be modified"
+  when (any ((== input.outpoint) . (.outpoint)) psbt.unsignedTx.inputs) $
+    Left "An input of the PSBT spends that output already"
+  let added = withInputFields input m
+      inputs = psbt.inputs <> [added]
+      globals = withCounts (length inputs) (length psbt.outputs) psbt.globals
+      place = "input " <> show (length psbt.inputs)
+  -- The same checks as when a PSBT is read, so that the bytes written are
+  -- bytes 'decodePsbt' reads
+  checkMap place Version2 inputFields added
+  first ((capital place <> ": ") <>) (checkPreviousTx input added)
+  tx <- transactionOf globals inputs psbt.outputs
+  when (any hasSignatures psbt.inputs && tx.locktime /= psbt.unsignedTx.locktime) $
+    Left "An input is signed already: the lock time may not change"
+  return $ Psbt Version2 tx globals inputs psbt.outputs
+
+-- | The PSBT with an output added at the end, as the constructor of BIP
+-- 370 adds one: its amount and script from the output given, and the
+-- fields of the map given. A PSBT of version 0 takes none, nor one whose
+-- outputs are not modifiable.
+addOutput :: TxOut -> PsbtMap -> Psbt -> Either String Psbt
+addOutput output m psbt = do
+  flags <- modifiableOf psbt
+  unless flags.outputsModifiable $ Left "The outputs of the PSBT may not be modified"
+  let added = withOutputFields output m
+      outputs = psbt.outputs <> [added]
+      globals = withCounts (length psbt.inputs) (length outputs) psbt.globals
+  checkMap ("output " <> show (length psbt.outputs)) Version2 outputFields added
+  tx <- transactionOf globals psbt.inputs outputs
+  return $ Psbt Version2 tx globals psbt.inputs outputs
+
+-- | The flags of a PSBT of version 2, none set when it has no field of
+-- them. A PSBT of version 0 takes no input or output.
+modifiableOf :: Psbt -> Either String Modifiable
+modifiableOf psbt = do
+  unless (psbt.version == Version2) $ Left "A PSBT of version 0 takes no input or output: its transaction is fixed"
+  fromMaybe noFlags <$> txModifiable psbt.globals
+
+-- | Whether an input has a signature: one that is not final, a Taproot
+-- one, or its final script or witness
+hasSignatures :: PsbtMap -> Bool
+hasSignatures m = hasPartialSignatures m || isFinal m || any ((`elem` [tapKeySigType, tapScriptSigType]) . (.keyType)) (Map.keys m)
+
+-- | The PSBT with the sequence of the input at the index set, as an
+-- updater of BIP 370 may set one. The sequences of a PSBT of version 0
+-- are in its unsigned transaction, which is fixed. An input that is
+-- signed keeps its sequence, since every signature commits to it.
+setInputSequence :: Int -> Word32 -> Psbt -> Either String Psbt
+setInputSequence i sequence' psbt = do
+  unless (psbt.version == Version2) $ Left "The sequences of a PSBT of version 0 are in its unsigned transaction, which is fixed"
+  unless (i >= 0 && i < length psbt.inputs) $ Left ("The PSBT has no input " <> show i)
+  when (hasSignatures (psbt.inputs !! i)) $ Left ("Input " <> show i <> " is signed already: its sequence may not change")
+  let inputs = [if j == i then insertPlainField sequenceType (word32le sequence') m else m | (j, m) <- zip [0 ..] psbt.inputs]
+  tx <- transactionOf psbt.globals inputs psbt.outputs
+  return $ Psbt Version2 tx psbt.globals inputs psbt.outputs
+
+-- | The global map with the fields of version 2 that describe the
+-- transaction: its version, its lock time as the fallback, and the number
+-- of its inputs and outputs
+withTxFields :: Tx -> PsbtMap -> PsbtMap
+withTxFields tx =
+  insertPlainField txVersionType (word32le tx.version)
+    . insertPlainField fallbackLockTimeType (word32le tx.locktime)
+    . withCounts (length tx.inputs) (length tx.outputs)
+
+withCounts :: Int -> Int -> PsbtMap -> PsbtMap
+withCounts inputCount outputCount =
+  insertPlainField inputCountType (compactSize (fromIntegral inputCount))
+    . insertPlainField outputCountType (compactSize (fromIntegral outputCount))
+
+-- | The map of an input with the fields of version 2 that describe it: the
+-- id of the transaction it spends from, the index of the output, and its
+-- sequence
+withInputFields :: TxIn -> PsbtMap -> PsbtMap
+withInputFields input =
+  insertPlainField prevTxidType (S.encode input.outpoint.hash)
+    . insertPlainField outputIndexType (word32le input.outpoint.index)
+    . insertPlainField sequenceType (word32le input.sequence)
+
+-- | The map of an output with the fields of version 2 that describe it:
+-- its amount and its script
+withOutputFields :: TxOut -> PsbtMap -> PsbtMap
+withOutputFields output =
+  insertPlainField amountType (word64le output.value)
+    . insertPlainField outScriptType output.script
+
+{- The types of the spec -}
+
+unsignedTxType, xpubType, txVersionType, fallbackLockTimeType, inputCountType, outputCountType, txModifiableType, versionType :: Word8
+unsignedTxType = 0x00
+xpubType = 0x01
+txVersionType = 0x02
+fallbackLockTimeType = 0x03
+inputCountType = 0x04
+outputCountType = 0x05
+txModifiableType = 0x06
+versionType = 0xfb
+
+nonWitnessUtxoType, witnessUtxoType, partialSigType, sigHashTypeType, inRedeemScriptType, inWitnessScriptType, inDerivationType, finalScriptSigType, finalScriptWitnessType, tapKeySigType, tapScriptSigType, tapLeafScriptType, inTapDerivationType, inTapInternalKeyType, tapMerkleRootType :: Word8
+nonWitnessUtxoType = 0x00
+witnessUtxoType = 0x01
+partialSigType = 0x02
+sigHashTypeType = 0x03
+inRedeemScriptType = 0x04
+inWitnessScriptType = 0x05
+inDerivationType = 0x06
+finalScriptSigType = 0x07
+finalScriptWitnessType = 0x08
+tapKeySigType = 0x13
+tapScriptSigType = 0x14
+tapLeafScriptType = 0x15
+inTapDerivationType = 0x16
+inTapInternalKeyType = 0x17
+tapMerkleRootType = 0x18
+
+-- The preimages of BIP 174, and the MuSig2 fields of BIP 373
+ripemd160Type, sha256Type, hash160Type, hash256Type, inMusigParticipantsType, musigNonceType, musigPartialSigType :: Word8
+ripemd160Type = 0x0a
+sha256Type = 0x0b
+hash160Type = 0x0c
+hash256Type = 0x0d
+inMusigParticipantsType = 0x1a
+musigNonceType = 0x1b
+musigPartialSigType = 0x1c
+
+prevTxidType, outputIndexType, sequenceType, requiredTimeType, requiredHeightType :: Word8
+prevTxidType = 0x0e
+outputIndexType = 0x0f
+sequenceType = 0x10
+requiredTimeType = 0x11
+requiredHeightType = 0x12
+
+outRedeemScriptType, outWitnessScriptType, outDerivationType, amountType, outScriptType, outTapInternalKeyType, outTapTreeType, outTapDerivationType :: Word8
+outRedeemScriptType = 0x00
+outWitnessScriptType = 0x01
+outDerivationType = 0x02
+amountType = 0x03
+outScriptType = 0x04
+outTapInternalKeyType = 0x05
+outTapTreeType = 0x06
+outTapDerivationType = 0x07
+
+-- The MuSig2 field of an output, of BIP 373
+outMusigParticipantsType :: Word8
+outMusigParticipantsType = 0x08
+
+-- | The types of the fields of version 2, which version 0 excludes, by
+-- map
+globalV2Types, inputV2Types, outputV2Types :: [Word8]
+globalV2Types = [txVersionType, fallbackLockTimeType, inputCountType, outputCountType, txModifiableType]
+inputV2Types = [prevTxidType, outputIndexType, sequenceType, requiredTimeType, requiredHeightType]
+outputV2Types = [amountType, outScriptType]
+
+-- | The lock times from this value are times, below it heights
+lockTimeThreshold :: Word32
+lockTimeThreshold = 500000000
+
+proprietaryType :: Word8
+proprietaryType = 0xfc
+
+-- | The key of the unsigned transaction in the global map
+unsignedTxKey :: Key
+unsignedTxKey = Key unsignedTxType B.empty
+
+{- Bytes -}
+
+-- | The five bytes every PSBT starts with: "psbt" and 0xff
+psbtMagic :: ByteString
+psbtMagic = B.pack [0x70, 0x73, 0x62, 0x74, 0xff]
+
+-- | Whether the bytes are those of a PSBT, by their first five
+isPsbt :: ByteString -> Bool
+isPsbt = B.isPrefixOf psbtMagic
+
+-- | The bytes of a PSBT: the magic, the global map, with the unsigned
+-- transaction in version 0, then the maps of the inputs and of the outputs
+encodePsbt :: Psbt -> ByteString
+encodePsbt psbt =
+  B.concat $ psbtMagic : encodeMap globals : (encodeMap <$> psbt.inputs) <> (encodeMap <$> psbt.outputs)
+  where
+    globals = case psbt.version of
+      Version0 -> Map.insert unsignedTxKey (S.encode psbt.unsignedTx) psbt.globals
+      Version2 -> psbt.globals
+
+-- | A map: each key and value after its length, the keys in order, then a
+-- zero byte
+encodeMap :: PsbtMap -> ByteString
+encodeMap m =
+  B.concat [sized (B.cons key.keyType key.keyData) <> sized value | (key, value) <- Map.toAscList m]
+    <> B.singleton 0
+
+-- | Bytes after their length, as a compact size integer
+sized :: ByteString -> ByteString
+sized bytes = compactSize (fromIntegral (B.length bytes)) <> bytes
+
+-- | A compact size integer, in its shortest form
+compactSize :: Word64 -> ByteString
+compactSize = S.encode . VarInt
+
+-- | A 32-bit integer, little-endian
+word32le :: Word32 -> ByteString
+word32le = S.runPut . S.putWord32le
+
+-- | A 64-bit integer, little-endian
+word64le :: Word64 -> ByteString
+word64le = S.runPut . S.putWord64le
+
+-- | The PSBT the bytes hold, or why they hold none: not a PSBT, or one that
+-- breaks the spec.
+--
+-- __What is refused.__ A key out of shape, a key twice in a map, a value
+-- that does not decode, a field of the other version, a field that
+-- version 2 requires and that is missing, bytes after the last map. The
+-- fields checked are those of BIP 174, BIP 370, BIP 371 and BIP 373. And
+-- what Bitcoin Core refuses when it reads a PSBT: a key type that is not a
+-- compact size integer in its shortest form, a public key that is not a
+-- point of the curve, a partial signature that is not in the encoding of
+-- BIP 66 with a defined sighash byte, a previous transaction that is not
+-- the one its input spends, a script tree that is not whole, and an
+-- extended key of depth 0 that has a child number or a parent fingerprint,
+-- which BIP 32 gives to no master key.
+--
+-- __What is read as bytes.__ Where a BIP gives a field as bytes, any bytes
+-- are read, as Bitcoin Core reads them, and the function that gives the
+-- field refuses those that it cannot use: a redeem script, a witness
+-- script or a leaf script that is no list of opcodes ('inputRedeemScript',
+-- 'tapLeafScripts', 'outputTapTree'), an x-only key that is no point of
+-- the curve, and a Taproot signature of 65 bytes whose last byte is no
+-- sighash type of BIP 341 ('tapKeySig'). The signer and the finalizer
+-- leave such an input as it is.
+--
+-- __Where a BIP is stricter than Bitcoin Core,__ the BIP is followed, and
+-- Bitcoin Core reads what is refused here:
+--
+-- * a hash preimage that does not hash to its key. BIP 174: the preimage
+--   "must equal the key when run through" the algorithm of the field;
+-- * a control block of more than 128 nodes, the most BIP 341 allows;
+-- * an extended key with a path that is not as deep as the key. BIP 174:
+--   "The number of 32 bit unsigned integer indexes must match the depth
+--   provided in the extended public key".
+--
+-- __A PSBT of version 2 without a lock time.__ When some inputs require a
+-- height and others a time, no lock time fits them all, and the PSBT has
+-- no transaction. BIP 370 lists such a PSBT with the note that its lock
+-- time "cannot be computed", and Bitcoin Core reads it and gives no
+-- transaction. A t'Psbt' here always has its unsigned transaction, so
+-- such a PSBT is refused. Nobody can sign it.
+decodePsbt :: ByteString -> Either String Psbt
+decodePsbt = parseAll psbtParser "the last map"
+
+-- | The text of a PSBT, in base64, as the spec gives it for text
+encodePsbtBase64 :: Psbt -> ByteString
+encodePsbtBase64 = extractBase64 . encodeBase64' . encodePsbt
+
+-- | The PSBT of a base64 text, around which spaces and line breaks are
+-- left aside
+decodePsbtBase64 :: ByteString -> Either String Psbt
+decodePsbtBase64 text = do
+  bytes <- first (const "Not the base64 text of a PSBT") $ decodeBase64Untyped (B.filter (`notElem` spaces) text)
+  decodePsbt bytes
+  where
+    spaces = [0x20, 0x09, 0x0a, 0x0d]
+
+{- Reading bytes -}
+
+-- | A reader of bytes, which stops at the first byte out of place with a
+-- sentence saying so
+newtype BytesParser a = BytesParser (ByteString -> Either String (a, ByteString))
+
+instance Functor BytesParser where
+  fmap f (BytesParser p) = BytesParser $ \bytes -> do
+    (a, rest) <- p bytes
+    return (f a, rest)
+
+instance Applicative BytesParser where
+  pure a = BytesParser $ \bytes -> Right (a, bytes)
+  (<*>) = ap
+
+instance Monad BytesParser where
+  BytesParser p >>= f = BytesParser $ \bytes -> do
+    (a, rest) <- p bytes
+    let BytesParser q = f a
+    q rest
+
+refuse :: String -> BytesParser a
+refuse reason = BytesParser $ \_ -> Left reason
+
+-- | Read all the bytes with the parser: nothing may follow what it reads
+parseAll :: BytesParser a -> String -> ByteString -> Either String a
+parseAll (BytesParser p) what bytes = do
+  (a, rest) <- p bytes
+  unless (B.null rest) $ Left ("Bytes follow " <> what)
+  return a
+
+-- | The next bytes, which must be there. What they are part of names
+-- them in the refusal.
+bytesOf :: Int -> String -> BytesParser ByteString
+bytesOf n what = BytesParser $ \bytes ->
+  if B.length bytes < n
+    then Left ("The PSBT ends inside " <> what)
+    else Right (B.splitAt n bytes)
+
+-- | All the bytes left
+restOf :: BytesParser ByteString
+restOf = BytesParser $ \bytes -> Right (bytes, B.empty)
+
+-- | A compact size integer: one byte below 0xfd, or 0xfd, 0xfe or 0xff and
+-- two, four or eight bytes, little-endian, in the shortest form, as
+-- Bitcoin Core reads it
+compactSizeOf :: String -> BytesParser Word64
+compactSizeOf what = do
+  first' <- B.head <$> bytesOf 1 what
+  case first' of
+    0xfd -> longer 2 0xfd
+    0xfe -> longer 4 0x10000
+    0xff -> longer 8 0x100000000
+    _ -> return (fromIntegral first')
+  where
+    longer :: Int -> Word64 -> BytesParser Word64
+    longer n least = do
+      value <- B.foldr (\b acc -> acc `shiftL` 8 .|. fromIntegral b) 0 <$> bytesOf n what
+      when (value < least) $ refuse ("A length in " <> what <> " is not in its shortest form")
+      return value
+
+-- | A length, which must fit in memory
+lengthOf :: String -> BytesParser Int
+lengthOf what = do
+  n <- compactSizeOf what
+  when (n > fromIntegral (maxBound :: Int)) $ refuse ("A length in " <> what <> " is beyond any PSBT")
+  return (fromIntegral n)
+
+-- | Bytes after their length
+sizedBytes :: String -> BytesParser ByteString
+sizedBytes what = lengthOf what >>= (`bytesOf` what)
+
+-- | A map: keys and values up to a zero byte, each key once
+mapOf :: String -> BytesParser PsbtMap
+mapOf what = go Map.empty
+  where
+    go m = do
+      keyLength <- lengthOf what
+      if keyLength == 0
+        then return m
+        else do
+          keyBytes <- bytesOf keyLength what
+          either refuse return (checkKeyType what keyBytes)
+          value <- sizedBytes what
+          let key = Key (B.head keyBytes) (B.tail keyBytes)
+          when (Map.member key m) $
+            refuse (capital what <> " has the key " <> showKey key <> " twice")
+          go (Map.insert key value m)
+
+-- | The type of a key is a compact size integer at the start of the key.
+-- Every type the spec defines is below 0xfd and so is the first byte. A
+-- type from 0xfd on takes three, five or nine bytes: it must be whole, in
+-- its shortest form, and at most 'maxCompactSize', as Bitcoin Core reads
+-- it (@ReadCompactSize@ in serialize.h). Such a key is kept as its first
+-- byte and, as its data, the bytes after it.
+checkKeyType :: String -> ByteString -> Either String ()
+checkKeyType what keyBytes = case B.unpack (B.take 1 keyBytes) of
+  [0xfd] -> longer 2 0xfd
+  [0xfe] -> longer 4 0x10000
+  [0xff] -> longer 8 0x100000000
+  _ -> Right ()
+  where
+    longer :: Int -> Word64 -> Either String ()
+    longer n least = do
+      let bytes = B.take n (B.drop 1 keyBytes)
+      unless (B.length bytes == n) $
+        Left (capital what <> " has a key that ends inside its type")
+      let value = B.foldr (\b acc -> acc `shiftL` 8 .|. fromIntegral b) 0 bytes
+      when (value < least) $
+        Left (capital what <> " has a key whose type is not in its shortest form")
+      when (value > maxCompactSize) $
+        Left (capital what <> " has a key whose type is beyond any type")
+
+-- | The largest compact size integer Bitcoin Core reads: its @MAX_SIZE@
+maxCompactSize :: Word64
+maxCompactSize = 0x02000000
+
+psbtParser :: BytesParser Psbt
+psbtParser = do
+  magic <- bytesOf 5 "the magic bytes"
+  unless (magic == psbtMagic) $ refuse "Not a PSBT: the bytes do not start with the magic bytes of BIP 174"
+  globals <- mapOf "the global map"
+  (_, inputCount, outputCount) <- either refuse return (countsOf globals)
+  inputs <- forM [0 .. inputCount - 1] $ \i -> mapOf ("input " <> show i)
+  outputs <- forM [0 .. outputCount - 1] $ \i -> mapOf ("output " <> show i)
+  either refuse return (psbtOfMaps globals inputs outputs)
+
+-- | The version a global map names, and the number of inputs and of
+-- outputs: those of the unsigned transaction in version 0, those the map
+-- counts in version 2. The map is checked against the spec of the version
+-- first.
+countsOf :: PsbtMap -> Either String (PsbtVersion, Int, Int)
+countsOf globals = do
+  version <- versionOf globals
+  checkMap "the global map" version globalFields globals
+  case version of
+    Version0 -> do
+      tx <- unsignedTxOf globals
+      return (Version0, length tx.inputs, length tx.outputs)
+    Version2 -> do
+      _ <- requiredField "The global map" "transaction version" txVersionType decodeWord32le globals
+      inputCount <- requiredField "The global map" "input count" inputCountType decodeCount globals
+      outputCount <- requiredField "The global map" "output count" outputCountType decodeCount globals
+      return (Version2, inputCount, outputCount)
+
+-- | The version the global map names with PSBT_GLOBAL_VERSION: 0 when it
+-- names none
+versionOf :: PsbtMap -> Either String PsbtVersion
+versionOf globals = case plainField versionType globals of
+  Nothing -> Right Version0
+  Just bytes -> do
+    n <- first ("The global map: the value of the key 0xfb " <>) (decodeWord32le bytes)
+    case n of
+      0 -> Right Version0
+      2 -> Right Version2
+      _ -> Left ("The PSBT is of version " <> show n <> ": only versions 0 and 2 are supported")
+
+-- | The unsigned transaction of the global map of version 0, which must be
+-- there, in the serialization without witness, with no input script. It
+-- is read with 'parseLegacyTx', as Bitcoin Core reads it without allowing
+-- a witness, so that a transaction with no inputs, which the spec allows,
+-- is not taken for the extended format of BIP 144.
+unsignedTxOf :: PsbtMap -> Either String Tx
+unsignedTxOf globals = do
+  bytes <- maybe (Left "The global map has no unsigned transaction") Right (Map.lookup unsignedTxKey globals)
+  tx <- case S.runGetState parseLegacyTx bytes 0 of
+    Right (parsed, rest) | B.null rest -> Right parsed
+    _ -> Left "The unsigned transaction does not decode"
+  unless (null tx.witness && S.encode tx == bytes) $
+    Left "The unsigned transaction is not in the serialization without witness"
+  unless (all (B.null . (.script)) tx.inputs) $
+    Left "The unsigned transaction has an input with a script"
+  return tx
+
+-- | The transaction the fields of version 2 describe: its version from
+-- the global map, the lock time the inputs require or the fallback, an
+-- input per input map from the id of the transaction it spends from, the
+-- index of the output and the sequence, final when the map has none, and
+-- an output per output map from its amount and script
+transactionOf :: PsbtMap -> [PsbtMap] -> [PsbtMap] -> Either String Tx
+transactionOf globals inputs outputs = do
+  version <- requiredField "The global map" "transaction version" txVersionType decodeWord32le globals
+  locktime <- lockTimeOf globals inputs
+  txInputs <- forM (zip [0 :: Int ..] inputs) $ \(i, m) -> do
+    let place = "Input " <> show i
+    hash <- requiredField place "previous transaction id" prevTxidType decodeTxHash m
+    index <- requiredField place "output index" outputIndexType decodeWord32le m
+    sequence' <- fromMaybe 0xffffffff <$> optionalField "The sequence" sequenceType decodeWord32le m
+    return (TxIn (OutPoint hash index) B.empty sequence')
+  txOutputs <- forM (zip [0 :: Int ..] outputs) $ \(i, m) -> do
+    let place = "Output " <> show i
+    value <- requiredField place "amount" amountType decodeWord64le m
+    script <- requiredField place "script" outScriptType Right m
+    return (TxOut value script)
+  return (Tx version txInputs txOutputs [] locktime)
+
+-- | The lock time of a PSBT of version 2, as BIP 370 determines it. An
+-- input may require a lock time as a height, as a time, or either, with
+-- both. When no input requires one, it is the fallback lock time of the
+-- global map, 0 without one. Otherwise it is the greatest of the kind every
+-- input that requires one takes, a height when every one takes a height.
+-- When some inputs take a height only and others a time only, no lock time
+-- fits them.
+lockTimeOf :: PsbtMap -> [PsbtMap] -> Either String Word32
+lockTimeOf globals inputs = do
+  fallback <- fromMaybe 0 <$> fallbackLockTime globals
+  required <- forM inputs $ \m -> (,) <$> requiredTimeLockTime m <*> requiredHeightLockTime m
+  let asking = [r | r@(time, height) <- required, isJust time || isJust height]
+      heights = [height | (_, Just height) <- asking]
+      times = [time | (Just time, _) <- asking]
+  case () of
+    _
+      | null asking -> Right fallback
+      | length heights == length asking -> Right (maximum heights)
+      | length times == length asking -> Right (maximum times)
+      | otherwise -> Left "No lock time fits every input: some require a height, others a time"
+
+-- | A field a map must have, decoded. Its absence, or a value out of shape,
+-- names the map and the field.
+requiredField :: String -> String -> Word8 -> (ByteString -> Either String a) -> PsbtMap -> Either String a
+requiredField what name t decode m = do
+  bytes <- maybe (Left (what <> " has no " <> name)) Right (plainField t m)
+  first ((what <> ": the " <> name <> " ") <>) (decode bytes)
+
+-- | A field a map may have, decoded, named in a refusal
+optionalField :: String -> Word8 -> (ByteString -> Either String a) -> PsbtMap -> Either String (Maybe a)
+optionalField name t decode = traverse (first ((name <> " ") <>) . decode) . plainField t
+
+-- | A value decoded from all the bytes given, or a refusal naming it
+decodeFully :: (S.Serialize a) => String -> ByteString -> Either String a
+decodeFully what bytes = case S.runGetState S.get bytes 0 of
+  Right (a, rest) | B.null rest -> Right a
+  _ -> Left (what <> " does not decode")
+
+-- | A sentence that starts with the words given
+capital :: String -> String
+capital (c : rest) = toUpper c : rest
+capital [] = []
+
+-- | A key as a refusal names it: its type in hexadecimal, and its data.
+-- Only the first 'maxShownKeyData' bytes of the data are written, then
+-- its length, so that whoever writes a PSBT cannot make a refusal as
+-- long as they like.
+showKey :: Key -> String
+showKey key =
+  "0x" <> hexByte key.keyType <> (if B.null key.keyData then "" else " with the data " <> shown)
+  where
+    hexByte b = (if b < 16 then "0" else "") <> showHex b ""
+    hexOf = concatMap hexByte . B.unpack
+    shown
+      | B.length key.keyData <= maxShownKeyData = hexOf key.keyData
+      | otherwise = hexOf (B.take maxShownKeyData key.keyData) <> "… (" <> show (B.length key.keyData) <> " bytes)"
+
+-- | How many bytes of the data of a key a refusal writes: enough for a
+-- compressed public key, which is 33 bytes
+maxShownKeyData :: Int
+maxShownKeyData = 40
+
+{- The shapes of the spec -}
+
+-- | The data of a key of the spec: none, a public key, an extended public
+-- key, an x-only public key, an x-only public key with a leaf hash, a
+-- control block, a hash of some bytes, a compressed public key, or the
+-- compressed keys of a MuSig2 participant and of the aggregate with a leaf
+-- hash or none
+data KeyShape
+  = NoData
+  | PublicKeyData
+  | XpubData
+  | XOnlyKeyData
+  | KeyAndLeafData
+  | ControlBlockData
+  | HashData Int
+  | CompressedKeyData
+  | MusigSignerData
+
+-- | A field the spec defines: the shape of its key, the versions of the
+-- PSBT that may hold it, and a check of its value given the data of the
+-- key
+data Field = Field
+  { shape :: KeyShape,
+    versions :: [PsbtVersion],
+    checkValue :: ByteString -> ByteString -> Either String ()
+  }
+
+-- | The fields the spec defines for a map, by type
+type Fields = Map Word8 Field
+
+-- | A field of both versions whose key carries no data
+plain :: (ByteString -> Either String ()) -> Field
+plain = Field NoData [Version0, Version2] . const
+
+-- | A field of version 2 only whose key carries no data
+plain2 :: (ByteString -> Either String ()) -> Field
+plain2 = Field NoData [Version2] . const
+
+-- | Check every key of a map against the spec: the keys of the fields it
+-- defines must be of the version, must have their shape and their values
+-- must decode, and a proprietary key must have its identifier and subtype.
+-- Other keys are not the spec's to check.
+checkMap :: String -> PsbtVersion -> Fields -> PsbtMap -> Either String ()
+checkMap what version fields m = forM_ (Map.toList m) $ \(key, value) ->
+  first ((capital what <> ": ") <>) $
+    case Map.lookup key.keyType fields of
+      Just field -> do
+        unless (version `elem` field.versions) $
+          Left ("the key " <> showKey key <> " is not of PSBT version " <> show (versionNumber version))
+        checkShape field.shape key
+        first (("the value of the key " <> showKey key <> " ") <>) $ field.checkValue key.keyData value
+      Nothing
+        | key.keyType == proprietaryType -> () <$ proprietaryOf key
+        | otherwise -> return ()
+
+checkShape :: KeyShape -> Key -> Either String ()
+checkShape shape key = case shape of
+  NoData -> unless (B.null key.keyData) $ Left ("the key " <> showKey key <> " carries data")
+  PublicKeyData -> unless (isPublicKeyBytes key.keyData) $ Left ("the key " <> showKey key <> " is not a public key")
+  XpubData -> unless (isXpubBytes key.keyData) $ Left ("the key " <> showKey key <> " is not an extended public key")
+  XOnlyKeyData -> unless (B.length key.keyData == 32) $ Left ("the key " <> showKey key <> " is not an x-only public key")
+  KeyAndLeafData -> unless (B.length key.keyData == 64) $ Left ("the key " <> showKey key <> " is not an x-only public key and a leaf hash")
+  ControlBlockData -> unless (isControlBlockLength (B.length key.keyData)) $ Left ("the key " <> showKey key <> " is not a control block")
+  HashData size -> unless (B.length key.keyData == size) $ Left ("the key " <> showKey key <> " is not a hash of " <> show size <> " bytes")
+  CompressedKeyData -> unless (isCompressedKeyBytes key.keyData) $ Left ("the key " <> showKey key <> " is not a compressed public key")
+  MusigSignerData ->
+    unless (B.length key.keyData `elem` [66, 98] && all isCompressedKeyBytes [B.take 33 key.keyData, B.take 33 (B.drop 33 key.keyData)]) $
+      Left ("the key " <> showKey key <> " is not a participant key and an aggregate key, with a leaf hash or none")
+
+-- | Whether a control block may have the length: 33 bytes plus 32 per
+-- node, with at most 'maxControlBlockNodes' nodes
+isControlBlockLength :: Int -> Bool
+isControlBlockLength len =
+  len >= 33 && (len - 33) `mod` 32 == 0 && (len - 33) `div` 32 <= maxControlBlockNodes
+
+-- | Whether the bytes are a public key, compressed or not: they have the
+-- length and the first byte of one, and are a point of the curve, as
+-- Bitcoin Core requires of the keys of a PSBT (@IsFullyValid@ in psbt.h).
+isPublicKeyBytes :: ByteString -> Bool
+isPublicKeyBytes bytes = shaped && isJust (importPubKey bytes)
+  where
+    shaped = case B.unpack (B.take 1 bytes) of
+      [0x02] -> B.length bytes == 33
+      [0x03] -> B.length bytes == 33
+      [0x04] -> B.length bytes == 65
+      _ -> False
+
+-- | Whether the bytes are a compressed public key: 33 bytes that are a
+-- point of the curve
+isCompressedKeyBytes :: ByteString -> Bool
+isCompressedKeyBytes bytes = B.length bytes == 33 && isPublicKeyBytes bytes
+
+-- | Whether the bytes are an extended public key as BIP 32 serializes
+-- one: 78 bytes that end with a compressed public key. A key of depth 0 is
+-- a master key, which has no parent fingerprint and the child number 0:
+-- Bitcoin Core reads no other key of depth 0 (@CExtPubKey::Decode@).
+isXpubBytes :: ByteString -> Bool
+isXpubBytes bytes = B.length bytes == 78 && isCompressedKeyBytes (B.drop 45 bytes) && (depth /= 0 || B.all (== 0) parentAndChild)
+  where
+    depth = B.index bytes 4
+    parentAndChild = B.take 8 (B.drop 5 bytes)
+
+-- | Whether the bytes are a signature as a script holds one: in the
+-- encoding BIP 66 requires, with its sighash byte last. This is
+-- @IsValidSignatureEncoding@ of Bitcoin Core (script/interpreter.cpp),
+-- line for line. It checks the shape of the bytes, not the range of the
+-- two numbers.
+isSignatureEncoding :: ByteString -> Bool
+isSignatureEncoding sig =
+  -- Minimum and maximum size
+  size >= 9
+    && size <= 73
+    -- A signature is of type 0x30 (compound)
+    && at 0 == 0x30
+    -- The length covers the entire signature, without the sighash byte
+    && fromIntegral (at 1) == size - 3
+    -- The length of the S element is still inside the signature
+    && 5 + lenR < size
+    -- The lengths of the two elements add up to the signature
+    && lenR + lenS + 7 == size
+    -- R is an integer, not empty, not negative, with no needless zero byte
+    && at 2 == 0x02
+    && lenR /= 0
+    && at 4 .&. 0x80 == 0
+    && not (lenR > 1 && at 4 == 0x00 && at 5 .&. 0x80 == 0)
+    -- S is an integer, not empty, not negative, with no needless zero byte
+    && at (lenR + 4) == 0x02
+    && lenS /= 0
+    && at (lenR + 6) .&. 0x80 == 0
+    && not (lenS > 1 && at (lenR + 6) == 0x00 && at (lenR + 7) .&. 0x80 == 0)
+  where
+    size = B.length sig
+    at = B.index sig
+    lenR = fromIntegral (at 3) :: Int
+    lenS = fromIntegral (at (5 + lenR)) :: Int
+
+-- The unsigned transaction is checked apart, by 'unsignedTxOf', and the
+-- version by 'versionOf'
+globalFields :: Fields
+globalFields =
+  Map.fromList
+    [ (unsignedTxType, Field NoData [Version0] (const anyValue)),
+      (xpubType, Field XpubData [Version0, Version2] xpubValue),
+      (txVersionType, plain2 word32Value),
+      (fallbackLockTimeType, plain2 word32Value),
+      (inputCountType, plain2 countValue),
+      (outputCountType, plain2 countValue),
+      (txModifiableType, plain2 flagsValue),
+      (versionType, plain word32Value)
+    ]
+  where
+    -- The path of an extended key has one index per level of its depth,
+    -- the fifth byte of the key
+    xpubValue keyData value = do
+      derivation <- decodeDerivation value
+      unless (length (pathToList derivation.path) == fromIntegral (B.index keyData 4)) $
+        Left "has a path that is not as deep as the key"
+    countValue value = () <$ decodeCount value
+    flagsValue value = unless (B.length value == 1) $ Left "is not a byte of flags"
+
+inputFields :: Fields
+inputFields =
+  Map.fromList
+    [ (nonWitnessUtxoType, plain txValue),
+      (witnessUtxoType, plain txOutValue),
+      (partialSigType, Field PublicKeyData [Version0, Version2] (const partialSigValue)),
+      (sigHashTypeType, plain word32Value),
+      -- BIP 174 gives the two scripts as bytes, and Bitcoin Core reads
+      -- any. 'inputRedeemScript' and 'inputWitnessScript' refuse bytes that
+      -- are no list of opcodes.
+      (inRedeemScriptType, plain anyValue),
+      (inWitnessScriptType, plain anyValue),
+      (inDerivationType, Field PublicKeyData [Version0, Version2] (const derivationValue)),
+      (finalScriptSigType, plain anyValue),
+      (finalScriptWitnessType, plain witnessValue),
+      (ripemd160Type, preimageOf 20 (S.encode . ripemd160)),
+      (sha256Type, preimageOf 32 (S.encode . sha256)),
+      (hash160Type, preimageOf 20 (S.encode . addressHash)),
+      (hash256Type, preimageOf 32 (S.encode . doubleSHA256)),
+      (tapKeySigType, plain tapSigValue),
+      (tapScriptSigType, Field KeyAndLeafData [Version0, Version2] (const tapSigValue)),
+      (tapLeafScriptType, Field ControlBlockData [Version0, Version2] (const leafScriptValue)),
+      (inTapDerivationType, Field XOnlyKeyData [Version0, Version2] (const tapDerivationValue)),
+      (inTapInternalKeyType, plain xOnlyKeyValue),
+      (tapMerkleRootType, plain hashValue),
+      (inMusigParticipantsType, Field CompressedKeyData [Version0, Version2] (const compressedKeysValue)),
+      (musigNonceType, Field MusigSignerData [Version0, Version2] (const (sizedValue 66 "is not a public nonce of 66 bytes"))),
+      (musigPartialSigType, Field MusigSignerData [Version0, Version2] (const (sizedValue 32 "is not a partial signature of 32 bytes"))),
+      (prevTxidType, plain2 txHashValue),
+      (outputIndexType, plain2 word32Value),
+      (sequenceType, plain2 word32Value),
+      (requiredTimeType, plain2 timeLockValue),
+      (requiredHeightType, plain2 heightLockValue)
+    ]
+  where
+    -- BIP 174: the preimage "must equal the key when run through" the
+    -- algorithm of the field. Bitcoin Core checks the size of the key only.
+    preimageOf size hash = Field (HashData size) [Version0, Version2] $ \keyData value ->
+      unless (hash value == keyData) $ Left "is not the preimage of the hash in its key"
+    sizedValue size refusal value = unless (B.length value == size) $ Left refusal
+    txValue value = () <$ (decodeTx value :: Either String Tx)
+    -- Bitcoin Core checks a partial signature with the flags DERSIG and
+    -- STRICTENC when it reads a PSBT: the encoding of BIP 66, and a sighash
+    -- byte that is ALL, NONE or SINGLE, with ANYONECANPAY or not. The fork
+    -- id flag is let through here, since the decoder knows no network; the
+    -- signer and the finalizer check it.
+    partialSigValue value =
+      unless (isSignatureEncoding value && not (isSigHashUnknown (fromIntegral (B.last value)))) $
+        Left "is not a signature in the encoding of BIP 66 with a defined sighash byte"
+    txOutValue value = () <$ (decodeTxOut value :: Either String TxOut)
+    witnessValue value = () <$ decodeWitness value
+    txHashValue value = () <$ decodeTxHash value
+    timeLockValue value = do
+      time <- decodeWord32le value
+      unless (time >= lockTimeThreshold) $ Left ("is a time lock below " <> show lockTimeThreshold)
+    heightLockValue value = do
+      height <- decodeWord32le value
+      unless (height > 0 && height < lockTimeThreshold) $ Left ("is not a height between 1 and " <> show (lockTimeThreshold - 1))
+
+outputFields :: Fields
+outputFields =
+  Map.fromList
+    [ (outRedeemScriptType, plain anyValue),
+      (outWitnessScriptType, plain anyValue),
+      (outDerivationType, Field PublicKeyData [Version0, Version2] (const derivationValue)),
+      (amountType, plain2 amountValue),
+      (outScriptType, plain2 anyValue),
+      (outTapInternalKeyType, plain xOnlyKeyValue),
+      (outTapTreeType, plain tapTreeValue),
+      (outTapDerivationType, Field XOnlyKeyData [Version0, Version2] (const tapDerivationValue)),
+      (outMusigParticipantsType, Field CompressedKeyData [Version0, Version2] (const compressedKeysValue))
+    ]
+  where
+    amountValue value = () <$ decodeWord64le value
+
+-- | A Taproot signature as BIP 371 gives it and as Bitcoin Core reads it:
+-- 64 or 65 bytes. The last byte of 65 is not looked at: 'tapKeySig' and
+-- 'tapScriptSigs' refuse one that is no sighash type of BIP 341, and
+-- 'finalizePsbt' makes no witness of it.
+tapSigValue :: ByteString -> Either String ()
+tapSigValue value =
+  unless (B.length value `elem` [64, 65]) $
+    () <$ first ("is not a Taproot signature: " <>) (decodeTaprootSig value)
+
+-- | The compressed public keys of the participants of a MuSig2 aggregate
+-- key (BIP 373), one after the other, each a point of the curve
+compressedKeysValue :: ByteString -> Either String ()
+compressedKeysValue value =
+  unless (all isCompressedKeyBytes (chunksOf 33 value)) $ Left "is not a list of compressed public keys"
+
+leafScriptValue :: ByteString -> Either String ()
+leafScriptValue value = when (B.null value) $ Left "has no leaf version"
+
+tapDerivationValue :: ByteString -> Either String ()
+tapDerivationValue value = () <$ decodeTapDerivation value
+
+xOnlyKeyValue :: ByteString -> Either String ()
+xOnlyKeyValue value = unless (B.length value == 32) $ Left "is not an x-only public key"
+
+hashValue :: ByteString -> Either String ()
+hashValue value = unless (B.length value == 32) $ Left "is not a 32-byte hash"
+
+-- | A script tree as Bitcoin Core accepts one when it reads a PSBT: not
+-- empty, no leaf deeper than 128, every leaf version even, and the leaves
+-- those of one whole tree in depth-first order
+--
+-- The script of a leaf is read as bytes, as BIP 371 gives it: only
+-- 'outputTapTree' asks that it is a list of opcodes.
+tapTreeValue :: ByteString -> Either String ()
+tapTreeValue value = do
+  leaves <- parseTapTree (const (Right (Script []))) value
+  when (null leaves) $ Left "is an empty script tree"
+  when (any ((> maxControlBlockNodes) . fromIntegral . (.depth)) leaves) $
+    Left ("has a leaf deeper than " <> show maxControlBlockNodes)
+  when (any (odd . (.version)) leaves) $ Left "has a leaf with an odd leaf version"
+  when (isNothing (tapTreeFromLeaves leaves)) $ Left "is not a whole script tree"
+
+word32Value :: ByteString -> Either String ()
+word32Value value = () <$ decodeWord32le value
+
+anyValue :: ByteString -> Either String ()
+anyValue _ = Right ()
+
+derivationValue :: ByteString -> Either String ()
+derivationValue value = () <$ decodeDerivation value
+
+decodeTx :: ByteString -> Either String Tx
+decodeTx = decodeFully "is not a transaction: it"
+
+decodeTxOut :: ByteString -> Either String TxOut
+decodeTxOut = decodeFully "is not an output: it"
+
+decodeScript :: ByteString -> Either String Script
+decodeScript = decodeFully "is not a script: it"
+
+decodeWord32le :: ByteString -> Either String Word32
+decodeWord32le bytes
+  | B.length bytes == 4 = Right $ B.foldr (\b acc -> acc `shiftL` 8 .|. fromIntegral b) 0 bytes
+  | otherwise = Left "is not a 32-bit integer"
+
+decodeWord64le :: ByteString -> Either String Word64
+decodeWord64le bytes
+  | B.length bytes == 8 = Right $ B.foldr (\b acc -> acc `shiftL` 8 .|. fromIntegral b) 0 bytes
+  | otherwise = Left "is not a 64-bit integer"
+
+decodeTxHash :: ByteString -> Either String TxHash
+decodeTxHash = decodeFully "is not a transaction id: it"
+
+-- | A count, as a compact size integer in its shortest form
+decodeCount :: ByteString -> Either String Int
+decodeCount bytes = do
+  n <- first (const "is not a count") (parseAll (compactSizeOf "a count") "a count" bytes)
+  when (n > fromIntegral (maxBound :: Int)) $ Left "is a count beyond any PSBT"
+  return (fromIntegral n)
+
+-- | A witness stack: the number of items, then each item after its length
+decodeWitness :: ByteString -> Either String WitnessStack
+decodeWitness = parseAll stack "the final witness"
+  where
+    stack = do
+      count <- lengthOf "the final witness"
+      replicateM count (sizedBytes "the final witness")
+
+encodeWitness :: WitnessStack -> ByteString
+encodeWitness stack = compactSize (fromIntegral (length stack)) <> B.concat (sized <$> stack)
+
+{- Derivations -}
+
+-- | How a key derives: the fingerprint of the key the path starts from,
+-- the master key's as the spec wants it, and the path from it. A key
+-- whose origin is unknown is named by its own fingerprint and an empty
+-- path, or by the fingerprint of an ancestor and the path from it.
+data Derivation = Derivation
+  { fingerprint :: !Fingerprint,
+    path :: !DerivPath
+  }
+  deriving (Eq, Show, Read, Generic)
+  deriving anyclass (NFData)
+
+encodeDerivation :: Derivation -> ByteString
+encodeDerivation derivation =
+  S.encode derivation.fingerprint <> B.concat (word32le <$> pathToList derivation.path)
+
+-- | A derivation: four bytes of fingerprint, then four per index of the
+-- path, little-endian
+decodeDerivation :: ByteString -> Either String Derivation
+decodeDerivation bytes = do
+  unless (B.length bytes >= 4 && (B.length bytes - 4) `mod` 4 == 0) $
+    Left "is not a fingerprint and a path"
+  let (fingerprintBytes, pathBytes) = B.splitAt 4 bytes
+  fingerprint <- decodeFully "is not a fingerprint: it" fingerprintBytes
+  indices <- mapM decodeWord32le (chunksOf 4 pathBytes)
+  return $ Derivation fingerprint (listToPath indices)
+
+chunksOf :: Int -> ByteString -> [ByteString]
+chunksOf n bytes
+  | B.null bytes = []
+  | otherwise = let (chunk, rest) = B.splitAt n bytes in chunk : chunksOf n rest
+
+-- | The records of the type whose keys are public keys, in the order of
+-- the map, with their values decoded
+publicKeyRecords :: Word8 -> (ByteString -> Either String a) -> PsbtMap -> Either String [(PublicKey, a)]
+publicKeyRecords t decodeValue m =
+  forM [(key, value) | (key, value) <- Map.toAscList m, key.keyType == t] $ \(key, value) -> do
+    public <- first (const ("The key " <> showKey key <> " is not a public key")) (decodeSerial key.keyData)
+    decoded <- first (("The value of the key " <> showKey key <> " ") <>) (decodeValue value)
+    return (public, decoded)
+
+derivationsOf :: Word8 -> PsbtMap -> Either String [(PublicKey, Derivation)]
+derivationsOf t = publicKeyRecords t decodeDerivation
+
+insertDerivation :: Word8 -> PublicKey -> Derivation -> PsbtMap -> PsbtMap
+insertDerivation t public derivation = Map.insert (Key t (encodeSerial public)) (encodeDerivation derivation)
+
+-- | The derivations of the keys of an input: PSBT_IN_BIP32_DERIVATION
+inputDerivations :: PsbtMap -> Either String [(PublicKey, Derivation)]
+inputDerivations = derivationsOf inDerivationType
+
+insertInputDerivation :: PublicKey -> Derivation -> PsbtMap -> PsbtMap
+insertInputDerivation = insertDerivation inDerivationType
+
+-- | The derivations of the keys of an output: PSBT_OUT_BIP32_DERIVATION.
+-- A record is a claim of whoever wrote the PSBT. To treat an output as
+-- change, derive the key and compare it with the script of the output.
+outputDerivations :: PsbtMap -> Either String [(PublicKey, Derivation)]
+outputDerivations = derivationsOf outDerivationType
+
+insertOutputDerivation :: PublicKey -> Derivation -> PsbtMap -> PsbtMap
+insertOutputDerivation = insertDerivation outDerivationType
+
+-- | The extended public keys of the global map, with their derivations:
+-- PSBT_GLOBAL_XPUB. Those of another network, by their version bytes, are
+-- left aside.
+xpubRecords :: Network -> PsbtMap -> Either String [(XPubKey, Derivation)]
+xpubRecords net m =
+  fmap catMaybes . forM [(key, value) | (key, value) <- Map.toAscList m, key.keyType == xpubType] $ \(key, value) -> do
+    derivation <- first (("The value of the key " <> showKey key <> " ") <>) (decodeDerivation value)
+    return $ (\xpub -> (xpub, derivation)) <$> eitherToMaybe (unmarshal net key.keyData)
+
+insertXpubRecord :: Network -> XPubKey -> Derivation -> PsbtMap -> PsbtMap
+insertXpubRecord net xpub derivation = Map.insert (Key xpubType (marshal net xpub)) (encodeDerivation derivation)
+
+{- The fields of an input and of an output -}
+
+-- | The field of a type whose key carries no data, if the map has it
+plainField :: Word8 -> PsbtMap -> Maybe ByteString
+plainField t = Map.lookup (Key t B.empty)
+
+insertPlainField :: Word8 -> ByteString -> PsbtMap -> PsbtMap
+insertPlainField t = Map.insert (Key t B.empty)
+
+deletePlainField :: Word8 -> PsbtMap -> PsbtMap
+deletePlainField t = Map.delete (Key t B.empty)
+
+-- | The whole transaction the input spends from: PSBT_IN_NON_WITNESS_UTXO
+nonWitnessUtxo :: PsbtMap -> Either String (Maybe Tx)
+nonWitnessUtxo = traverse (first ("The previous transaction " <>) . decodeTx) . plainField nonWitnessUtxoType
+
+insertNonWitnessUtxo :: Tx -> PsbtMap -> PsbtMap
+insertNonWitnessUtxo = insertPlainField nonWitnessUtxoType . S.encode
+
+-- | The output the input spends, alone: PSBT_IN_WITNESS_UTXO
+witnessUtxo :: PsbtMap -> Either String (Maybe TxOut)
+witnessUtxo = traverse (first ("The witness output " <>) . decodeTxOut) . plainField witnessUtxoType
+
+insertWitnessUtxo :: TxOut -> PsbtMap -> PsbtMap
+insertWitnessUtxo = insertPlainField witnessUtxoType . S.encode
+
+-- | The signatures of the input that are not final, by the public key each
+-- is of, in the order of the map: PSBT_IN_PARTIAL_SIG. A signature is as
+-- it goes in a script, with its sighash byte last.
+partialSignatures :: PsbtMap -> Either String [(PublicKey, ByteString)]
+partialSignatures = publicKeyRecords partialSigType Right
+
+-- | Whether the input carries a signature that is not final
+hasPartialSignatures :: PsbtMap -> Bool
+hasPartialSignatures = any ((== partialSigType) . (.keyType)) . Map.keys
+
+insertPartialSignature :: PublicKey -> ByteString -> PsbtMap -> PsbtMap
+insertPartialSignature public = Map.insert (Key partialSigType (encodeSerial public))
+
+-- | The map without its signatures that are not final, as a finalizer
+-- leaves it
+deletePartialSignatures :: PsbtMap -> PsbtMap
+deletePartialSignatures = Map.filterWithKey (\key _ -> key.keyType /= partialSigType)
+
+-- | The sighash the input is to be signed with: PSBT_IN_SIGHASH_TYPE
+sigHashType :: PsbtMap -> Either String (Maybe SigHash)
+sigHashType = traverse (fmap fromIntegral . first ("The sighash type " <>) . decodeWord32le) . plainField sigHashTypeType
+
+insertSigHashType :: SigHash -> PsbtMap -> PsbtMap
+insertSigHashType = insertPlainField sigHashTypeType . word32le . fromIntegral
+
+-- | The map without the sighash the input was to be signed with, as a
+-- finalizer leaves it
+deleteSigHashType :: PsbtMap -> PsbtMap
+deleteSigHashType = deletePlainField sigHashTypeType
+
+-- | The script of a type whose key carries no data, if the map has it
+scriptField :: Word8 -> String -> PsbtMap -> Either String (Maybe Script)
+scriptField t what = traverse (first ((what <> " ") <>) . decodeScript) . plainField t
+
+insertScriptField :: Word8 -> Script -> PsbtMap -> PsbtMap
+insertScriptField t = insertPlainField t . S.encode
+
+-- | The redeem script of the P2SH coin an input spends:
+-- PSBT_IN_REDEEM_SCRIPT
+inputRedeemScript :: PsbtMap -> Either String (Maybe Script)
+inputRedeemScript = scriptField inRedeemScriptType "The redeem script"
+
+insertInputRedeemScript :: Script -> PsbtMap -> PsbtMap
+insertInputRedeemScript = insertScriptField inRedeemScriptType
+
+-- | The witness script of the P2WSH coin an input spends:
+-- PSBT_IN_WITNESS_SCRIPT
+inputWitnessScript :: PsbtMap -> Either String (Maybe Script)
+inputWitnessScript = scriptField inWitnessScriptType "The witness script"
+
+insertInputWitnessScript :: Script -> PsbtMap -> PsbtMap
+insertInputWitnessScript = insertScriptField inWitnessScriptType
+
+-- | The input script of a signed input: PSBT_IN_FINAL_SCRIPTSIG
+finalScriptSig :: PsbtMap -> Maybe ByteString
+finalScriptSig = plainField finalScriptSigType
+
+insertFinalScriptSig :: ByteString -> PsbtMap -> PsbtMap
+insertFinalScriptSig = insertPlainField finalScriptSigType
+
+-- | The witness of a signed input: PSBT_IN_FINAL_SCRIPTWITNESS
+finalScriptWitness :: PsbtMap -> Either String (Maybe WitnessStack)
+finalScriptWitness = traverse decodeWitness . plainField finalScriptWitnessType
+
+insertFinalScriptWitness :: WitnessStack -> PsbtMap -> PsbtMap
+insertFinalScriptWitness = insertPlainField finalScriptWitnessType . encodeWitness
+
+-- | The redeem script of a P2SH output: PSBT_OUT_REDEEM_SCRIPT
+outputRedeemScript :: PsbtMap -> Either String (Maybe Script)
+outputRedeemScript = scriptField outRedeemScriptType "The redeem script"
+
+insertOutputRedeemScript :: Script -> PsbtMap -> PsbtMap
+insertOutputRedeemScript = insertScriptField outRedeemScriptType
+
+-- | The witness script of a P2WSH output: PSBT_OUT_WITNESS_SCRIPT
+outputWitnessScript :: PsbtMap -> Either String (Maybe Script)
+outputWitnessScript = scriptField outWitnessScriptType "The witness script"
+
+insertOutputWitnessScript :: Script -> PsbtMap -> PsbtMap
+insertOutputWitnessScript = insertScriptField outWitnessScriptType
+
+{- The Taproot fields of BIP 371 -}
+
+-- | The key path signature of a Taproot input: PSBT_IN_TAP_KEY_SIG
+tapKeySig :: PsbtMap -> Either String (Maybe TaprootSignature)
+tapKeySig = optionalField "The key path signature" tapKeySigType decodeTaprootSig
+
+insertTapKeySig :: TaprootSignature -> PsbtMap -> PsbtMap
+insertTapKeySig = insertPlainField tapKeySigType . encodeTaprootSig
+
+-- | The script path signatures of a Taproot input, each by the x-only key
+-- and the leaf hash it is for: PSBT_IN_TAP_SCRIPT_SIG
+tapScriptSigs :: PsbtMap -> Either String [((PubKey, Digest SHA256), TaprootSignature)]
+tapScriptSigs m =
+  forM [(key, value) | (key, value) <- Map.toAscList m, key.keyType == tapScriptSigType] $ \(key, value) -> do
+    let (keyBytes, leafBytes) = B.splitAt 32 key.keyData
+    leafKey <- maybe (Left ("The key " <> showKey key <> " is not an x-only public key and a leaf hash")) Right $ importXOnlyPubKey keyBytes
+    leaf <- maybe (Left ("The key " <> showKey key <> " is not an x-only public key and a leaf hash")) Right $ digestOf leafBytes
+    signature <- first (("The value of the key " <> showKey key <> " ") <>) (decodeTaprootSig value)
+    return ((leafKey, leaf), signature)
+
+insertTapScriptSig :: PubKey -> Digest SHA256 -> TaprootSignature -> PsbtMap -> PsbtMap
+insertTapScriptSig leafKey leaf signature =
+  Map.insert (Key tapScriptSigType (exportXOnlyPubKey leafKey <> BA.convert leaf)) (encodeTaprootSig signature)
+
+-- | A leaf script a Taproot input may be spent with, and the control
+-- block that commits it to the output key: PSBT_IN_TAP_LEAF_SCRIPT
+data TapLeafScript = TapLeafScript
+  { controlBlock :: !ByteString,
+    script :: !Script,
+    leafVersion :: !TapLeafVersion
+  }
+  deriving (Eq, Show, Read, Generic)
+  deriving anyclass (NFData)
+
+-- | The leaf scripts of a Taproot input, with their control blocks:
+-- PSBT_IN_TAP_LEAF_SCRIPT
+tapLeafScripts :: PsbtMap -> Either String [TapLeafScript]
+tapLeafScripts = sequence . tapLeafScriptEntries
+
+-- | Each leaf script of a Taproot input, or why it is refused: a control
+-- block whose internal key is no point of the curve, or a script that is
+-- not a list of opcodes. 'decodePsbt' reads such an entry, as Bitcoin Core
+-- does, and a leaf of an unknown leaf version may hold any bytes. The
+-- signer and the finalizer take the entries one by one, so that one they
+-- cannot use does not hide the others.
+tapLeafScriptEntries :: PsbtMap -> [Either String TapLeafScript]
+tapLeafScriptEntries m =
+  [ do
+      _ <- first (const ("The key " <> showKey key <> " is not a control block")) (decodeControlBlock key.keyData)
+      when (B.null value) $ Left ("The value of the key " <> showKey key <> " has no leaf version")
+      script <- first (("The value of the key " <> showKey key <> " ") <>) (decodeScript (B.init value))
+      return (TapLeafScript key.keyData script (B.last value))
+  | (key, value) <- Map.toAscList m,
+    key.keyType == tapLeafScriptType
+  ]
+
+insertTapLeafScript :: TapLeafScript -> PsbtMap -> PsbtMap
+insertTapLeafScript leaf =
+  Map.insert (Key tapLeafScriptType leaf.controlBlock) (S.encode leaf.script <> B.singleton leaf.leafVersion)
+
+-- | How an x-only key of a Taproot input or output derives, and the
+-- leaves it appears in: the value of PSBT_IN_TAP_BIP32_DERIVATION and
+-- PSBT_OUT_TAP_BIP32_DERIVATION. The internal key has no leaf.
+data TapDerivation = TapDerivation
+  { leafHashes :: ![Digest SHA256],
+    derivation :: !Derivation
+  }
+  deriving (Eq, Show, Generic)
+
+encodeTapDerivation :: TapDerivation -> ByteString
+encodeTapDerivation d =
+  compactSize (fromIntegral (length d.leafHashes)) <> B.concat (BA.convert <$> d.leafHashes) <> encodeDerivation d.derivation
+
+-- | A Taproot derivation: the number of leaf hashes, the hashes, then the
+-- fingerprint and the path
+decodeTapDerivation :: ByteString -> Either String TapDerivation
+decodeTapDerivation = parseAll record "a Taproot derivation"
+  where
+    record = do
+      count <- lengthOf "a Taproot derivation"
+      hashes <- replicateM count (bytesOf 32 "a Taproot derivation")
+      leaves <- maybe (refuse "is not a Taproot derivation") return (mapM digestOf hashes)
+      rest <- restOf
+      derivation <- either refuse return (decodeDerivation rest)
+      return (TapDerivation leaves derivation)
+
+tapDerivationsOf :: Word8 -> PsbtMap -> Either String [(PubKey, TapDerivation)]
+tapDerivationsOf t m =
+  forM [(key, value) | (key, value) <- Map.toAscList m, key.keyType == t] $ \(key, value) -> do
+    public <- maybe (Left ("The key " <> showKey key <> " is not an x-only public key")) Right (importXOnlyPubKey key.keyData)
+    decoded <- first (("The value of the key " <> showKey key <> " ") <>) (decodeTapDerivation value)
+    return (public, decoded)
+
+insertTapDerivation :: Word8 -> PubKey -> TapDerivation -> PsbtMap -> PsbtMap
+insertTapDerivation t public d = Map.insert (Key t (exportXOnlyPubKey public)) (encodeTapDerivation d)
+
+-- | The derivations of the x-only keys of a Taproot input, each with the
+-- leaves it appears in: PSBT_IN_TAP_BIP32_DERIVATION. The key is the
+-- point of even y with that x coordinate.
+inputTapDerivations :: PsbtMap -> Either String [(PubKey, TapDerivation)]
+inputTapDerivations = tapDerivationsOf inTapDerivationType
+
+insertInputTapDerivation :: PubKey -> TapDerivation -> PsbtMap -> PsbtMap
+insertInputTapDerivation = insertTapDerivation inTapDerivationType
+
+-- | The derivations of the x-only keys of a Taproot output:
+-- PSBT_OUT_TAP_BIP32_DERIVATION. A record is a claim of whoever wrote the
+-- PSBT, as for 'outputDerivations'.
+outputTapDerivations :: PsbtMap -> Either String [(PubKey, TapDerivation)]
+outputTapDerivations = tapDerivationsOf outTapDerivationType
+
+insertOutputTapDerivation :: PubKey -> TapDerivation -> PsbtMap -> PsbtMap
+insertOutputTapDerivation = insertTapDerivation outTapDerivationType
+
+xOnlyKeyField :: Word8 -> String -> PsbtMap -> Either String (Maybe PubKey)
+xOnlyKeyField t what = optionalField what t (maybe (Left "is not an x-only public key") Right . importXOnlyPubKey)
+
+insertXOnlyKeyField :: Word8 -> PubKey -> PsbtMap -> PsbtMap
+insertXOnlyKeyField t = insertPlainField t . exportXOnlyPubKey
+
+-- | The internal key of the Taproot coin an input spends:
+-- PSBT_IN_TAP_INTERNAL_KEY. The key is the point of even y with that x
+-- coordinate.
+inputTapInternalKey :: PsbtMap -> Either String (Maybe PubKey)
+inputTapInternalKey = xOnlyKeyField inTapInternalKeyType "The internal key"
+
+insertInputTapInternalKey :: PubKey -> PsbtMap -> PsbtMap
+insertInputTapInternalKey = insertXOnlyKeyField inTapInternalKeyType
+
+-- | The root of the script tree of the Taproot coin an input spends:
+-- PSBT_IN_TAP_MERKLE_ROOT
+inputTapMerkleRoot :: PsbtMap -> Either String (Maybe (Digest SHA256))
+inputTapMerkleRoot = optionalField "The Merkle root" tapMerkleRootType (maybe (Left "is not a 32-byte hash") Right . digestOf)
+
+insertInputTapMerkleRoot :: Digest SHA256 -> PsbtMap -> PsbtMap
+insertInputTapMerkleRoot = insertPlainField tapMerkleRootType . BA.convert
+
+-- | The internal key of a Taproot output: PSBT_OUT_TAP_INTERNAL_KEY
+outputTapInternalKey :: PsbtMap -> Either String (Maybe PubKey)
+outputTapInternalKey = xOnlyKeyField outTapInternalKeyType "The internal key"
+
+insertOutputTapInternalKey :: PubKey -> PsbtMap -> PsbtMap
+insertOutputTapInternalKey = insertXOnlyKeyField outTapInternalKeyType
+
+-- | The script tree of a Taproot output, as its leaves depth first:
+-- PSBT_OUT_TAP_TREE. 'tapTreeFromLeaves' builds the tree.
+outputTapTree :: PsbtMap -> Either String (Maybe [TapLeaf])
+outputTapTree = optionalField "The script tree" outTapTreeType decodeTapTree
+
+insertOutputTapTree :: [TapLeaf] -> PsbtMap -> PsbtMap
+insertOutputTapTree leaves = insertPlainField outTapTreeType (B.concat (encodeLeaf <$> leaves))
+  where
+    encodeLeaf :: TapLeaf -> ByteString
+    encodeLeaf leaf = B.pack [leaf.depth, leaf.version] <> sized (S.encode leaf.script)
+
+-- | A script tree: for each leaf, its depth, its leaf version and its
+-- script after its length
+decodeTapTree :: ByteString -> Either String [TapLeaf]
+decodeTapTree = parseTapTree (first ("has a leaf whose script " <>) . decodeScript)
+
+-- | The leaves of a script tree, with the script of each leaf read from
+-- its bytes by the function given
+parseTapTree :: (ByteString -> Either String Script) -> ByteString -> Either String [TapLeaf]
+parseTapTree scriptOf = parseAll leaves "a script tree"
+  where
+    leaves = do
+      rest <- restOf
+      if B.null rest
+        then return []
+        else do
+          BytesParser (\_ -> Right ((), rest)) -- put the bytes back
+          depth <- B.head <$> bytesOf 1 "a script tree"
+          version <- B.head <$> bytesOf 1 "a script tree"
+          scriptBytes <- sizedBytes "a script tree"
+          script <- either refuse return (scriptOf scriptBytes)
+          (TapLeaf depth version script :) <$> leaves
+
+-- | A 32-byte hash as a digest
+digestOf :: ByteString -> Maybe (Digest SHA256)
+digestOf = digestFromByteString
+
+{- The fields of version 2 -}
+
+-- | The flags of PSBT_GLOBAL_TX_MODIFIABLE: whether inputs may be added,
+-- whether outputs may be added, and whether an input is signed with
+-- SIGHASH_SINGLE, which pairs it with the output at its index. The other
+-- bits of the byte are not defined; they are kept as they are.
+data Modifiable = Modifiable
+  { inputsModifiable :: !Bool,
+    outputsModifiable :: !Bool,
+    hasSigHashSingle :: !Bool,
+    undefinedBits :: !Word8
+  }
+  deriving (Eq, Show, Read, Generic)
+  deriving anyclass (NFData)
+
+-- | No flag set
+noFlags :: Modifiable
+noFlags = Modifiable False False False 0
+
+-- | The flags of the global map, if it has the field: PSBT_GLOBAL_TX_MODIFIABLE
+txModifiable :: PsbtMap -> Either String (Maybe Modifiable)
+txModifiable = optionalField "The modifiable flags" txModifiableType decodeFlags
+  where
+    decodeFlags value = case B.unpack value of
+      [byte] -> Right $ Modifiable (testBit byte 0) (testBit byte 1) (testBit byte 2) (byte .&. 0xf8)
+      _ -> Left "are not one byte"
+
+insertTxModifiable :: Modifiable -> PsbtMap -> PsbtMap
+insertTxModifiable flags = insertPlainField txModifiableType (B.singleton byte)
+  where
+    byte = bit 0 flags.inputsModifiable .|. bit 1 flags.outputsModifiable .|. bit 2 flags.hasSigHashSingle .|. (flags.undefinedBits .&. 0xf8)
+    bit :: Int -> Bool -> Word8
+    bit n set = if set then 1 `shiftL` n else 0
+
+-- | The global map without the flags, which a constructor may remove once
+-- nothing is to be added
+deleteTxModifiable :: PsbtMap -> PsbtMap
+deleteTxModifiable = deletePlainField txModifiableType
+
+-- | The lock time of the transaction when no input requires one:
+-- PSBT_GLOBAL_FALLBACK_LOCKTIME
+fallbackLockTime :: PsbtMap -> Either String (Maybe Word32)
+fallbackLockTime = optionalField "The fallback lock time" fallbackLockTimeType decodeWord32le
+
+-- | The least time, as a Unix timestamp, the input requires as the lock
+-- time of the transaction: PSBT_IN_REQUIRED_TIME_LOCKTIME
+requiredTimeLockTime :: PsbtMap -> Either String (Maybe Word32)
+requiredTimeLockTime = optionalField "The required time lock time" requiredTimeType decodeWord32le
+
+insertRequiredTimeLockTime :: Word32 -> PsbtMap -> PsbtMap
+insertRequiredTimeLockTime = insertPlainField requiredTimeType . word32le
+
+-- | The least block height the input requires as the lock time of the
+-- transaction: PSBT_IN_REQUIRED_HEIGHT_LOCKTIME
+requiredHeightLockTime :: PsbtMap -> Either String (Maybe Word32)
+requiredHeightLockTime = optionalField "The required height lock time" requiredHeightType decodeWord32le
+
+insertRequiredHeightLockTime :: Word32 -> PsbtMap -> PsbtMap
+insertRequiredHeightLockTime = insertPlainField requiredHeightType . word32le
+
+{- Proprietary fields -}
+
+-- | A proprietary field, of type 0xFC: the identifier of the software it
+-- belongs to, its subtype under that identifier, and the data after the
+-- subtype, none for most
+data Proprietary = Proprietary
+  { identifier :: !ByteString,
+    subtype :: !Word64,
+    extra :: !ByteString
+  }
+  deriving (Eq, Show, Read, Generic)
+  deriving anyclass (NFData)
+
+-- | The key of a proprietary field: the type 0xFC, the identifier after
+-- its length, the subtype as a compact size integer, and the data
+proprietaryKey :: Proprietary -> Key
+proprietaryKey p =
+  Key proprietaryType (sized p.identifier <> compactSize p.subtype <> p.extra)
+
+-- | The proprietary field a key is, if it is one: nothing for a key of
+-- another type, a refusal for a proprietary key without its identifier
+-- and subtype
+proprietaryOf :: Key -> Either String (Maybe Proprietary)
+proprietaryOf key
+  | key.keyType /= proprietaryType = Right Nothing
+  | otherwise =
+      first (const ("the proprietary key " <> showKey key <> " has no identifier and subtype")) $
+        Just <$> parseAll (Proprietary <$> sizedBytes what <*> compactSizeOf what <*> restOf) what key.keyData
+  where
+    what = "a proprietary key"
+
+-- | The value of the proprietary field of the identifier and subtype,
+-- with no data after the subtype, if the map has it
+lookupProprietary :: ByteString -> Word64 -> PsbtMap -> Maybe ByteString
+lookupProprietary identifier subtype = Map.lookup (proprietaryKey (Proprietary identifier subtype B.empty))
+
+insertProprietary :: ByteString -> Word64 -> ByteString -> PsbtMap -> PsbtMap
+insertProprietary identifier subtype = Map.insert (proprietaryKey (Proprietary identifier subtype B.empty))
+
+{- Signing -}
+
+-- | Where a signer gets its private keys: by a derivation record naming a
+-- public key, or by the hash of a public key when the input has no record
+-- for it. A key that is not held is 'Nothing'. The signer also says which
+-- sighash types it agrees to sign with, and whether it wants the previous
+-- transaction of a SegWit version 0 coin.
+data Signer = Signer
+  { -- | the private key of the public key a derivation record names
+    keyOfRecord :: PublicKey -> Derivation -> Maybe SecKey,
+    -- | the private key whose public key, compressed or not, has the hash
+    keyOfHash :: Hash160 -> Maybe PrivateKey,
+    -- | the sighash types the signer signs with. An input that asks for
+    -- another type is refused, as BIP 174 asks of a signer. The fork id
+    -- flag does not count, since the network decides it.
+    acceptedSigHashes :: [SigHash],
+    -- | whether a SegWit version 0 coin (P2WPKH or P2WSH, nested in P2SH
+    -- or not) is signed only when the input carries its previous
+    -- transaction. A BIP 143 signature commits to the amount of its own
+    -- coin and to no other. With the witness output alone, whoever writes
+    -- the PSBT can lie about the amount of one coin of the signer in each
+    -- of two signing rounds, keep the valid signature of each round, and
+    -- make a transaction that pays the difference as fee
+    -- (CVE-2020-14199). BIP 174 lets a signer "fail to sign a segwit
+    -- input if a non-witness UTXO is not provided" for this reason. A
+    -- Taproot signature commits to the amount of every coin and needs no
+    -- such care.
+    requirePreviousTx :: Bool
+  }
+
+-- | The sighash types a signer accepts unless told otherwise:
+-- 'sigHashDefault', which a Taproot input uses when it asks for none, and
+-- 'sigHashAll'. The other types leave part of the transaction out of the
+-- signature, so a PSBT written by someone else may not ask for them on its
+-- own; a signer that agrees to them lists them, for example
+-- @(keySigner key) {acceptedSigHashes = sigHashNone : defaultSigHashes}@.
+defaultSigHashes :: [SigHash]
+defaultSigHashes = [sigHashDefault, sigHashAll]
+
+-- | Whether the signer accepts the sighash type: it is one of its types,
+-- the fork id flag aside
+acceptsSigHash :: Signer -> SigHash -> Bool
+acceptsSigHash signer sighash =
+  withoutForkId sighash `elem` map withoutForkId signer.acceptedSigHashes
+  where
+    withoutForkId = (.&. complement forkIdBit)
+    forkIdBit = fromIntegral (fromEnum SIGHASH_FORKID)
+
+-- | A signer that holds one private key, for the records of its public
+-- key and for the hash of its public key in either form. It wants the
+-- previous transaction of a SegWit version 0 coin ('requirePreviousTx').
+-- A caller that has checked the amounts of its coins another way, for
+-- example against its own records, turns that off with
+-- @(keySigner key) {requirePreviousTx = False}@.
+keySigner :: SecKey -> Signer
+keySigner secret =
+  Signer
+    { keyOfRecord = \public _ -> do
+        guard (public.point == derivePubKey secret)
+        return secret,
+      keyOfHash = \h -> find ((== h) . addressHash . encodeSerial . derivePublicKey) [PrivateKey secret True, PrivateKey secret False],
+      acceptedSigHashes = defaultSigHashes,
+      requirePreviousTx = True
+    }
+
+-- | A signer that derives from an extended private key. A record names a
+-- key it derives by the fingerprint of the extended key and the path from
+-- it, or, when the origin of the extended key is given, by the
+-- fingerprint of that origin and the path from it, which starts with the
+-- path of the extended key. A path the key cannot follow, such as one
+-- deeper than the 255 levels of BIP 32 or one with a hardened step
+-- below a key that cannot derive it, names no key. It has no key for a
+-- hash, since it cannot know which path to derive. Like 'keySigner', it
+-- wants the previous transaction of a SegWit version 0 coin.
+xPrvSigner :: XPrvKey -> Maybe Derivation -> Signer
+xPrvSigner xprv originM =
+  Signer
+    { keyOfRecord = \public derivation -> do
+        path <- relative derivation
+        secret <- (.key) <$> eitherToMaybe (tryDerivePath path xprv)
+        guard (public.point == derivePubKey secret)
+        return secret,
+      keyOfHash = const Nothing,
+      acceptedSigHashes = defaultSigHashes,
+      requirePreviousTx = True
+    }
+  where
+    own = xPubFP (deriveXPubKey xprv)
+    relative :: Derivation -> Maybe DerivPath
+    relative derivation
+      | derivation.fingerprint == own = Just derivation.path
+      | Just origin <- originM,
+        derivation.fingerprint == origin.fingerprint =
+          listToPath <$> stripPrefix (pathToList origin.path) (pathToList derivation.path)
+      | otherwise = Nothing
+
+-- | Sign every input the signer has keys for, as the signer of the spec
+-- does. An input is signed against the coin it spends: the output of its
+-- previous transaction, whose id must be the one the input spends, or,
+-- without that transaction, its witness output, which only a witness
+-- signature may use, as BIP 174 requires. A witness output beside the
+-- previous transaction is not read, as Bitcoin Core does not read it.
+--
+-- __One input at a time.__ The parties of a transaction fill a PSBT in
+-- turn, so an input that this signer cannot sign is the normal case and
+-- not a fault. BIP 174 names one case in which a signer must fail, the
+-- sighash type, and for the rest says "If a Signer cannot sign a
+-- transaction, it must not add a Partial Signature." So the signer does as
+-- Bitcoin Core does (@SignPSBTInput@): it refuses the whole PSBT for a
+-- sighash type only, and an input that it cannot or may not sign stays as
+-- it is while the other inputs are signed. The cost of that choice is that
+-- the result does not say why an input has no signature: compare the
+-- inputs before and after.
+--
+-- __What refuses the PSBT.__ The sighash type of an input is the one it
+-- asks for. When it asks for none it is SIGHASH_ALL, with the fork id flag
+-- on a network that has one, and SIGHASH_DEFAULT for a Taproot coin. On
+-- any input that has its coin and is not final, whoever it belongs to:
+--
+-- * a type that no node accepts for the kind of coin, or that the signer
+--   does not accept ('acceptedSigHashes'). BIP 174: "If a sighash type is
+--   provided, the signer must check that the sighash is acceptable. If
+--   unacceptable, they must fail";
+-- * a signature that the input already has and that is of another type,
+--   as Bitcoin Core checks it: a partial signature by its last byte, a
+--   Taproot signature by its length and its last byte.
+--
+-- A previous transaction that is not the one its input spends refuses the
+-- PSBT too. 'decodePsbt' does not read such a PSBT.
+--
+-- __What leaves an input as it is.__ An input without its coin, or final
+-- already, and an input for which the signer holds no key. And, although
+-- the signer holds a key:
+--
+-- * a redeem script that does not hash to the coin, or a witness script
+--   that does not hash to the witness program, and either script on a coin
+--   that has none. BIP 174 has a signer check both before it signs.
+--   Bitcoin Core signs a coin that carries a script it does not use;
+-- * a P2SH coin without its redeem script, a P2WSH coin without its
+--   witness script, and a coin, redeem script or witness script that is no
+--   standard template;
+-- * a P2SH coin whose redeem script has more than 'maxRedeemScriptSize'
+--   bytes, which no transaction can spend. Bitcoin Core adds a signature
+--   to it, which serves nothing;
+-- * a legacy coin known from its witness output only: "If a witness UTXO
+--   is provided, no non-witness signature may be created";
+-- * a SegWit version 0 coin known from its witness output only, when the
+--   signer wants the previous transaction ('requirePreviousTx');
+-- * a SegWit version 0 coin of more than 'maxSatoshi', which Bitcoin Core
+--   does not sign;
+-- * a legacy coin asked to sign SIGHASH_SINGLE with no output at its
+--   index, as 'Haskoin.Transaction.Builder.makeSignature' explains, and a
+--   Taproot coin in that case, for which BIP 341 defines no digest.
+--
+-- An uncompressed key gets no signature on a SegWit version 0 coin, which
+-- no node relays and Bitcoin Core does not sign, and the other keys of
+-- that coin are still signed with. A key that has a signature on the input
+-- already is not signed with again: the signature that is there stays, as
+-- in Bitcoin Core.
+--
+-- __The keys.__ They are those that the script that is signed names: the
+-- script of the coin, its redeem script or its witness script. The signer
+-- is asked for the key of a derivation record only when that script names
+-- the key of the record, and for the key of each hash the script names. A
+-- key that the script does not name gets no signature, whatever the
+-- records say.
+--
+-- __Taproot.__ A Taproot coin is signed only when every input of the PSBT
+-- has its coin, since the BIP 341 digest commits to the output that every
+-- input spends. It is signed by its key path when the signer holds the
+-- internal key that the input names and that key gives the coin, or when
+-- it holds the output key of the coin itself. Otherwise it is signed by
+-- each of its leaf scripts that is the check of one key (@\<key\>
+-- OP_CHECKSIG@ of the leaf version 0xc0) that the signer holds. As in
+-- Bitcoin Core (@SignTaproot@):
+--
+-- * an input that has a key path signature, or gets one, gets no leaf
+--   signature;
+-- * a leaf is signed by the leaf version in the value of its entry,
+--   whatever its control block holds, and whether or not the control block
+--   commits the leaf to the coin. Such a signature is for this input and
+--   this leaf alone, so it spends nothing, and 'finalizePsbt' makes a
+--   witness only of a leaf that its control block commits;
+-- * the key of a leaf is found by the record of that key, whichever leaves
+--   the record lists.
+--
+-- In one case the signer does not do as Bitcoin Core: an internal key that
+-- does not give, with the Merkle root of the input, the output key of the
+-- coin. Bitcoin Core signs with it when its wallet holds it, and that
+-- signature verifies for no coin and then stops the owner of the input,
+-- whose finalizer takes the key path signature first. The signer adds
+-- none: BIP 174 has a signer make only valid signatures.
+--
+-- A field that cannot be used gives no key and refuses nothing: an
+-- internal key that is no point of the curve, a Merkle root that is not a
+-- hash, a record that does not decode. On a network without SegWit a
+-- script of the form of a Taproot output is no Taproot coin.
+--
+-- __Cost.__ A PSBT that another party wrote can hold thousands of leaf
+-- scripts and of derivation records on one input, and thousands of leaves
+-- in one record, at no cost to its writer. The signer asks for the key of
+-- each leaf script once, however many entries have that script, and finds
+-- the record of a key by a lookup. So the time it takes grows with the
+-- size of the input, and not with the product of two of those numbers.
+-- The hashes that the digests of the inputs share are computed once for
+-- the PSBT ('taprootTxHashes' for the Taproot inputs, 'txSigHashes' for
+-- the SegWit version 0 inputs), so the time for all the inputs grows with
+-- the size of the PSBT, and not with the number of its signatures times
+-- the size of its transaction. A legacy input is the exception: its
+-- digest hashes a copy of the whole transaction, in Bitcoin Core too.
+signPsbt :: Network -> Signer -> Psbt -> Either String Psbt
+signPsbt net signer psbt = do
+  coins <- spentOutputs psbt
+  let hashes = taprootHashes tx coins
+      sigHashes = txSigHashes tx
+  signed <- forM (zip3 [0 ..] (zip tx.inputs psbt.inputs) coins) $ \(i, (input, m), coinM) ->
+    first (("Input " <> show i <> ": ") <>) $ case coinM of
+      Just (coin, witnessOnly) | not (isFinal m) -> do
+        sighash <- fromMaybe (defaultSigHash net coin) <$> sigHashType m
+        checkSigHash net coin sighash
+        unless (acceptsSigHash signer sighash) $
+          Left (notAcceptedSigHash sighash)
+        unless (signaturesUse sighash m) $
+          Left ("a signature of the input does not use the sighash type " <> show (fromIntegral sighash :: Word32))
+        return . fromMaybe (m, []) $
+          if isTaprootCoin net coin
+            then signTaproot signer hashes i m coin sighash
+            else signEcdsa net signer sigHashes i input m coin witnessOnly sighash
+      _ -> return (m, [])
+  return $ foldr afterSignature (Psbt psbt.version tx psbt.globals (fst <$> signed) psbt.outputs) (concatMap snd signed)
+  where
+    tx = psbt.unsignedTx
+
+-- | An input with a signature of each key that the signer holds among
+-- those the script names, for a coin signed with ECDSA, and the sighash
+-- type used. 'Nothing' when no signature is added: the input is left as it
+-- is, for each reason that 'signPsbt' lists.
+signEcdsa ::
+  Network -> Signer -> TxSigHashes -> Int -> TxIn -> PsbtMap -> TxOut -> Bool -> SigHash -> Maybe (PsbtMap, [SigHash])
+signEcdsa net signer sigHashes i input m coin witnessOnly sighash = do
+  spend <- inputSpend coin m
+  let witnessCoin = isSegwit spend.program
+  -- BIP 174 has the signer check the scripts that the input provides
+  guard (not spend.strayScript)
+  -- Only a witness signature may rely on a witness output, and a signer
+  -- may want the previous transaction for that one too
+  guard (not witnessOnly || (witnessCoin && not signer.requirePreviousTx))
+  guard (not witnessCoin || coin.value <= net.maxSatoshi)
+  let sigInput = signingInput input coin sighash spend
+      signatures =
+        [ (public, encodeTxSig net signature)
+        | key <- heldKeys signer m (scriptKeyHashes spend.naming),
+          key.compress || not witnessCoin,
+          let public = derivePublicKey key,
+          Map.notMember (Key partialSigType (encodeSerial public)) m,
+          Right signature <- [makeSignatureWith net sigHashes i sigInput key]
+        ]
+  guard (not (null signatures))
+  return (foldr (uncurry insertPartialSignature) m signatures, [sighash])
+
+-- | The keys the signer holds among those whose hashes the script that is
+-- signed names. The signer is asked for the key of a derivation record
+-- only when the hash of the key of the record is one of them, so the work
+-- it does is bounded by the script, however many records the PSBT carries.
+-- A key the signer gives is kept only when it is the key that was asked
+-- for. A record that does not decode names no key.
+heldKeys :: Signer -> PsbtMap -> [Hash160] -> [PrivateKey]
+heldKeys signer m named = nubBy (\a b -> derivePublicKey a == derivePublicKey b) (recordKeys <> hashKeys)
+  where
+    recordKeys =
+      [ PrivateKey secret public.compress
+      | (key, value) <- Map.toAscList m,
+        key.keyType == inDerivationType,
+        addressHash key.keyData `elem` named,
+        Right public <- [decodeSerial key.keyData :: Either String PublicKey],
+        Right derivation <- [decodeDerivation value],
+        Just secret <- [signer.keyOfRecord public derivation],
+        derivePubKey secret == public.point
+      ]
+    hashKeys = [key | h <- named, Just key <- [signer.keyOfHash h], addressHash (encodeSerial (derivePublicKey key)) == h]
+
+-- | An input with a key path signature, or else one signature for each
+-- leaf that is the check of a key the signer holds, for a Taproot coin,
+-- and the sighash type used. 'Nothing' when no signature is added: while
+-- another input lacks its coin, since the BIP 341 digest commits to the
+-- output that every input spends, when the signer holds no key, and when
+-- the digest does not exist (SIGHASH_SINGLE with no output at the index).
+--
+-- As Bitcoin Core (@SignTaproot@): a signature that the input has stays,
+-- and an input that has or gets a key path signature gets no leaf
+-- signature.
+signTaproot :: Signer -> Maybe TaprootTxHashes -> Int -> PsbtMap -> TxOut -> SigHash -> Maybe (PsbtMap, [SigHash])
+signTaproot signer hashesM i m coin sighash = do
+  hashes <- hashesM
+  let held = heldTaprootKeys signer (taprootProgram coin) m
+      signatureFor secret leafM = eitherToMaybe $ do
+        h <- taprootSigHashWith hashes i sighash Nothing ((,0xffffffff) <$> leafM)
+        taprootSignature (signSchnorr secret (hashToMsg h)) sighash
+      hasKeySig = Map.member (Key tapKeySigType B.empty) m
+      keySig =
+        [ insertTapKeySig signature
+        | not hasKeySig,
+          Just secret <- [held.keyPathKey],
+          Just signature <- [signatureFor secret Nothing]
+        ]
+      leafSigs =
+        [ insertTapScriptSig leafKey hashOfLeaf signature
+        | not hasKeySig,
+          null keySig,
+          (leafKey, hashOfLeaf, secret) <- held.leafKeys,
+          Map.notMember (tapScriptSigKey (exportXOnlyPubKey leafKey) hashOfLeaf) m,
+          Just signature <- [signatureFor secret (Just hashOfLeaf)]
+        ]
+      added = keySig <> leafSigs
+  guard (not (null added))
+  return (foldr ($) m added, [sighash])
+
+-- | The secret keys a signer holds for a Taproot input
+data TaprootKeys = TaprootKeys
+  { -- | the secret key that signs the key path of the coin: the secret
+    -- key of the internal key, tweaked, or the one of the output key
+    keyPathKey :: Maybe SecKey,
+    -- | for each leaf the signer can sign: the key of the leaf, the hash
+    -- of the leaf, and the secret key
+    leafKeys :: [(PubKey, Digest SHA256, SecKey)]
+  }
+
+-- | The keys a signer holds for a Taproot input whose coin has the witness
+-- program: the key of its key path, and the key of each leaf script that
+-- is the check of one key ('singleKeyLeaves').
+--
+-- The key path has two keys, tried in the order of Bitcoin Core. First the
+-- internal key that the input names, when the signer holds it. It counts
+-- only when it gives, with the Merkle root of the input, the output key of
+-- the coin, as BIP 174 has a signer make only valid signatures: Bitcoin
+-- Core signs with an internal key that does not, and that signature
+-- verifies for no coin. Then the output key of the coin itself, for a coin
+-- that pays to a key with no tweak.
+--
+-- A leaf counts whatever its control block holds, as in Bitcoin Core.
+--
+-- A field that cannot be used gives no key and no refusal: an internal key
+-- that is no point of the curve, a Merkle root that is not a hash, a
+-- record that does not decode. A signer holds no key for such a field, and
+-- the input may belong to another party, whose fields are not the signer's
+-- to judge.
+heldTaprootKeys :: Signer -> ByteString -> PsbtMap -> TaprootKeys
+heldTaprootKeys signer program m =
+  TaprootKeys
+    { keyPathKey = ofInternalKey <|> (importXOnlyPubKey program >>= held),
+      leafKeys =
+        [ (leafKey, leafHashBytes tapscriptLeafVersion script, secret)
+        | script <- Map.keys (singleKeyLeaves m),
+          Just leafKey <- [importXOnlyPubKey (leafKeyBytes script)],
+          Just secret <- [held leafKey]
+        ]
+    }
+  where
+    ofInternalKey = do
+      internal <- either (const Nothing) id (inputTapInternalKey m)
+      commitment <- fmap MASTCommitment <$> eitherToMaybe (inputTapMerkleRoot m)
+      guard ((exportXOnlyPubKey <$> taprootOutputKey (TaprootOutput internal commitment)) == Right program)
+      secret <- held internal
+      taprootOutputSecKey secret commitment
+    -- The record of each x-only key, by the 32 bytes of the key. An input
+    -- has at most one record for a key, since the key is the key of the
+    -- entry in its map. A key finds its record here by a lookup: a walk
+    -- through the records for each leaf would take time by the product of
+    -- two numbers that whoever wrote the PSBT chooses. Any record of a key
+    -- will do, whichever leaves it lists: Bitcoin Core finds a key by its
+    -- record and does not read the list.
+    recordOf = Map.fromList [(key.keyData, value) | (key, value) <- Map.toAscList m, key.keyType == inTapDerivationType]
+    -- The secret key of an x-only key, by the record of that key or by the
+    -- hash of the key. A key the signer gives is kept only when it is the
+    -- key that was asked for.
+    held :: PubKey -> Maybe SecKey
+    held public =
+      listToMaybe . filter (sameX public . derivePubKey) . catMaybes $
+        [ signer.keyOfRecord (PublicKey candidate True) record.derivation
+        | Just (Right record) <- [decodeTapDerivation <$> Map.lookup (exportXOnlyPubKey public) recordOf],
+          candidate <- bothParities public
+        ]
+          <> [ (.key) <$> signer.keyOfHash (addressHash (encodeSerial (PublicKey candidate True)))
+             | candidate <- bothParities public
+             ]
+    sameX a b = exportXOnlyPubKey a == exportXOnlyPubKey b
+    -- The two points with the x coordinate of the key
+    bothParities public =
+      [ candidate.point
+      | prefix <- [0x02, 0x03],
+        Right candidate <- [decodeSerial (B.cons prefix (exportXOnlyPubKey public)) :: Either String PublicKey]
+      ]
+
+-- | The sighash type of an ECDSA signature for an input that asks for
+-- none: SIGHASH_ALL, with the fork id flag on a network that has one
+defaultEcdsaSigHash :: Network -> SigHash
+defaultEcdsaSigHash net
+  | isJust net.sigHashForkId = setForkIdFlag sigHashAll
+  | otherwise = sigHashAll
+
+-- | The hashes of the keys a script names: the keys a coin of that script
+-- is signed with
+scriptKeyHashes :: ScriptOutput -> [Hash160]
+scriptKeyHashes = \case
+  PayPK public -> [addressHash (encodeSerial public)]
+  PayPKHash h -> [h]
+  PayWitnessPKHash h -> [h]
+  PayMulSig publics _ -> map (addressHash . encodeSerial) publics
+  _ -> []
+
+-- | The leaf scripts of a Taproot input that are the check of one key,
+-- @\<key\> OP_CHECKSIG@ of the leaf version 0xc0, which is the leaf that
+-- the signer signs and the finalizer spends: the bytes of each script,
+-- with the control blocks of its entries. One script has an entry for each
+-- place it has in the tree.
+--
+-- The entry is read as Bitcoin Core reads it: the leaf version is the one
+-- of its value, and nothing is asked of the control block, nor of the 32
+-- bytes of the key. BIP 342 gives the script its meaning for the leaf
+-- version 0xc0 only.
+singleKeyLeaves :: PsbtMap -> Map ByteString [ByteString]
+singleKeyLeaves m =
+  Map.fromListWith
+    (<>)
+    [ (B.init value, [key.keyData])
+    | (key, value) <- Map.toAscList m,
+      key.keyType == tapLeafScriptType,
+      -- The push of 32 bytes, OP_CHECKSIG, and the leaf version
+      B.length value == 35,
+      B.head value == 0x20,
+      B.index value 33 == 0xac,
+      B.last value == tapscriptLeafVersion
+    ]
+
+-- | The 32 bytes of the key of a script of 'singleKeyLeaves'
+leafKeyBytes :: ByteString -> ByteString
+leafKeyBytes = B.take 32 . B.drop 1
+
+-- | The key of the entry of a script path signature: PSBT_IN_TAP_SCRIPT_SIG
+-- with the 32 bytes of the x-only key and the leaf hash
+tapScriptSigKey :: ByteString -> Digest SHA256 -> Key
+tapScriptSigKey keyBytes leaf = Key tapScriptSigType (keyBytes <> BA.convert leaf)
+
+-- | Whether a control block commits a leaf script of the leaf version 0xc0
+-- to the output key of the coin, with that leaf version. A spend takes the
+-- leaf version from the first byte of the control block (BIP 341): one
+-- that holds another version spends another leaf, which is not the one
+-- that was signed.
+commitsLeaf :: PubKey -> ByteString -> ByteString -> Bool
+commitsLeaf outKey control scriptBytes = case decodeControlBlock control of
+  Right (v, internalKey, proof)
+    | v .&. 0xfe == tapscriptLeafVersion ->
+        verifyScriptPathData outKey $
+          ScriptPathData Nothing [] (Script []) (odd v) tapscriptLeafVersion internalKey proof (Just scriptBytes)
+  _ -> False
+
+-- | Whether every signature of an input is of the sighash type, as Bitcoin
+-- Core checks it before it signs or finalizes an input (@SignPSBTInput@),
+-- by the bytes alone: a Taproot signature of 64 bytes is of
+-- SIGHASH_DEFAULT, one of 65 bytes of the type of its last byte, and a
+-- partial signature of the type of its last byte. For SIGHASH_DEFAULT,
+-- which no ECDSA signature has, Bitcoin Core does not look at the partial
+-- signatures.
+signaturesUse :: SigHash -> PsbtMap -> Bool
+signaturesUse sighash m
+  | sighash == sigHashDefault = all ((== 64) . B.length) taprootSignatures
+  | otherwise = all (\value -> B.length value == 65 && ofType value) taprootSignatures && all ofType (valuesOf [partialSigType])
+  where
+    valuesOf types = [value | (key, value) <- Map.toAscList m, key.keyType `elem` types]
+    taprootSignatures = valuesOf [tapKeySigType, tapScriptSigType]
+    ofType value = not (B.null value) && fromIntegral (B.last value) == sighash
+
+-- | The error for a sighash type the signer does not accept
+notAcceptedSigHash :: SigHash -> String
+notAcceptedSigHash sighash =
+  "the sighash type " <> show (fromIntegral sighash :: Word32) <> " is not one the signer accepts"
+
+-- | A sighash type an ECDSA signature may carry on the network: one of
+-- ALL, NONE and SINGLE, with ANYONECANPAY or not, and the fork id flag
+-- exactly on the networks with a fork id
+checkEcdsaSigHash :: Network -> SigHash -> Either String ()
+checkEcdsaSigHash net sighash = do
+  when (isSigHashUnknown sighash) $
+    Left ("the sighash type " <> show (fromIntegral sighash :: Word32) <> " is not one a node accepts")
+  when (isJust net.sigHashForkId && not (hasForkIdFlag sighash)) $
+    Left "the sighash type lacks the fork id flag the network requires"
+  when (isNothing net.sigHashForkId && hasForkIdFlag sighash) $
+    Left "the sighash type has a fork id flag the network does not use"
+
+-- | The sighash type of an input that asks for none: SIGHASH_DEFAULT for a
+-- Taproot coin, and that of 'defaultEcdsaSigHash' for any other
+defaultSigHash :: Network -> TxOut -> SigHash
+defaultSigHash net coin
+  | isTaprootCoin net coin = sigHashDefault
+  | otherwise = defaultEcdsaSigHash net
+
+-- | A sighash type a signature of the coin may carry on the network
+checkSigHash :: Network -> TxOut -> SigHash -> Either String ()
+checkSigHash net coin sighash
+  | isTaprootCoin net coin =
+      unless (isTaprootSigHash sighash) $
+        Left ("the sighash type " <> show (fromIntegral sighash :: Word32) <> " is not one a Taproot signature may use")
+  | otherwise = checkEcdsaSigHash net sighash
+
+-- | Whether a coin is a Taproot output: a witness program of version 1 and
+-- 32 bytes, on a network that has SegWit. The bytes of the script tell, as
+-- in Bitcoin Core (@IsPayToTaproot@). On a network without SegWit the same
+-- bytes are a script that anyone can spend, and no Taproot rule applies.
+isTaprootCoin :: Network -> TxOut -> Bool
+isTaprootCoin net coin = net.segWit && B.length coin.script == 34 && B.take 2 coin.script == "\x51\x20"
+
+-- | The witness program of a Taproot coin: the 32 bytes of its output key
+taprootProgram :: TxOut -> ByteString
+taprootProgram coin = B.drop 2 coin.script
+
+-- | The PSBT after a signature with the sighash was added, as the signer
+-- of BIP 370 leaves the flags of version 2: inputs may no longer be added
+-- unless the sighash has ANYONECANPAY, outputs no longer unless it is
+-- NONE, and the PSBT has a SIGHASH_SINGLE signature when it is SINGLE. A
+-- PSBT of version 0 has no flags.
+afterSignature :: SigHash -> Psbt -> Psbt
+afterSignature sighash psbt = case psbt.version of
+  Version0 -> psbt
+  Version2
+    | isJust beforeM || after /= noFlags -> Psbt Version2 psbt.unsignedTx (insertTxModifiable after psbt.globals) psbt.inputs psbt.outputs
+    | otherwise -> psbt
+  where
+    beforeM = either (const Nothing) id (txModifiable psbt.globals)
+    before = fromMaybe noFlags beforeM
+    after =
+      before
+        { inputsModifiable = before.inputsModifiable && anyoneCanPay sighash,
+          outputsModifiable = before.outputsModifiable && isSigHashNone sighash,
+          hasSigHashSingle = before.hasSigHashSingle || isSigHashSingle sighash
+        }
+
+-- | Whether an input has its final script or witness
+isFinal :: PsbtMap -> Bool
+isFinal m = any (`Map.member` m) [Key finalScriptSigType B.empty, Key finalScriptWitnessType B.empty]
+
+{- The coins of a PSBT -}
+
+-- | The coin an input of a PSBT spends, as the PSBT gives it
+data InputCoin = InputCoin
+  { -- | the output the input spends: its amount and its script
+    coin :: !TxOut,
+    -- | 'True' when the coin is the output of the previous transaction of
+    -- the input, whose id the input names, so that it cannot be made up.
+    -- 'False' when the PSBT gives the output alone (PSBT_IN_WITNESS_UTXO):
+    -- its amount is then a claim of whoever wrote the PSBT.
+    fromPreviousTx :: !Bool
+  }
+  deriving (Eq, Show, Read, Generic)
+  deriving anyclass (NFData)
+
+-- | The coin every input of a PSBT spends, 'Nothing' for an input that
+-- carries none. A previous transaction must be the one its input spends
+-- and have the output it spends. It gives the coin, and a witness output
+-- beside it is not read, as in Bitcoin Core.
+--
+-- An amount with 'fromPreviousTx' is checked. Another is only checked by a
+-- signature that commits to it: a SegWit version 0 signature commits to
+-- the amount of its own coin, and a Taproot signature to the amount of
+-- every coin of the transaction. Show a user amounts and a fee from
+-- checked coins only, or from a PSBT in which the user signs a Taproot
+-- input.
+inputCoins :: Psbt -> Either String [Maybe InputCoin]
+inputCoins psbt = map (fmap (\(output, witnessOnly) -> InputCoin output (not witnessOnly))) <$> spentOutputs psbt
+
+-- | The fee of the transaction of a PSBT: what its coins hold above what
+-- its outputs pay. Every input must carry its previous transaction, so
+-- that no amount is a claim ('inputCoins' tells which are). A PSBT whose
+-- outputs pay more than its coins hold has no fee.
+psbtFee :: Psbt -> Either String Word64
+psbtFee psbt = do
+  coins <- inputCoins psbt
+  amounts <- forM (zip [0 :: Int ..] coins) $ \(i, coinM) -> case coinM of
+    Nothing -> Left ("Input " <> show i <> " has no coin")
+    Just found
+      | found.fromPreviousTx -> Right (toInteger found.coin.value)
+      | otherwise -> Left ("Input " <> show i <> ": the coin is given as a witness output only, so its amount is not checked")
+  let fee = sum amounts - sum (toInteger . (.value) <$> psbt.unsignedTx.outputs)
+  when (fee < 0) $ Left "The outputs pay more than the coins hold"
+  return (fromInteger fee)
+
+-- | The output every input spends, from the fields of each input, and
+-- whether it is known from the witness output alone
+spentOutputs :: Psbt -> Either String [Maybe (TxOut, Bool)]
+spentOutputs psbt =
+  forM (zip3 [0 :: Int ..] psbt.unsignedTx.inputs psbt.inputs) $ \(i, input, m) ->
+    first (("Input " <> show i <> ": ") <>) (spentOutput input m)
+
+-- | The hashes that the BIP 341 digests of the Taproot inputs share, once
+-- every input has its coin: the digest commits to the output that every
+-- input spends. The signer and the finalizer take them once for a PSBT, as
+-- Bitcoin Core does (@PrecomputePSBTData@), so that a digest takes time by
+-- the size of its own input, and not by the size of the transaction.
+taprootHashes :: Tx -> [Maybe (TxOut, Bool)] -> Maybe TaprootTxHashes
+taprootHashes tx coins = mapM (fmap fst) coins >>= eitherToMaybe . taprootTxHashes tx
+
+-- | The output an input spends, from the fields of the input: the output
+-- of its previous transaction, which must be the transaction the input
+-- spends from, or else its witness output alone. The flag tells when the
+-- witness output alone is known, which only a witness signature may rely
+-- on. With both, the previous transaction gives the coin and the witness
+-- output is not read, as in Bitcoin Core (@PSBTInput::GetUTXO@): the id of
+-- the previous transaction is checked, and a witness output is a claim.
+spentOutput :: TxIn -> PsbtMap -> Either String (Maybe (TxOut, Bool))
+spentOutput input m = do
+  parentM <- nonWitnessUtxo m
+  case parentM of
+    Just parent -> (\output -> Just (output, False)) <$> previousOutput input parent
+    Nothing -> fmap (,True) <$> witnessUtxo m
+
+-- | How a coin signed with ECDSA is spent, from its script and the redeem
+-- and witness scripts of its input
+data Spend = Spend
+  { -- | the script the coin is signed against: the script of the coin, or
+    -- the witness program its redeem script is when it is nested in P2SH
+    program :: ScriptOutput,
+    -- | the script that names the keys: the script of the coin, its
+    -- redeem script or its witness script. It is a P2PK, P2PKH or multisig
+    -- script, or the P2WPKH program itself.
+    naming :: ScriptOutput,
+    -- | the redeem script of a P2SH coin
+    redeemScript :: Maybe Script,
+    -- | the witness script of a P2WSH coin, nested in P2SH or not
+    witnessScript :: Maybe Script,
+    -- | whether the input has a redeem script or a witness script that is
+    -- not the one of its coin
+    strayScript :: Bool
+  }
+
+-- | How the coin of an input is spent, as Bitcoin Core solves it
+-- (@ProduceSignature@). A redeem script serves only when it hashes to the
+-- P2SH coin, and a witness script only when it hashes to the witness
+-- program, which is what BIP 174 has a signer check. 'Nothing' for a coin
+-- that the library cannot sign or finalize, which is left to others:
+--
+-- * a coin without the script it commits to, or with one that does not
+--   parse;
+-- * a redeem script of more than 'maxRedeemScriptSize' bytes, or a
+--   witness script of more than 'maxWitnessScriptSize': no transaction
+--   can spend the coin. Bitcoin Core adds a signature to such a coin, and
+--   makes no final script of it;
+-- * a script that names the keys and is no standard template;
+-- * a script hash or a witness program where none may be: a P2SH script as
+--   redeem script, or a P2SH script or a witness program as witness
+--   script. Such a script is run as a script and not as a commitment, so
+--   no signature spends the coin.
+inputSpend :: TxOut -> PsbtMap -> Maybe Spend
+inputSpend coin m = do
+  coinScript <- eitherToMaybe (decodeSerial coin.script)
+  let given field = either (const Nothing) id (field m)
+      redeemM = mfilter ((== Right coinScript) . toP2SH) (given inputRedeemScript)
+  program <- case coinScript of
+    PayScriptHash _ -> do
+      redeem <- redeemM >>= eitherToMaybe . decodeOutput
+      return (if isSegwit redeem then redeem else coinScript)
+    _ -> Just coinScript
+  let witnessM = mfilter ((== Right program) . toP2WSH) (given inputWitnessScript)
+  naming <- case program of
+    PayWitnessScriptHash _ -> witnessM >>= eitherToMaybe . decodeOutput >>= keyScript
+    PayScriptHash _ -> redeemM >>= eitherToMaybe . decodeOutput >>= keyScript
+    PayWitnessPKHash _ -> Just program
+    _ -> keyScript program
+  return
+    Spend
+      { program = program,
+        naming = naming,
+        redeemScript = redeemM,
+        witnessScript = witnessM,
+        strayScript =
+          (Map.member (Key inRedeemScriptType B.empty) m && isNothing redeemM)
+            || (Map.member (Key inWitnessScriptType B.empty) m && isNothing witnessM)
+      }
+  where
+    keyScript out = case out of
+      PayPK _ -> Just out
+      PayPKHash _ -> Just out
+      PayMulSig _ _ -> Just out
+      _ -> Nothing
+
+-- | What an input is signed against, as 'makeSignatureWith' wants it: the
+-- script of its coin or its witness program, with the redeem script of a
+-- P2SH coin or the witness script of a P2WSH coin
+signingInput :: TxIn -> TxOut -> SigHash -> Spend -> SigInput
+signingInput input output sighash spend =
+  SigInput
+    { script = spend.program,
+      value = output.value,
+      outpoint = input.outpoint,
+      sighash = sighash,
+      redeem = case spend.program of
+        PayWitnessScriptHash _ -> Just spend.naming
+        PayScriptHash _ -> Just spend.naming
+        _ -> Nothing
+    }
+
+{- Finalizing -}
+
+-- | Finalize every input whose signatures suffice for the coin it spends,
+-- as the finalizer of the spec does: the final script and witness go in
+-- the input, and its partial signatures, sighash type, redeem script,
+-- witness script, derivation records, hash preimages, Taproot fields and
+-- MuSig2 fields go, as Bitcoin Core drops them. Its coin and the keys the
+-- library does not define stay. An input that is final already loses
+-- those fields too.
+--
+-- __One input at a time.__ BIP 174: "For each input, the Input Finalizer
+-- determines if the input has enough data to pass validation." An input
+-- that does not is left as it is, and the others are finalized, as in
+-- Bitcoin Core (@FinalizePSBT@), which refuses nothing. The only refusal
+-- here is for a previous transaction that is not the one its input spends,
+-- which 'decodePsbt' does not read either. 'psbtTransaction' tells whether
+-- every input is final.
+--
+-- __The final script.__ The finalizer makes the one script that Bitcoin
+-- Core would make, and then checks it. When it does not pass, the input is
+-- left, and no other choice of signatures is tried:
+--
+-- * a multisig takes the signatures of the first keys, in the order of the
+--   script, that have one, as many as it requires;
+-- * a Taproot coin takes its key path signature when it has one, and
+--   otherwise the signed leaf whose witness is smallest: the one with the
+--   shortest control block, since the leaves are the check of one key.
+--
+-- Each signature that is used must verify against the digest of the coin
+-- and be one that nodes relay: no high S, and no uncompressed key on a
+-- SegWit version 0 coin. A leaf must be committed to the coin by its
+-- control block, with the leaf version 0xc0. A signature that is not used
+-- is not verified, so it cannot stop an input that is ready.
+--
+-- __The sighash type.__ Every signature of the input, used or not, must be
+-- of the type the input names: BIP 174 has the finalizer "fail to finalize
+-- that input if any signature does not match the specified sighash type".
+-- When the input names none, Bitcoin Core wants SIGHASH_ALL, with the fork
+-- id flag on a network that has one, and SIGHASH_DEFAULT for a Taproot
+-- coin, where it does not look at partial signatures.
+--
+-- __What is left as it is.__ Besides an input without enough signatures:
+-- one without its coin, one whose scripts are no standard template, a
+-- legacy coin known from its witness output only, a Taproot coin whose
+-- output key is no point of the curve, which nobody can spend, and a
+-- signed Taproot coin while another input of the PSBT lacks its coin,
+-- since the digest of a Taproot signature commits to the output every
+-- input spends and the signature cannot be verified before.
+--
+-- A redeem script or a witness script on a coin that has none does not
+-- stop the finalizer, as it does not stop Bitcoin Core: BIP 174 gives that
+-- check to the signer.
+--
+-- The coins finalized are those of P2PK, P2PKH and multisig scripts, P2SH
+-- coins with their redeem script, P2WPKH coins, P2WSH coins with their
+-- witness script, nested in P2SH or not, and Taproot coins by their key
+-- path signature or by a leaf script that is the check of one key.
+--
+-- __Cost.__ A Taproot input of a PSBT that another party wrote can hold
+-- thousands of leaf scripts and of script path signatures, at no cost to
+-- its writer. A leaf finds its signature by a lookup, so the time such an
+-- input takes grows with its size, and not with the product of the two
+-- numbers. The hashes that the digests of the inputs share are computed
+-- once for the PSBT ('taprootTxHashes' for the Taproot inputs,
+-- 'txSigHashes' for the SegWit version 0 inputs), so the time for all the
+-- inputs grows with the size of the PSBT, and not with its square. A
+-- legacy input is the exception: its digest hashes a copy of the whole
+-- transaction, in Bitcoin Core too.
+finalizePsbt :: Network -> Psbt -> Either String Psbt
+finalizePsbt net psbt = do
+  coins <- spentOutputs psbt
+  let hashes = taprootHashes tx coins
+      sigHashes = txSigHashes tx
+  inputs <- forM (zip3 [0 ..] (zip tx.inputs psbt.inputs) coins) $ \(i, (input, m), coinM) ->
+    first (("Input " <> show i <> ": ") <>) $ case coinM of
+      _ | isFinal m -> return (cleared m)
+      Nothing -> return m
+      Just (coin, witnessOnly) -> do
+        sighashM <- sigHashType m
+        let sighash = fromMaybe (defaultSigHash net coin) sighashM
+            finals
+              -- BIP 174 asks it of every signature when the input names a
+              -- type, also for the type 0, which no partial signature has
+              | not (signaturesUse sighash m) || (sighashM == Just sigHashDefault && hasPartialSignatures m) = Nothing
+              | isTaprootCoin net coin = finalTaproot hashes i m coin
+              | otherwise = finalEcdsa net sigHashes i input m coin witnessOnly sighash
+        return (maybe m (finalized m) finals)
+  return $ Psbt psbt.version tx psbt.globals inputs psbt.outputs
+  where
+    tx = psbt.unsignedTx
+    finalized m (scriptSig, stack) =
+      foldr ($) (cleared m) $
+        [insertFinalScriptSig scriptSig | not (B.null scriptSig)]
+          <> [insertFinalScriptWitness stack | not (null stack)]
+    cleared = Map.filterWithKey (\key _ -> key.keyType `notElem` clearedTypes)
+    clearedTypes =
+      [ partialSigType,
+        sigHashTypeType,
+        inRedeemScriptType,
+        inWitnessScriptType,
+        inDerivationType,
+        ripemd160Type,
+        sha256Type,
+        hash160Type,
+        hash256Type,
+        tapKeySigType,
+        tapScriptSigType,
+        tapLeafScriptType,
+        inTapDerivationType,
+        inTapInternalKeyType,
+        tapMerkleRootType,
+        inMusigParticipantsType,
+        musigNonceType,
+        musigPartialSigType
+      ]
+
+-- | The final script and witness of an input signed with ECDSA, from the
+-- partial signatures that its script takes, when they suffice and each of
+-- them verifies. 'Nothing' leaves the input as it is.
+finalEcdsa ::
+  Network -> TxSigHashes -> Int -> TxIn -> PsbtMap -> TxOut -> Bool -> SigHash -> Maybe (ByteString, WitnessStack)
+finalEcdsa net sigHashes i input m coin witnessOnly sighash = do
+  spend <- inputSpend coin m
+  let witnessCoin = isSegwit spend.program
+      sigInput = signingInput input coin sighash spend
+  -- Only a witness signature may rely on a witness output
+  guard (witnessCoin || not witnessOnly)
+  used <- usedSignatures spend.naming (namedSignatures m spend.naming)
+  digest <- eitherToMaybe (makeSigHashWith net sigHashes i sigInput.script coin.value sighash sigInput.redeem)
+  -- One digest serves every signature: all are of the sighash type, by
+  -- 'signaturesUse'
+  forM_ used $ \(public, bytes) -> do
+    TxSignature signature _ <- eitherToMaybe (decodeTxSig net bytes)
+    guard (public.compress || not witnessCoin)
+    guard (verifyHashSig digest signature public.point)
+  let items = case spend.naming of
+        PayPK _ -> map snd used
+        PayMulSig _ _ -> B.empty : map snd used
+        _ -> concat [[signature, encodeSerial public] | (public, signature) <- used]
+      redeemItem = S.encode <$> maybeToList spend.redeemScript
+      witnessItem = S.encode <$> maybeToList spend.witnessScript
+      pushes = S.encode . Script . map opPushData
+  return $
+    if witnessCoin
+      then (pushes redeemItem, items <> witnessItem)
+      else (pushes (items <> redeemItem), [])
+
+-- | The signatures that a script takes, among those of the keys it names:
+-- the one of its key, or for a multisig those of its first keys that have
+-- one, in the order of the script and as many as it requires, which is
+-- the choice of Bitcoin Core (@SignStep@). 'Nothing' when they do not
+-- suffice.
+usedSignatures :: ScriptOutput -> [(PublicKey, ByteString)] -> Maybe [(PublicKey, ByteString)]
+usedSignatures naming named = case naming of
+  PayPK public -> (: []) . (public,) <$> lookup public named
+  PayPKHash h -> (: []) <$> ofHash h
+  PayWitnessPKHash h -> (: []) <$> ofHash h
+  PayMulSig keys n
+    | length found >= n -> Just (take n found)
+    where
+      found = [(key, signature) | key <- keys, Just signature <- [lookup key named]]
+  _ -> Nothing
+  where
+    ofHash h = find ((== h) . addressHash . encodeSerial . fst) named
+
+-- | The partial signatures of an input whose keys the script names, in
+-- the order of the map. A key is named by a script of public keys when it
+-- is one of them, and by a script of a key hash when it has that hash.
+-- The others are not looked at, so their number costs nothing.
+namedSignatures :: PsbtMap -> ScriptOutput -> [(PublicKey, ByteString)]
+namedSignatures m script =
+  [ (public, sig)
+  | (key, sig) <- Map.toAscList m,
+    key.keyType == partialSigType,
+    addressHash key.keyData `elem` named,
+    Right public <- [decodeSerial key.keyData]
+  ]
+  where
+    named = scriptKeyHashes script
+
+-- | The final witness of a Taproot input: its key path signature, or the
+-- signature of a leaf script that is the check of one key, with the
+-- script and its control block. The witness is the one Bitcoin Core makes
+-- (@SignTaproot@): the key path signature when the input has one, and
+-- otherwise the leaf of 'smallestSignedLeaf'. 'Nothing' leaves the input
+-- as it is: when it has no signature to use, when the signature does not
+-- verify or the control block does not commit the leaf to the coin, when
+-- the output key is no point of the curve, and while another input lacks
+-- its coin, since the signature cannot be verified before.
+finalTaproot :: Maybe TaprootTxHashes -> Int -> PsbtMap -> TxOut -> Maybe (ByteString, WitnessStack)
+finalTaproot hashesM i m coin = do
+  hashes <- hashesM
+  outKey <- importXOnlyPubKey (taprootProgram coin)
+  let verified public leafM bytes = do
+        signature <- eitherToMaybe (decodeTaprootSig bytes)
+        digest <- eitherToMaybe (taprootSigHashWith hashes i signature.hash Nothing ((,0xffffffff) <$> leafM))
+        guard (verifySchnorr public signature.sig (hashToMsg digest))
+  (B.empty,) <$> case plainField tapKeySigType m of
+    Just bytes -> [bytes] <$ verified outKey Nothing bytes
+    Nothing -> do
+      (script, control, bytes) <- smallestSignedLeaf m
+      leafKey <- importXOnlyPubKey (leafKeyBytes script)
+      guard (commitsLeaf outKey control script)
+      [bytes, script, control] <$ verified leafKey (Just (leafHashBytes tapscriptLeafVersion script)) bytes
+
+-- | The signed leaf of a Taproot input that Bitcoin Core spends
+-- (@SignTaproot@): its script, its control block and its signature. A leaf
+-- is signed when the input has a signature entry for its key and its leaf
+-- hash. Bitcoin Core takes each leaf with its shortest control block, and
+-- among the leaves the one whose witness is smallest. The leaves of
+-- 'singleKeyLeaves' have scripts of one size, and all the signatures of an
+-- input have one size ('signaturesUse'), so that is the leaf with the
+-- shortest control block. Among equals the first counts: by the bytes of
+-- the script for the leaves, and by the bytes for the control blocks.
+--
+-- A leaf finds its signature by a lookup: a walk through the signatures
+-- for each leaf would take time by the product of two numbers that whoever
+-- wrote the PSBT chooses.
+smallestSignedLeaf :: PsbtMap -> Maybe (ByteString, ByteString, ByteString)
+smallestSignedLeaf m
+  | null signed = Nothing
+  | otherwise = Just (minimumBy (comparing (\(_, control, _) -> B.length control)) signed)
+  where
+    signed =
+      [ (script, minimumBy (comparing B.length <> compare) controls, signature)
+      | (script, controls) <- Map.toAscList (singleKeyLeaves m),
+        Just signature <- [Map.lookup (tapScriptSigKey (leafKeyBytes script) (leafHashBytes tapscriptLeafVersion script)) m]
+      ]
diff --git a/src/Haskoin/Transaction/Segwit.hs b/src/Haskoin/Transaction/Segwit.hs
--- a/src/Haskoin/Transaction/Segwit.hs
+++ b/src/Haskoin/Transaction/Segwit.hs
@@ -30,6 +30,7 @@
   )
 where
 
+import Control.Monad (unless)
 import Crypto.Secp256k1
 import Data.ByteString (ByteString)
 import Data.Bytes.Get (runGetS)
@@ -111,8 +112,34 @@
     | null witness -> return EmptyWitnessProgram
     | otherwise -> Left "viewWitnessProgram: Invalid witness program"
 
--- | Analyze the witness, trying to match it with standard input structures
+-- | Match a witness program with the standard inputs. For a
+-- pay-to-witness-public-key-hash coin the answer is the signature and the
+-- key. For a pay-to-witness-script-hash coin it is the witness script as a
+-- 'ScriptOutput', and the input that such a script takes.
 --
+-- A 'ScriptOutput' does not keep the bytes of a script: see 'decodeOutput'.
+-- The caller only has 'encodeOutput' of the value returned here to hash
+-- and to sign, as 'Haskoin.Transaction.Builder.verifyStdInput' does. So a
+-- witness script that 'encodeOutput' would write back as other bytes is
+-- refused, as 'decodeInput' refuses such a redeem script. If one was read,
+-- a spend would verify although its witness script is not the one the coin
+-- commits to: the hash and the digest are taken on the script written
+-- back, which is the one of the coin. By consensus the hash of the bytes
+-- in the witness must be the witness program (BIP 141), so no block holds
+-- that spend.
+--
+-- The script this is about is a multisig whose keys are not direct pushes.
+-- 'decodeOutput' does not read it, so it is refused before this check. The
+-- check stays, so that a template that 'decodeOutput' learns later cannot
+-- bring the fault back. The one script it still refuses by itself is a
+-- data carrier whose data is not pushed in the shortest way, which is no
+-- witness script that is read here anyway.
+--
+-- The cost: the spend of a coin that does commit to such a multisig script
+-- is not read here, although a block may hold it. Nodes do not relay that
+-- spend (the @MINIMALDATA@ rule of the relay policy), and the signer of
+-- this library cannot make it.
+--
 -- @since 0.11.0.0
 decodeWitnessInput ::
   Network ->
@@ -122,6 +149,10 @@
   P2WPKH (WitnessProgramPKH sig key) -> return (Nothing, SpendPKHash sig key)
   P2WSH (WitnessProgramSH st scr) -> do
     so <- decodeOutput scr
+    -- A 'Script' is written as the bytes it was read from, so equal
+    -- scripts are equal bytes.
+    unless (encodeOutput so == Right scr) $
+      Left "decodeWitnessInput: the witness script is not in the form that encodeOutput writes"
     fmap (Just so,) $ case (so, st) of
       (PayPK _, [sigBS]) ->
         SpendPK <$> decodeTxSig net sigBS
diff --git a/src/Haskoin/Transaction/Taproot.hs b/src/Haskoin/Transaction/Taproot.hs
--- a/src/Haskoin/Transaction/Taproot.hs
+++ b/src/Haskoin/Transaction/Taproot.hs
@@ -65,6 +65,9 @@
     taprootSignature,
     isTaprootSigHash,
     taprootSigHash,
+    TaprootTxHashes,
+    taprootTxHashes,
+    taprootSigHashWith,
     encodeTaprootSig,
     decodeTaprootSig,
   )
@@ -97,8 +100,10 @@
 import Data.Bytes.Put (MonadPut, putByteString, putWord32le, putWord64le, putWord8, runPutL, runPutS)
 import Data.Bytes.Serial (Serial (..), deserialize, serialize)
 import Data.Foldable (foldl')
-import Data.Maybe (fromMaybe, maybeToList)
+import Data.Maybe (fromMaybe, isJust, maybeToList)
 import Data.Serialize (Serialize (..))
+import Data.Vector (Vector)
+import Data.Vector qualified as V
 import Data.Word (Word32, Word8)
 import GHC.Records (HasField (..))
 import Haskoin.Crypto.Hash
@@ -274,10 +279,8 @@
 --   version in the bits @0xfe@ of its first byte, so an odd version cannot
 --   be expressed, and @0x50@ would read as an annex.
 --
--- 'taprootOutputKey' and 'taprootScriptOutput' do not make this check: the
--- output of such a tree is well defined, and its other leaves and its key
--- path can still be spent. Check a tree with this function before you give
--- out its address, since a leaf it refuses can never be spent.
+-- 'taprootOutputKey' and 'taprootScriptOutput' make this check, and give
+-- no output for a tree that it refuses.
 checkTapTree :: MAST -> Either String ()
 checkTapTree = go (0 :: Int)
   where
@@ -353,27 +356,34 @@
 -- hash of the internal key and the root of the tree. The parity of its y
 -- coordinate is the one a control block of a script path spend carries.
 --
--- Two things this function does not do:
+-- It gives no key, with the reason, in two cases:
 --
--- * It does not look at the shape of the tree. A leaf deeper than 128, or
---   with a leaf version a control block cannot carry, gets an output like
---   any other and can never be spent. Run 'checkTapTree' on the tree first.
--- * It calls 'error' when the tweak is not below the order of the curve or
---   gives the point at infinity, which BIP 341 defines as a failure. The
---   tweak is a SHA256 output, so this happens for about one tree in 2^128,
---   and no input is known that reaches it. 'taprootOutputSecKey' returns
---   'Nothing' in the same case.
+-- * 'checkTapTree' refuses the tree: a leaf is deeper than 128, or has a
+--   leaf version that a control block cannot carry. Coins paid to that leaf
+--   alone could never be spent, so no output is made for it. Bitcoin Core
+--   builds no output for a tree deeper than 128 either (@TaprootBuilder@).
+--   The functions gave an output for any tree up to version 2.0.1, and left
+--   the check to the caller.
+-- * The tweak is not below the order of the curve or gives the point at
+--   infinity, which BIP 341 defines as a failure. The tweak is a SHA256
+--   output, so this happens for about one tree in 2^128, and no input is
+--   known that reaches it. 'taprootOutputSecKey' returns 'Nothing' in the
+--   same case.
 --
+-- To recognise a coin that someone else paid to such a tree, or to spend
+-- it by its key path, give the root of the tree in place of the tree:
+-- @MASTCommitment (mastCommitment tree)@. A commitment is not looked into.
+--
 -- @since 0.21.0
-taprootOutputKey :: TaprootOutput -> PubKey
-taprootOutputKey TaprootOutput {..} =
-  fromMaybe keyFail $
+taprootOutputKey :: TaprootOutput -> Either String PubKey
+taprootOutputKey TaprootOutput {..} = do
+  mapM_ checkTapTree mast
+  maybe (Left "taprootOutputKey: the tweak gives no key") Right $
     tweak commitment >>= tweakAddXOnlyPubKey internalKey
   where
     commitment =
       taprootCommitment internalKey $
         mastCommitment <$> mast
-    keyFail = error "haskoin-core taprootOutputKey: key derivation failed"
 
 -- | The secret key that signs a key path spend of the output of the secret
 -- key given: the secret key, negated when its public key has an odd y
@@ -396,17 +406,12 @@
     $ initTaggedHash "TapTweak"
 
 -- | The output script of a Taproot output: witness version 1 and the
--- x-only output key of 'taprootOutputKey', whose two caveats apply here
--- too. Check a script tree with 'checkTapTree' before you pay to it.
+-- x-only output key of 'taprootOutputKey', which gives no key for a tree
+-- that 'checkTapTree' refuses.
 --
 -- @since 0.21.0
-taprootScriptOutput :: TaprootOutput -> ScriptOutput
-taprootScriptOutput =
-  PayWitness 0x01
-    . runPutS
-    . serialize
-    . XOnlyPubKey
-    . taprootOutputKey
+taprootScriptOutput :: TaprootOutput -> Either String ScriptOutput
+taprootScriptOutput = fmap (PayWitness 0x01 . runPutS . serialize . XOnlyPubKey) . taprootOutputKey
 
 {- Witnesses -}
 
@@ -680,6 +685,13 @@
 -- output at the index of the input, or when the annex is empty or does not
 -- start with @0x50@: no node takes such an item for an annex, so no node
 -- computes that digest.
+--
+-- This is the function for one digest. It hashes every input and every
+-- output of the transaction, so a caller that needs the digest of each
+-- input, or several digests of one input, takes the hashes once with
+-- 'taprootTxHashes' and each digest with 'taprootSigHashWith'. With this
+-- function the time for all the inputs grows with the square of their
+-- number.
 taprootSigHash ::
   -- | transaction to sign
   Tx ->
@@ -696,30 +708,109 @@
   Maybe (Digest SHA256, Word32) ->
   Either String Hash256
 taprootSigHash tx spent i sh annexM leafM = do
-  unless (i >= 0 && i < length tx.inputs) $
-    Left "taprootSigHash: input index out of range"
+  -- A wrong index is told before a wrong number of spent outputs
+  unless (i >= 0 && i < length tx.inputs) $ Left indexOutOfRange
+  hashes <- taprootTxHashes tx spent
+  taprootSigHashWith hashes i sh annexM leafM
+
+indexOutOfRange :: String
+indexOutOfRange = "taprootSigHash: input index out of range"
+
+-- | What the Taproot digests of one transaction share: the transaction,
+-- the output that each of its inputs spends, and the five hashes of BIP 341
+-- that are the same for every input (@sha_prevouts@, @sha_amounts@,
+-- @sha_scriptpubkeys@, @sha_sequences@ and @sha_outputs@).
+--
+-- BIP 341 says of these hashes that they "may be cached across signatures
+-- of the same transaction", and Bitcoin Core computes them once for a
+-- transaction (@PrecomputedTransactionData@). They cover every input and
+-- every output, so a digest that computes them again takes time by the
+-- size of the transaction, and the digests of all the inputs by its
+-- square. With a value of this type, a digest takes time by the size of
+-- its own input.
+--
+-- Make it with 'taprootTxHashes', which is the only way, so that it always
+-- holds one spent output for each input. A hash is computed when the first
+-- digest needs it: one with @SIGHASH_ANYONECANPAY@ needs none of the four
+-- over the inputs, and one with @SIGHASH_NONE@ or @SIGHASH_SINGLE@ does not
+-- need the one over the outputs.
+--
+-- The digest does not commit to the input scripts nor to the witnesses, so
+-- the value stays right while the inputs of the transaction are signed.
+-- After any other change of the transaction or of a spent output, make it
+-- again.
+data TaprootTxHashes = TaprootTxHashes
+  { version :: !Word32,
+    locktime :: !Word32,
+    -- | each input with the output it spends
+    inputs :: !(Vector (TxIn, TxOut)),
+    outputs :: !(Vector TxOut),
+    shaPrevouts :: Hash256,
+    shaAmounts :: Hash256,
+    shaScriptPubKeys :: Hash256,
+    shaSequences :: Hash256,
+    shaOutputs :: Hash256
+  }
+
+-- | The hashes that the Taproot digests of a transaction share, from the
+-- transaction and the outputs that its inputs spend, one per input and in
+-- their order. Fails when the spent outputs do not match the inputs.
+taprootTxHashes :: Tx -> [TxOut] -> Either String TaprootTxHashes
+taprootTxHashes tx spent = do
   unless (length spent == length tx.inputs) $
     Left "taprootSigHash: one spent output per input is required"
+  return
+    TaprootTxHashes
+      { version = tx.version,
+        locktime = tx.locktime,
+        inputs = V.fromList (zip tx.inputs spent),
+        outputs = V.fromList tx.outputs,
+        shaPrevouts = hashOf (mapM_ (serialize . (.outpoint)) tx.inputs),
+        shaAmounts = hashOf (mapM_ (putWord64le . (.value)) spent),
+        shaScriptPubKeys = hashOf (mapM_ (putVarIntBytes . (.script)) spent),
+        shaSequences = hashOf (mapM_ (putWord32le . (.sequence)) tx.inputs),
+        shaOutputs = hashOf (mapM_ serialize tx.outputs)
+      }
+  where
+    hashOf = sha256 . runPutS
+
+-- | The digest of 'taprootSigHash' for one input, from the hashes that the
+-- inputs of the transaction share. It gives the digest that
+-- 'taprootSigHash' gives for the transaction and the spent outputs of
+-- 'taprootTxHashes', and fails as it does.
+taprootSigHashWith ::
+  TaprootTxHashes ->
+  -- | index of input being signed
+  Int ->
+  -- | what to sign
+  SigHash ->
+  -- | annex of the input, if there is one, with its @0x50@ prefix
+  Maybe ByteString ->
+  -- | for a script path spend: the leaf hash, and the position of the last
+  -- @OP_CODESEPARATOR@ executed, @0xffffffff@ for none
+  Maybe (Digest SHA256, Word32) ->
+  Either String Hash256
+taprootSigHashWith hashes i sh annexM leafM = do
+  (input, coin) <- maybe (Left indexOutOfRange) Right (hashes.inputs V.!? i)
   unless (isTaprootSigHash sh) $
     Left ("taprootSigHash: invalid hash type " <> show (fromIntegral sh :: Word32))
-  when (isSigHashSingle sh && i >= length tx.outputs) $
-    Left "taprootSigHash: SIGHASH_SINGLE without an output at the input index"
+  -- The output that SIGHASH_SINGLE signs
+  ownOutput <-
+    if isSigHashSingle sh
+      then maybe (Left noOutput) (Right . Just) (hashes.outputs V.!? i)
+      else Right Nothing
   forM_ annexM $ \annex ->
     unless (isAnnex annex) $ Left "taprootSigHash: an annex starts with 0x50"
   return . taggedHash "TapSighash" . runPutS $ do
     putWord8 0x00 -- the epoch
     putWord8 (fromIntegral sh)
-    putWord32le tx.version
-    putWord32le tx.locktime
-    unless (anyoneCanPay sh) $ do
-      serialize $ sha256 (runPutS (mapM_ (serialize . (.outpoint)) tx.inputs))
-      serialize $ sha256 (runPutS (mapM_ (putWord64le . (.value)) spent))
-      serialize $ sha256 (runPutS (mapM_ (putVarIntBytes . (.script)) spent))
-      serialize $ sha256 (runPutS (mapM_ (putWord32le . (.sequence)) tx.inputs))
+    putWord32le hashes.version
+    putWord32le hashes.locktime
+    unless (anyoneCanPay sh) $
+      mapM_ serialize [hashes.shaPrevouts, hashes.shaAmounts, hashes.shaScriptPubKeys, hashes.shaSequences]
     unless (isSigHashNone sh || isSigHashSingle sh) $
-      serialize $
-        sha256 (runPutS (mapM_ serialize tx.outputs))
-    putWord8 (bool 0 2 (isJust' leafM) .|. bool 0 1 (isJust' annexM))
+      serialize hashes.shaOutputs
+    putWord8 (bool 0 2 (isJust leafM) .|. bool 0 1 (isJust annexM))
     if anyoneCanPay sh
       then do
         serialize input.outpoint
@@ -729,17 +820,14 @@
       else putWord32le (fromIntegral i)
     forM_ annexM $ \annex ->
       serialize $ sha256 (runPutS (putVarIntBytes annex))
-    when (isSigHashSingle sh) $
-      serialize $
-        sha256 (runPutS (serialize (tx.outputs !! i)))
+    forM_ ownOutput $ \output ->
+      serialize $ sha256 (runPutS (serialize output))
     forM_ leafM $ \(leaf, codeSeparatorPosition) -> do
       putByteString (BA.convert leaf)
       putWord8 0x00 -- the key version
       putWord32le codeSeparatorPosition
   where
-    input = tx.inputs !! i
-    coin = spent !! i
-    isJust' = maybe False (const True)
+    noOutput = "taprootSigHash: SIGHASH_SINGLE without an output at the input index"
 
 -- | The tagged hash of BIP 340: SHA256 of the hash of the tag twice, then
 -- the message
diff --git a/src/Haskoin/Util/Arbitrary.hs b/src/Haskoin/Util/Arbitrary.hs
--- a/src/Haskoin/Util/Arbitrary.hs
+++ b/src/Haskoin/Util/Arbitrary.hs
@@ -19,5 +19,6 @@
 import Haskoin.Util.Arbitrary.Message as X
 import Haskoin.Util.Arbitrary.Network as X
 import Haskoin.Util.Arbitrary.Script as X
+import Haskoin.Util.Arbitrary.Spelling as X
 import Haskoin.Util.Arbitrary.Transaction as X
 import Haskoin.Util.Arbitrary.Util as X
diff --git a/src/Haskoin/Util/Arbitrary/Script.hs b/src/Haskoin/Util/Arbitrary/Script.hs
--- a/src/Haskoin/Util/Arbitrary/Script.hs
+++ b/src/Haskoin/Util/Arbitrary/Script.hs
@@ -176,6 +176,29 @@
       return OP_CHECKDATASIGVERIFY,
       -- Bitcoin Cash May 2020 hard fork
       return OP_REVERSEBYTES,
+      -- Bitcoin Cash May 2022 and May 2023 hard forks
+      return OP_INPUTINDEX,
+      return OP_ACTIVEBYTECODE,
+      return OP_TXVERSION,
+      return OP_TXINPUTCOUNT,
+      return OP_TXOUTPUTCOUNT,
+      return OP_TXLOCKTIME,
+      return OP_UTXOVALUE,
+      return OP_UTXOBYTECODE,
+      return OP_OUTPOINTTXHASH,
+      return OP_OUTPOINTINDEX,
+      return OP_INPUTBYTECODE,
+      return OP_INPUTSEQUENCENUMBER,
+      return OP_OUTPUTVALUE,
+      return OP_OUTPUTBYTECODE,
+      return OP_UTXOTOKENCATEGORY,
+      return OP_UTXOTOKENCOMMITMENT,
+      return OP_UTXOTOKENAMOUNT,
+      return OP_OUTPUTTOKENCATEGORY,
+      return OP_OUTPUTTOKENCOMMITMENT,
+      return OP_OUTPUTTOKENAMOUNT,
+      return OP_RESERVED3,
+      return OP_RESERVED4,
       -- Other
       return OP_PUBKEYHASH,
       return OP_PUBKEY,
@@ -523,3 +546,29 @@
       sigs <- map lst3 <$> vectorOf m (arbitraryTxSignature net)
       return $ ScriptHashInput (SpendMulSig sigs) rdm
     _ -> undefined
+
+-- | Arbitrary valid t'TokenData'. The amounts cover every size of compact
+-- number up to 'maxTokenAmount', and the commitments every length up to 300
+-- bytes, so that both the short and the three-byte length are written.
+arbitraryTokenData :: Gen TokenData
+arbitraryTokenData = do
+  category <- TxHash <$> arbitraryHash256
+  nft <- arbitraryMaybe arbitraryNFToken
+  let amounts =
+        [ choose (1, 0xfc),
+          choose (0xfd, 0xffff),
+          choose (0x10000, 0xffffffff),
+          choose (0x100000000, maxTokenAmount)
+        ]
+  amount <- case nft of
+    Nothing -> oneof amounts
+    Just _ -> oneof (return 0 : amounts)
+  return TokenData {category = category, amount = amount, nft = nft}
+
+-- | Arbitrary t'NFToken', with or without a commitment.
+arbitraryNFToken :: Gen NFToken
+arbitraryNFToken = do
+  capability <- arbitraryBoundedEnum
+  len <- frequency [(1, return 0), (4, choose (1, 40)), (1, choose (41, 300))]
+  commitment <- B.pack <$> vectorOf len arbitrary
+  return NFToken {capability = capability, commitment = commitment}
diff --git a/src/Haskoin/Util/Arbitrary/Spelling.hs b/src/Haskoin/Util/Arbitrary/Spelling.hs
new file mode 100644
--- /dev/null
+++ b/src/Haskoin/Util/Arbitrary/Spelling.hs
@@ -0,0 +1,329 @@
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE NamedFieldPuns #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- |
+-- Module      : Haskoin.Util.Arbitrary.Spelling
+-- Copyright   : No rights reserved
+-- License     : MIT
+-- Maintainer  : jprupp@protonmail.ch
+-- Stability   : experimental
+-- Portability : POSIX
+--
+-- Signed transactions with one input written in another way than a signer
+-- writes it, to test a verifier.
+--
+-- The other generators of this library hand a verifier what 'signTx'
+-- writes: every push the shortest one, every S low, every key compressed
+-- or uncompressed, every script the one 'encodeOutput' writes. A verifier
+-- that is wrong about any other form passes all the tests made from them.
+-- The same spend can be written in other bytes with every signature still
+-- good, and what a node does with it then depends on the form and on the
+-- network: it relays it, it takes it in a block only, or no block can hold
+-- it. Anyone can make most of these forms from a spend seen on the
+-- network, without a key. So a verifier that looks at the signatures alone
+-- says yes to a transaction that a node refuses, and a node of Bitcoin
+-- Cash drops the peer that sends one.
+--
+-- 'arbitraryRespelled' makes such a transaction for one 'Spelling'. Each
+-- constructor says what the nodes of each network do with it, which is
+-- what a test expects of the verifier. Every signature in the transaction
+-- is good: a verifier never has a reason to call an input forged.
+--
+-- These are not all the forms that a node refuses. A size limit, such as
+-- the 999 keys of a Taproot multisig, is not a spelling, and has tests of
+-- its own.
+module Haskoin.Util.Arbitrary.Spelling
+  ( Spelling (..),
+    Respelled (..),
+    arbitraryRespelled,
+  )
+where
+
+import Control.Applicative ((<|>))
+import Crypto.Secp256k1
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as B
+import Data.Bytes.Get (runGetS)
+import Data.Bytes.Put (runPutS)
+import Data.Bytes.Serial (deserialize, serialize)
+import Data.Maybe (fromMaybe)
+import Haskoin.Crypto.Hash (addressHash)
+import Haskoin.Crypto.Keys.Common
+import Haskoin.Crypto.Signature (decodeStrictSig)
+import Haskoin.Network.Data
+import Haskoin.Script
+import Haskoin.Transaction.Builder.Sign
+import Haskoin.Transaction.Common
+import Haskoin.Transaction.Segwit (isSegwit)
+import Haskoin.Util
+import Haskoin.Util.Arbitrary.Keys
+import Haskoin.Util.Arbitrary.Transaction
+import Test.QuickCheck
+
+-- | A way to write an input other than the way of 'signTx', with every
+-- signature still good.
+--
+-- On Bitcoin three of the rules below belong to the relay policy: a block
+-- may hold the input, and nodes do not relay it. Bitcoin Cash applies the
+-- same three to every block (@MANDATORY_SCRIPT_VERIFY_FLAGS@ of Bitcoin
+-- Cash Node).
+data Spelling
+  = -- | An item of the input script is pushed by @OP_PUSHDATA1@, @2@ or
+    -- @4@ where a shorter push holds it. The coin is not a witness program.
+    -- This is the @MINIMALDATA@ rule: relay policy on Bitcoin, every block
+    -- on Bitcoin Cash.
+    LongPush
+  | -- | The witness program of a SegWit input nested in a script hash is
+    -- pushed by @OP_PUSHDATA1@, @2@ or @4@. No block holds it: BIP 141
+    -- wants the input script to be exactly the push of the program. Only a
+    -- network with SegWit has this spelling.
+    LongProgramPush
+  | -- | An ECDSA signature has the order of the curve less S in place of
+    -- S. Both verify. This is the @LOW_S@ rule: relay policy on Bitcoin,
+    -- every block on Bitcoin Cash.
+    HighS
+  | -- | The coin is locked to the hash of a key in the hybrid form, 65
+    -- bytes that start with 0x06 or 0x07, and the input shows that key. The
+    -- coin is a key hash or, on a network with SegWit, a witness key hash.
+    -- This is the @STRICTENC@ rule: relay policy on Bitcoin, every block on
+    -- Bitcoin Cash.
+    HybridKey
+  | -- | A SegWit version 0 coin is locked to the hash of an uncompressed
+    -- key, and the input shows that key. A block may hold it, and nodes do
+    -- not relay it (@WITNESS_PUBKEYTYPE@). 'signTx' refuses to make it.
+    -- Only a network with SegWit has this spelling.
+    UncompressedKey
+  | -- | The input shows its redeem script or its witness script with a
+    -- longer push in it: the same keys in other bytes, with another hash
+    -- than the one that the coin holds. No block holds it (BIP 16, BIP
+    -- 141).
+    UncommittedScript
+  | -- | The coin is locked to a script with a longer push in it, a key, a
+    -- key hash or a multisig, and not to the hash of one. The signatures
+    -- cover the script with the shortest pushes, which is what a decoder
+    -- that forgets the form of a push hands to a verifier. No block holds
+    -- it: a signature covers the bytes of the script of its coin.
+    UnsignedScript
+  deriving (Eq, Show, Enum, Bounded)
+
+-- | A signed transaction with one input in another spelling. The other
+-- inputs are as 'signTx' wrote them: a node takes each of them.
+data Respelled = Respelled
+  { -- | the transaction
+    tx :: Tx,
+    -- | the output that each input spends, in order
+    coins :: [TxOut],
+    -- | which input is in the other spelling
+    index :: Int
+  }
+  deriving (Eq, Show)
+
+-- | Arbitrary signed transaction of one to four inputs, one of them in the
+-- spelling asked for, with the outputs that it spends. A SegWit input is
+-- native or nested in a script hash. The outputs of the transaction spend
+-- no more than its coins hold.
+--
+-- The call is an error for a spelling that the network does not have: see
+-- 'Spelling'.
+arbitraryRespelled :: Network -> Spelling -> Gen Respelled
+arbitraryRespelled net spelling = do
+  made <- recipe net spelling
+  others <- resize 3 (listOf other)
+  (unsigned, sigis, keys) <- arbitrarySigningDataOf net (made.coin : others)
+  nestings <- vectorOf (length sigis) arbitrary
+  let goal = (fst made.coin).outpoint
+      spent =
+        [ (s, isSegwit s.script && (if s.outpoint == goal then made.nested else n))
+        | (s, n) <- zip sigis nestings
+        ]
+      signed = orError (signTx net unsigned spent (map (.key) keys))
+      outputs = [(s.outpoint, spentOutput s n) | (s, n) <- spent]
+      coins = [coin | input <- signed.inputs, Just coin <- [lookup input.outpoint outputs]]
+      index = length (takeWhile ((/= goal) . (.outpoint)) signed.inputs)
+  made.change Respelled {tx = signed, coins, index}
+  where
+    -- A Taproot signature covers the script of every coin spent, so it
+    -- would not stand a coin whose script changes after the signing
+    other
+      | spelling == UnsignedScript = arbitrarySigInput net `suchThat` (not . isTaprootKey . (.script) . fst)
+      | otherwise = arbitrarySigInput net
+    isTaprootKey = \case
+      PayWitness 1 _ -> True
+      _ -> False
+
+-- | The output that a coin of the signer is on the chain: a nested SegWit
+-- program is locked to the hash of the program.
+spentOutput :: SigInput -> Bool -> TxOut
+spentOutput s nested
+  | nested = TxOut s.value (encodeSerial (orError (toP2SH =<< encodeOutput s.script)))
+  | otherwise = TxOut s.value (encodeSerial s.script)
+
+-- | How a spelling is made.
+data Recipe = Recipe
+  { -- | the coin to respell, with the keys that 'signTx' gets for it: none
+    -- for a coin that 'signTx' does not sign, which the change signs
+    coin :: (SigInput, [PrivateKey]),
+    -- | whether a SegWit coin is nested in a script hash
+    nested :: Bool,
+    -- | what to change in the transaction once 'signTx' has signed it
+    change :: Respelled -> Gen Respelled
+  }
+
+recipe :: Network -> Spelling -> Gen Recipe
+recipe net = \case
+  LongPush ->
+    Recipe <$> arbitraryLegacySigInput net <*> pure False <*> pure (onInputScript longerPush)
+  LongProgramPush ->
+    Recipe <$> witness <*> pure True <*> pure (onInputScript longerPush)
+  HighS ->
+    Recipe <$> oneof (arbitraryLegacySigInput net : [witness | net.segWit]) <*> arbitrary <*> pure (return . withHighS)
+  HybridKey -> do
+    secret <- arbitraryPrivateKey
+    let shown = hybridKey (derivePubKey secret.key)
+    coin <- keyHashCoin (PayPKHash (addressHash shown) : [PayWitnessPKHash (addressHash shown) | net.segWit])
+    return (Recipe (coin, []) False (return . signedShowing net coin secret shown))
+  UncompressedKey -> do
+    secret <- (\k -> wrapSecKey False k.key) <$> arbitraryPrivateKey
+    coin <- keyHashCoin [PayWitnessPKHash (addressHash (encodeSerial (derivePublicKey secret))) | net.segWit]
+    nested <- arbitrary
+    return (Recipe (coin, []) nested (return . signedBy net (coin, nested) secret))
+  UncommittedScript ->
+    Recipe
+      <$> oneof (arbitrarySHSigInput net : [arbitraryWSHSigInput net | net.segWit])
+      <*> arbitrary
+      <*> pure (onShownScript longerPush)
+  UnsignedScript ->
+    Recipe
+      <$> oneof [wrapKey <$> arbitraryPKSigInput net, wrapKey <$> arbitraryPKHashSigInput net, bareMultisig]
+      <*> pure False
+      <*> pure (onCoinScript longerPush)
+  where
+    bareMultisig = arbitraryMSSigInput net
+    witness
+      | net.segWit = arbitraryWitnessSigInput net
+      | otherwise = error "arbitraryRespelled: this network has no SegWit"
+    keyHashCoin [] = error "arbitraryRespelled: this network has no SegWit"
+    keyHashCoin scripts = do
+      script <- elements scripts
+      (value, outpoint, sighash) <- arbitraryInputStuff net
+      return SigInput {script, value, outpoint, sighash, redeem = Nothing}
+
+-- | The script with one of its pushes of data written by a longer opcode
+-- than the data needs: @OP_PUSHDATA1@, @2@ or @4@ for a direct push, and so
+-- on.
+longerPush :: ByteString -> Gen ByteString
+longerPush script = do
+  (n, op) <- elements [(n, OP_PUSHDATA d longer) | (n, OP_PUSHDATA d t) <- zip [0 ..] ops, longer <- longerThan t]
+  return (scriptBytes (updateIndex n ops (const op)))
+  where
+    ops = scriptOps script
+    longerThan = \case
+      OPCODE -> [OPDATA1, OPDATA2, OPDATA4]
+      OPDATA1 -> [OPDATA2, OPDATA4]
+      OPDATA2 -> [OPDATA4]
+      OPDATA4 -> []
+
+-- | An ECDSA signature and its hash type byte, with the order of the curve
+-- less S in place of S. Nothing for an item that is not such a signature.
+highS :: ByteString -> Maybe ByteString
+highS item = do
+  (der, hashType) <- B.unsnoc item
+  (r, s) <- B.splitAt 32 . (.get) . exportCompactSig <$> decodeStrictSig der
+  let order = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 :: Integer
+      other = integerToBS (order - bsToInteger s)
+  flipped <- importCompactSig =<< compactSig (r <> B.replicate (32 - B.length other) 0 <> other)
+  return (exportSig flipped `B.snoc` hashType)
+
+-- | The input with a high S in its first signature, which is in its input
+-- script or in its witness. The signature is pushed by the shortest push.
+withHighS :: Respelled -> Respelled
+withHighS r = fromMaybe (error "arbitraryRespelled: no ECDSA signature") (inScript <|> inWitness)
+  where
+    inScript = (\ops -> withInputScript (scriptBytes ops) r) <$> changeFirst pushed (scriptOps (inputScript r))
+    inWitness = (`withWitness` r) <$> changeFirst highS (witnessOf r)
+    pushed = \case
+      OP_PUSHDATA d _ -> opPushData <$> highS d
+      _ -> Nothing
+
+-- | The 65 bytes of a key in the hybrid form: both coordinates, after 0x06
+-- when y is even and 0x07 when it is odd.
+hybridKey :: PubKey -> ByteString
+hybridKey point = B.cons (if even (B.last full) then 0x06 else 0x07) (B.drop 1 full)
+  where
+    full = exportPubKey False point
+
+-- | The input signed by a key, and showing these bytes as that key. The
+-- coin is a key hash or a witness key hash.
+signedShowing :: Network -> SigInput -> PrivateKey -> ByteString -> Respelled -> Respelled
+signedShowing net coin secret shown r
+  | isSegwit coin.script = withWitness [signature, shown] r
+  | otherwise = withInputScript (scriptBytes (map opPushData [signature, shown])) r
+  where
+    signature = encodeTxSig net (orError (makeSignature net r.tx r.index coin secret))
+
+-- | The input signed by 'signInput', which signs with the key in the form
+-- that it is given.
+signedBy :: Network -> (SigInput, Bool) -> PrivateKey -> Respelled -> Respelled
+signedBy net coin secret r = r {tx = orError (signInput net r.tx r.index coin secret)}
+
+-- | Change the first element that the function changes.
+changeFirst :: (a -> Maybe a) -> [a] -> Maybe [a]
+changeFirst change = \case
+  [] -> Nothing
+  x : xs -> ((: xs) <$> change x) <|> ((x :) <$> changeFirst change xs)
+
+-- | Change the input script of the respelled input.
+onInputScript :: (ByteString -> Gen ByteString) -> Respelled -> Gen Respelled
+onInputScript change r = (`withInputScript` r) <$> change (inputScript r)
+
+-- | Change the script that the respelled input shows: its witness script,
+-- the last item of its witness, or else its redeem script, the last push of
+-- its input script. The redeem script is pushed by the shortest push.
+onShownScript :: (ByteString -> Gen ByteString) -> Respelled -> Gen Respelled
+onShownScript change r = case (reverse (witnessOf r), reverse (scriptOps (inputScript r))) of
+  (script : below, _) ->
+    (\s -> withWitness (reverse (s : below)) r) <$> change script
+  ([], OP_PUSHDATA script _ : below) ->
+    (\s -> withInputScript (scriptBytes (reverse (opPushData s : below))) r) <$> change script
+  _ -> error "arbitraryRespelled: the input shows no script"
+
+-- | Change the script of the coin that the respelled input spends.
+onCoinScript :: (ByteString -> Gen ByteString) -> Respelled -> Gen Respelled
+onCoinScript change r = do
+  script <- change (r.coins !! r.index).script
+  return (r {coins = updateIndex r.index r.coins (\coin -> TxOut coin.value script)} :: Respelled)
+
+inputScript :: Respelled -> ByteString
+inputScript r = (r.tx.inputs !! r.index).script
+
+withInputScript :: ByteString -> Respelled -> Respelled
+withInputScript script r = r {tx = r.tx {inputs = updateIndex r.index r.tx.inputs change}}
+  where
+    change :: TxIn -> TxIn
+    change input = TxIn input.outpoint script input.sequence
+
+-- | The witness of the respelled input: no item when it has none.
+witnessOf :: Respelled -> WitnessStack
+witnessOf r = concat (take 1 (drop r.index r.tx.witness))
+
+withWitness :: WitnessStack -> Respelled -> Respelled
+withWitness items r = r {tx = r.tx {witness = updateIndex r.index stacks (const items)}}
+  where
+    -- A transaction without a witness has no stack at all
+    stacks
+      | null r.tx.witness = map (const []) r.tx.inputs
+      | otherwise = r.tx.witness
+
+scriptOps :: ByteString -> [ScriptOp]
+scriptOps bytes = (orError (runGetS deserialize bytes) :: Script).ops
+
+scriptBytes :: [ScriptOp] -> ByteString
+scriptBytes = runPutS . serialize . Script
+
+-- | The generators only take apart what the signer just made.
+orError :: Either String a -> a
+orError = either (error . ("arbitraryRespelled: " <>)) id
diff --git a/src/Haskoin/Util/Arbitrary/Transaction.hs b/src/Haskoin/Util/Arbitrary/Transaction.hs
--- a/src/Haskoin/Util/Arbitrary/Transaction.hs
+++ b/src/Haskoin/Util/Arbitrary/Transaction.hs
@@ -189,19 +189,34 @@
 arbitrarySigInput :: Network -> Gen (SigInput, [PrivateKey])
 arbitrarySigInput net =
   oneof $
-    [ wrapKey <$> arbitraryPKSigInput net,
-      wrapKey <$> arbitraryPKHashSigInput net,
-      arbitraryMSSigInput net,
-      arbitrarySHSigInput net
-    ]
-      <> concat
-        [ [ wrapKey <$> arbitraryWPKHSigInput net,
-            arbitraryWSHSigInput net,
-            wrapKey <$> arbitraryTaprootSigInput net
-          ]
-        | net.segWit
-        ]
+    legacySigInputs net
+      <> concat [witnessSigInputs net <> [wrapKey <$> arbitraryTaprootSigInput net] | net.segWit]
 
+-- | Arbitrary 'SigInput' of a coin that is not a witness program: locked to
+-- a key, to a key hash, to a multisig script, or to the hash of one of
+-- those scripts.
+arbitraryLegacySigInput :: Network -> Gen (SigInput, [PrivateKey])
+arbitraryLegacySigInput = oneof . legacySigInputs
+
+-- | Arbitrary 'SigInput' of a SegWit version 0 coin: a witness key hash or
+-- a witness script hash. Only a network with SegWit has such coins.
+arbitraryWitnessSigInput :: Network -> Gen (SigInput, [PrivateKey])
+arbitraryWitnessSigInput = oneof . witnessSigInputs
+
+legacySigInputs :: Network -> [Gen (SigInput, [PrivateKey])]
+legacySigInputs net =
+  [ wrapKey <$> arbitraryPKSigInput net,
+    wrapKey <$> arbitraryPKHashSigInput net,
+    arbitraryMSSigInput net,
+    arbitrarySHSigInput net
+  ]
+
+witnessSigInputs :: Network -> [Gen (SigInput, [PrivateKey])]
+witnessSigInputs net =
+  [ wrapKey <$> arbitraryWPKHSigInput net,
+    arbitraryWSHSigInput net
+  ]
+
 -- | Arbitrary 'SigInput' of a Taproot output without a script tree, spent
 -- by its key path with the key of the internal key, as a wallet of BIP 86
 -- spends. The sighash is one a Taproot signature may use, other than
@@ -212,7 +227,8 @@
   val <- getTestCoin <$> arbitrarySatoshi net
   op <- arbitraryOutPoint
   sh <- elements [sigHashDefault, sigHashAll, sigHashNone, setAnyoneCanPay sigHashAll, setAnyoneCanPay sigHashNone]
-  let out = taprootScriptOutput (TaprootOutput p.point Nothing)
+  -- An output without a script tree: no tree is refused
+  let out = either error id (taprootScriptOutput (TaprootOutput p.point Nothing))
   return (SigInput out val op sh Nothing, k)
 
 -- | Arbitrary 'SigInput' with a 'ScriptOutput' of type 'PayPK'.
@@ -321,13 +337,19 @@
 -- spend no more than the inputs hold.
 arbitrarySigningData :: Network -> Gen (Tx, [SigInput], [PrivateKey])
 arbitrarySigningData net = do
-  v <- arbitrary
   ni <- choose (1, 5)
-  sigis <- vectorOf ni (arbitrarySigInput net)
+  arbitrarySigningDataOf net =<< vectorOf ni (arbitrarySigInput net)
+
+-- | 'arbitrarySigningData' for these coins and their keys, to choose what
+-- the transaction spends. Of two coins with the same outpoint, the first is
+-- kept. The inputs of the transaction are in an arbitrary order.
+arbitrarySigningDataOf :: Network -> [(SigInput, [PrivateKey])] -> Gen (Tx, [SigInput], [PrivateKey])
+arbitrarySigningDataOf net sigis = do
+  v <- arbitrary
   let uSigis = nubBy (\(a, _) (b, _) -> a.outpoint == b.outpoint) sigis
-  -- The signer refuses SIGHASH_SINGLE on a legacy input without an output
-  -- at its index, so every input gets an output when one asks for it
-  no <- choose (if any (legacySingle net . fst) uSigis then length uSigis else 1, 5)
+  -- The signer refuses SIGHASH_SINGLE on an input without an output at
+  -- its index, so every input gets an output when one asks for it
+  no <- choose (if any (isSigHashSingle . (.sighash) . fst) uSigis then length uSigis else 1, 5)
   inps <- forM uSigis $ \(s, _) -> TxIn s.outpoint BS.empty <$> arbitrary
   outs <- arbitraryOutputsWithin net (sum (map ((.value) . fst) uSigis)) no
   l <- arbitrary
@@ -338,7 +360,9 @@
 
 -- | Whether the input is to be signed with SIGHASH_SINGLE over the legacy
 -- digest, which is the constant 1 when the input has no output at its
--- index. 'makeSignature' refuses to sign that.
+-- index. 'makeSignature' refuses to sign that. 'signTx' refuses
+-- SIGHASH_SINGLE on any input without an output at its index, so the
+-- generators here ask 'isSigHashSingle' alone.
 legacySingle :: Network -> SigInput -> Bool
 legacySingle net si =
   isSigHashSingle si.sighash && not (isSegwit si.script) && isNothing net.sigHashForkId
@@ -379,10 +403,10 @@
   return (concatMap fst res, map snd res)
   where
     singleSig so val rdmM tx op prv = do
-      -- The signer refuses SIGHASH_SINGLE on a legacy input without an
-      -- output at its index
+      -- The signer refuses SIGHASH_SINGLE on an input without an output
+      -- at its index
       let index = fromMaybe 0 (findIndex ((== op) . (.outpoint)) tx.inputs)
-          refused sh = index >= length tx.outputs && legacySingle net (SigInput so val op sh rdmM)
+          refused sh = index >= length tx.outputs && isSigHashSingle sh
       sh <- arbitraryValidSigHash net `suchThat` (not . refused)
       let sigi = SigInput so val op sh rdmM
       return . fromRight (error "Could not decode transaction") $
diff --git a/src/Haskoin/Util/Arbitrary/Util.hs b/src/Haskoin/Util/Arbitrary/Util.hs
--- a/src/Haskoin/Util/Arbitrary/Util.hs
+++ b/src/Haskoin/Util/Arbitrary/Util.hs
@@ -32,7 +32,7 @@
   )
 where
 
-import Control.Monad (forM_, (<=<))
+import Control.Monad (forM_, unless)
 import qualified Data.Aeson as A
 import qualified Data.Aeson.Encoding as A
 import qualified Data.Aeson.Types as A
@@ -173,20 +173,34 @@
     proxy :: Gen a -> Proxy a
     proxy = const Proxy
 
--- | Generate binary identity tests
+-- | Generate binary identity tests: a value that 'serialize' writes must
+-- come back from 'deserialize' as itself, with the strict and the lazy
+-- runners of both. The bytes must hold the value and nothing else, the rule
+-- of 'decodeSerial': a codec that writes a byte that it does not read
+-- fails, since that byte would shift every value after it in a stream.
 testSerial ::
   (Eq a, Show a, T.Typeable a, Serial a) => Gen a -> Spec
 testSerial gen =
   prop ("Binary encoding/decoding identity for " <> name) $
     forAll gen $ \x -> do
-      (runGetL deserialize . runPutL . serialize) x `shouldBe` x
-      (runGetL deserialize . fromStrict . runPutS . serialize) x `shouldBe` x
-      (runGetS deserialize . runPutS . serialize) x `shouldBe` Right x
-      (runGetS deserialize . toStrict . runPutL . serialize) x `shouldBe` Right x
+      (runGetL deserializeAll . runPutL . serialize) x `shouldBe` x
+      (runGetL deserializeAll . fromStrict . runPutS . serialize) x `shouldBe` x
+      (runGetS deserializeAll . runPutS . serialize) x `shouldBe` Right x
+      (runGetS deserializeAll . toStrict . runPutL . serialize) x `shouldBe` Right x
   where
     name = show $ T.typeRep $ proxy gen
     proxy :: Gen a -> Proxy a
     proxy = const Proxy
+
+-- | Read a value and require that the input ends there. It is the reader of
+-- 'decodeSerial' for any monad, so that 'testSerial' can run it with the
+-- strict and the lazy runner.
+deserializeAll :: (MonadGet m, Serial a) => m a
+deserializeAll = do
+  value <- deserialize
+  done <- isEmpty
+  unless done $ fail "testSerial: bytes left over after the value"
+  return value
 
 -- | Generate Marshal identity tests
 testMarshal ::
diff --git a/test/BitcoinCore.hs b/test/BitcoinCore.hs
new file mode 100644
--- /dev/null
+++ b/test/BitcoinCore.hs
@@ -0,0 +1,246 @@
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE TypeApplications #-}
+
+-- | A regtest node of Bitcoin Core for the tests that check the library
+-- against it: Bitcoin Core makes and checks what the library signs, and
+-- the library must combine and finalize what Bitcoin Core does, as Bitcoin
+-- Core does.
+--
+-- The node runs in a rootless Podman container of
+-- [podman-test](https://github.com/jprupp/podman-test), for as long as the
+-- tests of a group: each group of tests that needs a node gets one of its
+-- own, so test processes that run at once never share a node, a port or a
+-- folder. Its RPC port is bridged to a Unix socket of its pod, and the pod
+-- has no network, so the node can reach no peer and nothing else can reach
+-- it.
+--
+-- Without Podman the tests are pending, and say why. Set @PODMAN_TEST_SKIP@
+-- to leave them out on purpose.
+--
+-- This module is part of the test suite only, not of the library: the
+-- library must not depend on podman-test.
+module BitcoinCore
+  ( -- * Running a node
+    Node,
+    aroundNode,
+    coreVersion,
+
+    -- * Calls
+    RpcError (..),
+    rpc,
+    walletRpc,
+    at,
+    textAt,
+  )
+where
+
+import Control.Exception (Exception, SomeException, bracket, throwIO, try)
+import Control.Lens ((^?))
+import Data.Aeson (Value (..), eitherDecodeStrict, encode, object, (.=))
+import Data.Aeson.Key qualified as Key
+import Data.Aeson.Lens (key)
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as B
+import Data.ByteString.Char8 qualified as C
+import Data.ByteString.Lazy qualified as BL
+import Data.Text (Text)
+import Data.Text qualified as T
+import Data.Text.Encoding (encodeUtf8)
+import Network.Socket (Socket, close)
+import Network.Socket.ByteString (recv, sendAll)
+import Test.Hspec (Spec, SpecWith, around, aroundAll, pendingWith, runIO)
+import Test.Podman
+
+-- | A node that runs, and the address of its RPC interface.
+newtype Node = Node Address
+
+-- | Release of Bitcoin Core in the image.
+coreVersion :: String
+coreVersion = "32.1"
+
+-- | Run a group of tests with a node of its own, after a setup that gives
+-- the tests what they need: the node itself, or what the setup made with
+-- it. The node is started before the first test of the group and removed
+-- after the last, however they end. Without Podman, each test is pending,
+-- and says why. Whether Podman can run is asked once, as the tree of tests
+-- is built, which takes a tenth of a second.
+--
+-- The first run on a machine builds the image, which downloads Ubuntu and
+-- Bitcoin Core and takes a minute or two; later runs start a node in a few
+-- seconds.
+aroundNode :: (Node -> IO a) -> SpecWith a -> Spec
+aroundNode setup tests = do
+  usable <- runIO podmanUsable
+  case usable of
+    Left why -> around (\_ -> pendingWith ("Bitcoin Core needs Podman: " <> why)) tests
+    Right () -> aroundAll (\test -> withPod nodePod $ \p -> setup (Node (address p "rpc")) >>= test) tests
+
+-- | The pod of a node: ready once the RPC answers, which Bitcoin Core does
+-- only after it has loaded its chain, some seconds after its port opens.
+nodePod :: PodSpec
+nodePod =
+  (pod "bitcoin-core" [nodeContainer])
+    { ready = [Accepts "rpc", Probe "Bitcoin Core answers RPC calls" answers],
+      readyWithin = 120
+    }
+  where
+    answers p = do
+      r <- try @SomeException (rpc (Node (address p "rpc")) "getblockchaininfo" [])
+      return (either (const False) (const True) r)
+
+-- | The container of a node. Its chain is in memory, it talks to no peer,
+-- and its caches and mempool are small, as a test needs.
+nodeContainer :: ContainerSpec
+nodeContainer =
+  (container "bitcoind" image)
+    { entrypoint = Just "/opt/bitcoin-core/bin/bitcoind",
+      memory = Just "1g",
+      tmpfs = [("/chain", "512m")],
+      command =
+        [ "-regtest",
+          "-datadir=/chain",
+          "-printtoconsole",
+          "-server",
+          "-rpcuser=test",
+          "-rpcpassword=test",
+          "-rpcbind=0.0.0.0",
+          "-rpcallowip=0.0.0.0/0",
+          "-listen=0",
+          "-txindex=1",
+          "-fallbackfee=0.0001",
+          "-dbcache=4",
+          "-maxmempool=5",
+          "-par=1",
+          "-rpcthreads=2"
+        ],
+      endpoints = [Bridged "rpc" 18443]
+    }
+
+-- | The image of the node, built from pinned and checked sources only.
+--
+-- It starts from the official Ubuntu 26.04 image, pinned by the digest of
+-- its index, installs curl from the Ubuntu archive at a fixed snapshot date,
+-- and downloads the release of Bitcoin Core from bitcoincore.org, checked
+-- against the SHA-256 hash pinned here: a tarball that does not match stops
+-- the build. The hashes are those of the @SHA256SUMS@ of the release, whose
+-- signatures by the builders of Bitcoin Core were checked when they were
+-- pinned for the tests of haskoin-store, which use the same base image and
+-- release.
+--
+-- podman-test tags the image with a hash of this recipe, so a new release
+-- or hash builds a new image. To move to a new release, change
+-- 'coreVersion' and the two hashes after checking them the same way.
+image :: Image
+image =
+  Built
+    ImageSpec
+      { name = "haskoin-core-bitcoind",
+        containerfile = C.pack (unlines recipe),
+        files = []
+      }
+  where
+    base =
+      "docker.io/library/ubuntu\
+      \@sha256:6a06111c3b0a8600feadb270aec771dc239bf407b25625f93f44ab00e11f4d3c"
+    snapshot = "20261101T000000Z"
+    amd64 = "61545c17c3120fb7412f896d248b11993af04ec8817aad3649c55b2afb044963"
+    arm64 = "7ed37c7373eb6aa3e3f72842596a1afeba1b223717033cade9842b25773e1922"
+    url =
+      "https://bitcoincore.org/bin/bitcoin-core-"
+        <> coreVersion
+        <> "/bitcoin-"
+        <> coreVersion
+        <> "-$a-linux-gnu.tar.gz"
+    -- The snapshot archive is served over HTTPS only, so its certificates
+    -- come first from the regular archive, whose packages apt checks by
+    -- their signatures.
+    recipe =
+      [ "FROM " <> base,
+        "ARG TARGETARCH",
+        "RUN apt-get update --error-on=any \\",
+        " && apt-get install -y --no-install-recommends ca-certificates \\",
+        " && apt-get update --error-on=any --snapshot " <> snapshot <> " \\",
+        " && apt-get install -y --no-install-recommends --snapshot " <> snapshot <> " ca-certificates curl \\",
+        " && rm -rf /var/lib/apt/lists/*",
+        "RUN set -eu; \\",
+        " case \"$TARGETARCH\" in \\",
+        "  amd64) a=x86_64; h=" <> amd64 <> ";; \\",
+        "  arm64) a=aarch64; h=" <> arm64 <> ";; \\",
+        "  *) echo \"unsupported architecture $TARGETARCH\"; exit 1;; \\",
+        " esac; \\",
+        " curl -fsSL -o /tmp/release.tar.gz \"" <> url <> "\"; \\",
+        " echo \"$h  /tmp/release.tar.gz\" | sha256sum -c -; \\",
+        " mkdir -p /opt/bitcoin-core; \\",
+        " tar -xzf /tmp/release.tar.gz -C /opt/bitcoin-core --strip-components=1; \\",
+        " rm /tmp/release.tar.gz"
+      ]
+
+-- | An error that the node gave for a call: the method, and the error.
+data RpcError = RpcError !Text !Value
+  deriving (Show)
+
+instance Exception RpcError
+
+-- | Call a method of the node, and give its result.
+rpc :: Node -> Text -> [Value] -> IO Value
+rpc node = call node "/"
+
+-- | Call a method of a wallet of the node, and give its result.
+walletRpc :: Node -> Text -> Text -> [Value] -> IO Value
+walletRpc node wallet = call node ("/wallet/" <> wallet)
+
+-- | One JSON-RPC call, as one request of HTTP 1.0 on a connection of its
+-- own: the node answers with the whole body and closes the connection, so
+-- the answer is all that comes back. That is all the HTTP the tests need,
+-- and it needs no client library. The node answers an error with a status
+-- that is not 200 and the error in the body, so only the body is read.
+call :: Node -> Text -> Text -> [Value] -> IO Value
+call (Node addr) path method params = do
+  answer <- bracket (connectTo addr) close $ \s -> do
+    sendAll s request
+    receiveAll s
+  let body = B.drop 4 (snd (B.breakSubstring "\r\n\r\n" answer))
+  case eitherDecodeStrict @Value body of
+    Left e -> fail ("Bitcoin Core gave no JSON for " <> T.unpack method <> ": " <> e)
+    Right v -> case (v ^? key "error", v ^? key "result") of
+      (Just Null, Just r) -> return r
+      (Just e, _) -> throwIO (RpcError method e)
+      _ -> fail ("Bitcoin Core gave no result for " <> T.unpack method)
+  where
+    payload =
+      BL.toStrict . encode $
+        object ["jsonrpc" .= ("1.0" :: Text), "id" .= ("test" :: Text), "method" .= method, "params" .= params]
+    request =
+      mconcat
+        [ "POST " <> encodeUtf8 path <> " HTTP/1.0\r\n",
+          -- test:test, the user and password of the node
+          "Authorization: Basic dGVzdDp0ZXN0\r\n",
+          "Content-Type: application/json\r\n",
+          "Content-Length: " <> C.pack (show (B.length payload)) <> "\r\n",
+          "\r\n",
+          payload
+        ]
+
+-- | All that comes on a connection until the node closes it.
+receiveAll :: Socket -> IO ByteString
+receiveAll s = B.concat <$> go
+  where
+    go =
+      recv s 65536 >>= \case
+        "" -> return []
+        chunk -> (chunk :) <$> go
+
+-- | The field of an object that a call gave, or a failure that names it.
+at :: Text -> Value -> IO Value
+at k v = maybe (fail ("No field " <> T.unpack k <> " in " <> show v)) return (v ^? key (Key.fromText k))
+
+-- | The text field of an object that a call gave.
+textAt :: Text -> Value -> IO Text
+textAt k v =
+  at k v >>= \case
+    String t -> return t
+    other -> fail ("The field " <> T.unpack k <> " is not text: " <> show other)
diff --git a/test/Haskoin/Address/Bech32Spec.hs b/test/Haskoin/Address/Bech32Spec.hs
--- a/test/Haskoin/Address/Bech32Spec.hs
+++ b/test/Haskoin/Address/Bech32Spec.hs
@@ -59,6 +59,18 @@
     it "should not encode long data string" $
       assert . isNothing $
         bech32Encode Bech32 "bc" (replicate 82 (word5 (1 :: Word8)))
+    it "encodes the longest string, of 90 characters" $
+      -- "bc", the separator, 81 words and the checksum of 6: 2 + 1 + 81 + 6 = 90.
+      -- The checksum is from a Python transcription of BIP 173.
+      bech32Encode Bech32 "bc" (replicate 81 (word5 (0 :: Word8)))
+        `shouldBe` Just ("bc1" <> Text.replicate 81 "q" <> "755kml")
+    it "refuses a word after a human-readable part that leaves no room for it" $
+      -- A part of 83 characters, the separator, one word and the checksum
+      -- of 6: 83 + 1 + 1 + 6 = 91
+      bech32Encode Bech32 (Text.replicate 83 "a") [word5 (0 :: Word8)] `shouldBe` Nothing
+    it "refuses a list of words that is too long before it reads it to its end" $
+      bech32Encode Bech32 "bc" (replicate 1000 (word5 (0 :: Word8)) ++ error "the list was read to its end")
+        `shouldBe` Nothing
     it "should not encode bad version number" $
       assert $
         isNothing $
diff --git a/test/Haskoin/Address/CashAddrSpec.hs b/test/Haskoin/Address/CashAddrSpec.hs
--- a/test/Haskoin/Address/CashAddrSpec.hs
+++ b/test/Haskoin/Address/CashAddrSpec.hs
@@ -1,5 +1,6 @@
 {-# LANGUAGE ImportQualifiedPost #-}
 {-# LANGUAGE OverloadedStrings #-}
+{-# OPTIONS_GHC -Wno-deprecations #-}
 
 module Haskoin.Address.CashAddrSpec (spec) where
 
@@ -201,7 +202,7 @@
       cashAddrEncode bch 3 hash32
         `shouldBe` Just "bitcoincash:rvvxx9puznz3v6qyh5vjqv6kmgfkexzk0rx56faphrrr99syjqexy30vcqxv4"
     it "uses the prefix of the network" $ do
-      cashAddrEncode bchTest 0 hash20
+      cashAddrEncode bchTest3 0 hash20
         `shouldBe` Just "bchtest:qpm2qsznhks23z7629mms6s4cwef74vcwvqcw003ap"
       cashAddrEncode bchRegTest 0 hash20
         `shouldBe` Just "bchreg:qpm2qsznhks23z7629mms6s4cwef74vcwv6ycwvz78"
@@ -251,6 +252,18 @@
       cash32encodeType "pref" 1 (B.replicate 21 1) `shouldBe` Nothing
     it "cash32decodeType rejects mixed case" $
       cash32decodeType "pref:pr6m7j9njldwwzlg9v7v53unlr4jkmx6ey65nvtkS5" `shouldBe` Nothing
+    it "cash32decodeType rejects a string of megabytes at once" $
+      -- 20 million characters after the colon, where the largest hash takes
+      -- 112. The checksum is wrong, so that a decoder without the bound
+      -- stops after the checksum and does not hold gigabytes.
+      timeout 1000000 (evaluate (cash32decodeType ("pref:" <> T.replicate 20000000 "q")))
+        `shouldReturn` Just Nothing
+    it "cash32decodeType decodes under a prefix of any length" $
+      -- A prefix of 200 letters, then the version byte and hash20 with the
+      -- checksum for that prefix (Python transcription of the CashAddr
+      -- specification)
+      cash32decodeType (T.replicate 200 "a" <> ":qpm2qsznhks23z7629mms6s4cwef74vcwvw08n49vg")
+        `shouldBe` Just (T.replicate 200 "a", 0, hash20)
   describe "version byte" $ do
     it "decodeVersionByte splits the type and the hash size" $ do
       -- type in the high four bits, size code in the low three bits
diff --git a/test/Haskoin/AddressSpec.hs b/test/Haskoin/AddressSpec.hs
--- a/test/Haskoin/AddressSpec.hs
+++ b/test/Haskoin/AddressSpec.hs
@@ -1,6 +1,7 @@
 {-# LANGUAGE ImportQualifiedPost #-}
 {-# LANGUAGE OverloadedRecordDot #-}
 {-# LANGUAGE OverloadedStrings #-}
+{-# OPTIONS_GHC -Wno-deprecations #-}
 
 module Haskoin.AddressSpec (spec) where
 
@@ -15,6 +16,7 @@
 import Data.Bytes.Serial (deserialize, serialize)
 import Data.Default (def)
 import Data.Either (isLeft)
+import Data.List (isInfixOf)
 import Data.Maybe (fromJust, isJust)
 import Data.Text (Text)
 import Data.Text qualified as T
@@ -208,7 +210,7 @@
     it "addrToBase58 gives the legacy form of a Bitcoin Cash address" $ do
       addrToBase58 bch p2pkh `shouldBe` Just "1BpEi6DfDAUFd7GtittLSdBeYJvcoaVggu"
       addrToBase58 bch p2sh `shouldBe` Just "3CWFddi6m4ndiGyKqzYvsFYagqDLPVMTzC"
-      addrToBase58 bchTest p2sh `shouldBe` Just "2N44ThNe8NXHyv4bsX8AoVCXquBRW94Ls7W"
+      addrToBase58 bchTest3 p2sh `shouldBe` Just "2N44ThNe8NXHyv4bsX8AoVCXquBRW94Ls7W"
     it "addrToBase58 has no form for other kinds" $ do
       addrToBase58 btc p2wpkh `shouldBe` Nothing
       addrToBase58 bch p2sh32 `shouldBe` Nothing
@@ -426,7 +428,11 @@
               0 -> changed
               1 -> changed <> "\x00"
               _ -> B.take (B.length changed - 1) changed
-        scriptToAddressBS net bytes `shouldBe` parsed net bytes
+        if isJust net.cashAddrPrefix && B.take 1 bytes == "\xef"
+          then -- A token prefix takes at least 34 bytes, and these have at
+          -- most 35, which leaves no room for a script that has an address.
+            scriptToAddressBS net bytes `shouldSatisfy` isLeft
+          else scriptToAddressBS net bytes `shouldBe` parsed net bytes
     it "recovers the address of every standard locking script on a network that has its kind" $
       forM_ scriptTable $ \(net, a, hex) ->
         assertEqual (T.unpack hex) (Right a) (scriptToAddressBS net (fromJust (decodeHex hex)))
@@ -456,7 +462,7 @@
       (addrToText bch =<< eitherToMaybe (scriptToAddressBS bch puzzle))
         `shouldBe` Just "bitcoincash:pdh79rq2kmcmxukp563ydtnr7a8ex85rvhs45zyudrtpjqqqqqqqqgss5hn0j"
     it "a witness program has no address on Bitcoin Cash" $
-      forM_ [bch, bchTest, bchTest4, bchRegTest] $ \net -> do
+      forM_ [bch, bchTest3, bchTest4, bchRegTest] $ \net -> do
         -- version 0 with 20 bytes, version 0 with 32 bytes, and Taproot
         assertEqual net.name (Left "Could not decode address") $
           scriptToAddressBS net (fromJust (decodeHex "001476a04053bda0a88bda5177b86a15c3b29f559873"))
@@ -476,6 +482,59 @@
       -- This is the value an indexer encodes for that output
       marshalValue btc <$> eitherToMaybe (scriptToAddressBS btc (fromJust (decodeHex "aa206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d619000000000087")))
         `shouldBe` Nothing
+  describe "Outputs that hold CashTokens" $ do
+    it "have the plain address of their locking script on Bitcoin Cash" $
+      forM_ tokenOutputs $ \(field, plain, _) ->
+        (addrToText bch =<< eitherToMaybe (scriptToAddressBS bch (fromJust (decodeHex field))))
+          `shouldBe` Just plain
+    it "have the token-aware address of the independent vectors" $
+      forM_ tokenOutputs $ \(field, plain, aware) -> do
+        let a = fromJust (eitherToMaybe (scriptToAddressBS bch (fromJust (decodeHex field))))
+        (addrToText bch =<< tokenAwareAddress a) `shouldBe` Just aware
+        (plainAddress <$> textToAddr bch aware) `shouldBe` Just a
+        textToAddr bch plain `shouldBe` Just a
+    it "have the same address through scriptToAddress when the field parses as a script" $ do
+      -- Most fields do not parse: a byte of the prefix reads as a push longer
+      -- than the rest. This one does: OP_1 for each byte of the category,
+      -- then the flags of an NFT with a commitment, which read as OP_16, and
+      -- a push of the one byte of the commitment.
+      let bytes =
+            fromJust . decodeHex $
+              "ef"
+                <> T.replicate 32 "51"
+                <> "600151\
+                   \76a9146e0810ceea13412b73feb41566a3d2d0ce54e10188ac"
+      script <- either fail return (decodeSerial bytes)
+      (addrToText bch =<< eitherToMaybe (scriptToAddress bch script))
+        `shouldBe` Just "bitcoincash:qphqsyxwagf5z2mnl66p2e4r6tgvu48pqyhmvay0uy"
+      scriptToAddress btc script `shouldSatisfy` isLeft
+    it "have no address on Bitcoin, where 0xef is no prefix" $
+      forM_ tokenOutputs $ \(field, _, _) ->
+        forM_ [btc, btcTest, btcTest4, btcRegTest] $ \net ->
+          scriptToAddressBS net (fromJust (decodeHex field)) `shouldSatisfy` isLeft
+    it "have no address with a prefix that is not valid" $ do
+      -- the prefix byte and the category, no token flag set, then a P2PKH script
+      let field = T.take 66 tokenField4 <> "00" <> T.drop 78 tokenField4
+      T.drop 66 field `shouldBe` "0076a9146e0810ceea13412b73feb41566a3d2d0ce54e10188ac"
+      scriptToAddressBS bch (fromJust (decodeHex field))
+        `shouldSatisfy` either ("must encode at least one token" `isInfixOf`) (const False)
+    prop "have the address of the script after any valid prefix" $
+      forAll ((,,) <$> arbitraryTokenData <*> arbitraryScriptOutput bch <*> elements [bch, bchTest3]) $
+        \(t, out, net) -> do
+          let bytes = encodeSerial out
+              field = fromJust (encodeTokenPrefix t) <> bytes
+          scriptToAddressBS net field `shouldBe` scriptToAddressBS net bytes
+    it "token-aware forms exist for P2PKH, P2SH and P2SH32 only" $ do
+      (addressVersion <$> tokenAwareAddress p2pkh) `shouldBe` Just 2
+      (addressVersion <$> tokenAwareAddress p2sh) `shouldBe` Just 3
+      (addressVersion <$> tokenAwareAddress p2sh32) `shouldBe` Just 3
+      (tokenAwareAddress =<< tokenAwareAddress p2sh32) `shouldBe` tokenAwareAddress p2sh32
+      tokenAwareAddress p2wpkh `shouldBe` Nothing
+      tokenAwareAddress p2tr `shouldBe` Nothing
+      (addrToText btc =<< tokenAwareAddress p2pkh) `shouldBe` Nothing
+    prop "plainAddress undoes tokenAwareAddress" $
+      forAll (arbitraryAddress bch) $ \a ->
+        (plainAddress <$> tokenAwareAddress a) `shouldSatisfy` maybe True (== plainAddress a)
   describe "inputAddress" $ do
     it "gives the P2PKH address of the key in a public key hash input" $
       (addrToText btc =<< inputAddress (RegularInput (SpendPKHash TxSignatureEmpty compressedKey)))
@@ -655,8 +714,8 @@
     (bch, tokenP2sh, "bitcoincash:rpm2qsznhks23z7629mms6s4cwef74vcwv59yeyr7n"),
     (bch, tokenP2sh32, "bitcoincash:rvvxx9puznz3v6qyh5vjqv6kmgfkexzk0rx56faphrrr99syjqexy30vcqxv4"),
     (bch, cash15, "bitcoincash:0yqsyqcyq5rqwzqfpg9scrgwpugpzysnzs23v9cc7akt68km"),
-    (bchTest, p2pkh, "bchtest:qpm2qsznhks23z7629mms6s4cwef74vcwvqcw003ap"),
-    (bchTest, p2sh, "bchtest:ppm2qsznhks23z7629mms6s4cwef74vcwvhanqgjxu")
+    (bchTest3, p2pkh, "bchtest:qpm2qsznhks23z7629mms6s4cwef74vcwvqcw003ap"),
+    (bchTest3, p2sh, "bchtest:ppm2qsznhks23z7629mms6s4cwef74vcwvhanqgjxu")
   ]
 
 -- | Valid addresses of one network that another network must reject.
@@ -672,7 +731,7 @@
     (bch, "bc1qw6syq5aa5z5ghkj3w7ux59wrk204txrn9k4rmm"),
     (bch, "bchtest:qpm2qsznhks23z7629mms6s4cwef74vcwvqcw003ap"),
     (bch, "qpm2qsznhks23z7629mms6s4cwef74vcwvqcw003ap"),
-    (bchTest, "bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a")
+    (bchTest3, "bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a")
   ]
 
 -- | Locking script of every address kind that has one, with a network that
@@ -891,6 +950,40 @@
 -- 'scriptToAddressBS' did for every script until haskoin-core 1.6.2.
 parsed :: Network -> ByteString -> Either String Address
 parsed net bytes = maybeToEither "Could not decode address" . outputAddress net =<< decodeSerial bytes
+
+-- | Outputs of BCH transaction
+-- e3abdbdc093c08cab3d6c23c320ca61f23c6e2cf4d8b3058398dcf0e78f5a809, in block
+-- 978089, that hold tokens of category 7fe0cd51…b2f3062c: the script field,
+-- the plain address and the token-aware address. The token-aware addresses
+-- were computed by an independent script.
+tokenOutputs :: [(Text, Text, Text)]
+tokenOutputs =
+  [ ( "ef2c06f3b2565d0818a8e41f58beff5918d5dbdc64b11ee8ad474e499751cde07f10fe554a0700\
+      \aa20656cdb1806fdb2c60baefe95a759637ec62fb7a778e65c2a75f4a6b13be88e5087",
+      "bitcoincash:pdjkekccqm7m93st4mlftf6evdlvvtah5auwvhp2wh62dvfmaz89qln3srgfn",
+      "bitcoincash:rdjkekccqm7m93st4mlftf6evdlvvtah5auwvhp2wh62dvfmaz89qdqd36fsc"
+    ),
+    ( "ef2c06f3b2565d0818a8e41f58beff5918d5dbdc64b11ee8ad474e499751cde07f10fe4e7a0600\
+      \aa203ad77e7a68a924669f8f195263c9c17e4e449d01dc222f4d3e551d3f83fc519a87",
+      "bitcoincash:pvadwln6dz5jge5l3uv4yc7fc9lyu3yaq8wzyt6d8e2360url3ge52h6cellw",
+      "bitcoincash:rvadwln6dz5jge5l3uv4yc7fc9lyu3yaq8wzyt6d8e2360url3ge5cyxeq7x9"
+    ),
+    ( "ef2c06f3b2565d0818a8e41f58beff5918d5dbdc64b11ee8ad474e499751cde07f10fec3800100\
+      \aa204e913324a857399b8da9253c835759b930b40e8e047b0bf82ab64c415c9efd2287",
+      "bitcoincash:pd8fzvey4ptnnxud4yjneq6htxunpdqw3cz8kzlc92mycs2unm7jyrlqp9eks",
+      "bitcoincash:rd8fzvey4ptnnxud4yjneq6htxunpdqw3cz8kzlc92mycs2unm7jy3vuquc0m"
+    ),
+    ( tokenField4,
+      "bitcoincash:qphqsyxwagf5z2mnl66p2e4r6tgvu48pqyhmvay0uy",
+      "bitcoincash:zphqsyxwagf5z2mnl66p2e4r6tgvu48pqys3lr2frh"
+    )
+  ]
+
+-- | Output 4 of that transaction: 110,830 fungible tokens on a P2PKH script.
+tokenField4 :: Text
+tokenField4 =
+  "ef2c06f3b2565d0818a8e41f58beff5918d5dbdc64b11ee8ad474e499751cde07f10feeeb00100\
+  \76a9146e0810ceea13412b73feb41566a3d2d0ce54e10188ac"
 
 -- | The four kinds of script that 'scriptToAddressBS' reads by their bytes.
 standardShapes :: [Text]
diff --git a/test/Haskoin/BlockSpec.hs b/test/Haskoin/BlockSpec.hs
--- a/test/Haskoin/BlockSpec.hs
+++ b/test/Haskoin/BlockSpec.hs
@@ -1,7 +1,9 @@
 {-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
 {-# LANGUAGE OverloadedRecordDot #-}
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE ScopedTypeVariables #-}
+{-# OPTIONS_GHC -Wno-deprecations #-}
 
 module Haskoin.BlockSpec
   ( spec,
@@ -894,6 +896,33 @@
       requiredOn net specs time = withChain net (storeChain specs >> requiredAfter net time)
   it "finds the first block whose median time past reaches the activation time" $
     anchorHeights `shouldBe` [Nothing, Just 15, Just 15, Just 15]
+  it "takes the anchor that the network knows, when the chain holds it" $
+    knownAnchor (\nodes -> Just (15, headerHash (nodes !! 14).header)) `shouldBe` Just 15
+  it "trusts the known anchor without searching" $
+    -- Block 10 has not reached the activation time; only the constant can
+    -- name it.
+    knownAnchor (\nodes -> Just (10, headerHash (nodes !! 9).header)) `shouldBe` Just 10
+  it "searches when the chain does not hold the known anchor" $ do
+    knownAnchor (const (Just (15, genesisHash))) `shouldBe` Just 15
+    knownAnchor (const (Just (100, genesisHash))) `shouldBe` Just 15
+    -- Block 10 is not the anchor: only the check of the hash stops it.
+    knownAnchor (const (Just (10, genesisHash))) `shouldBe` Just 15
+  it "reads far less of the store with a known anchor" $ do
+    let reads net = flip evalState (initialChain net, 0) . runCounting $ do
+          nodes <- Counting (zoomChain (storeChain (evenlySpaced net 600 2000 0x1f400000)))
+          Counting (modify (fmap (const 0)))
+          a <- asertAnchor net (last nodes)
+          n <- Counting (gets snd)
+          return (fmap (.height) a, n)
+        known = withChain asertNet $ do
+          nodes <- storeChain (evenlySpaced asertNet 600 15 0x1f400000)
+          return (Just (15, headerHash (last nodes).header))
+        (searched, searchReads) = reads asertNet
+        (walked, walkReads) = reads (asertNet :: Network) {asertAnchorBlock = known}
+    (searched, walked) `shouldBe` (Just 15, Just 15)
+    -- 36 and 479 reads when this test was written
+    walkReads `shouldSatisfy` (< 50)
+    searchReads `shouldSatisfy` (> 10 * walkReads)
   it "has no anchor without an activation time" $
     withChain cashNet (storeChain steady >>= asertAnchor cashNet . last) `shouldBe` Nothing
   it "keeps the target when the chain is on schedule" $
@@ -985,26 +1014,48 @@
           let h = mineOn net par.header time bits
           _ <- either error id <$> connectBlock net myTime h
           return h
+    -- The anchor of a chain of thirty blocks on a network that knows the
+    -- anchor given for those blocks.
+    knownAnchor known = withChain asertNet $ do
+      nodes <- storeChain (evenlySpaced asertNet 600 30 0x1f400000)
+      let net = (asertNet :: Network) {asertAnchorBlock = known nodes}
+      fmap (.height) <$> asertAnchor net (last nodes)
     anchorHeights = withChain asertNet $ do
       nodes <- storeChain (evenlySpaced asertNet 600 30 0x1f400000)
       forM [nodes !! 13, nodes !! 14, nodes !! 19, last nodes] $ \n ->
         fmap (.height) <$> asertAnchor asertNet n
 
+-- | The memory store, with a count of the blocks read from it.
+newtype Counting a = Counting {runCounting :: State (HeaderMemory, Int) a}
+  deriving (Functor, Applicative, Monad)
+
+instance BlockHeaders Counting where
+  addBlockHeader n = Counting (zoomChain (addBlockHeader n))
+  getBlockHeader h = Counting (modify (fmap (+ 1)) >> zoomChain (getBlockHeader h))
+  getBestBlockHeader = Counting (zoomChain getBestBlockHeader)
+  setBestBlockHeader n = Counting (zoomChain (setBestBlockHeader n))
+
+-- | Run an action on the store alone.
+zoomChain :: State HeaderMemory a -> State (HeaderMemory, Int) a
+zoomChain act = state $ \(mem, n) -> let (a, mem') = runState act mem in (a, (mem', n))
+
 checkpointSpec :: Spec
 checkpointSpec = describe "checkpoints and versions" $ do
   it "accepts the checkpoint hash at its height" $
-    validCP btc 11111 "0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d" `shouldBe` True
+    validCP bch 11111 "0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d" `shouldBe` True
   it "rejects another hash at a checkpoint height" $
-    validCP btc 11111 genesisHash `shouldBe` False
+    validCP bch 11111 genesisHash `shouldBe` False
   it "accepts any hash where there is no checkpoint" $
-    validCP btc 11112 genesisHash `shouldBe` True
+    validCP bch 11112 genesisHash `shouldBe` True
   it "requires new blocks above the last checkpoint reached" $ do
-    -- the checkpoints at or below height 50000 are 11111 and 33333
-    afterLastCP btc 50000 33334 `shouldBe` True
-    afterLastCP btc 50000 33333 `shouldBe` False
-    afterLastCP btc 50000 11112 `shouldBe` False
-    afterLastCP btc 10000 1 `shouldBe` True
+    -- the checkpoints of Bitcoin Cash at or below height 50000 are 11111
+    -- and 33333; Bitcoin has none
+    afterLastCP bch 50000 33334 `shouldBe` True
+    afterLastCP bch 50000 33333 `shouldBe` False
+    afterLastCP bch 50000 11112 `shouldBe` False
+    afterLastCP bch 10000 1 `shouldBe` True
     afterLastCP btcRegTest 10000 1 `shouldBe` True
+    afterLastCP btc 50000 11112 `shouldBe` True
   it "checks the BIP34 activation block" $ do
     bip34 btc 227931 "000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8" `shouldBe` True
     bip34 btc 227931 genesisHash `shouldBe` False
@@ -1602,20 +1653,31 @@
     btcRegTest.targetTimespan `shouldBe` 86400
     diffInterval btcRegTest `shouldBe` 144
   it "retargets every 2016 blocks on the other networks" $
-    map diffInterval [btc, btcTest, btcTest4, bch, bchTest, bchTest4, bchRegTest] `shouldBe` replicate 7 2016
+    map diffInterval [btc, btcTest, btcTest4, bch, bchTest3, bchTest4, bchRegTest] `shouldBe` replicate 7 2016
   it "starts the EDA and the DAA one block after the heights of Bitcoin Cash Node" $ do
     -- chainparams.cpp of Bitcoin Cash Node: uahfHeight 478558, daaHeight
-    -- 504031 on mainnet; 1155875 and 1188697 on testnet3; 6 and 3000 on testnet4
+    -- 504031 on mainnet; 1155875 and 1188697 on testnet3; 6 and 3000 on
+    -- testnet4
     (bch.edaHeight, bch.daaHeight) `shouldBe` (Just 478559, Just 504032)
-    (bchTest.edaHeight, bchTest.daaHeight) `shouldBe` (Just 1155876, Just 1188698)
+    (bchTest3.edaHeight, bchTest3.daaHeight) `shouldBe` (Just 1155876, Just 1188698)
     (bchTest4.edaHeight, bchTest4.daaHeight) `shouldBe` (Just 7, Just 3001)
+    -- 0 and 0 on regtest
+    (bchRegTest.edaHeight, bchRegTest.daaHeight) `shouldBe` (Just 1, Just 1)
   it "activates ASERT at the time of Bitcoin Cash Node, with its half-lives" $ do
     -- axionActivationTime = 1605441600; nASERTHalfLife is two days on
     -- mainnet (172800 seconds) and one hour on the test networks (3600)
-    map (.asertActivationTime) [bch, bchTest, bchTest4, bchRegTest] `shouldBe` replicate 4 (Just 1605441600)
-    map (.asertHalfLife) [bch, bchTest, bchTest4, bchRegTest] `shouldBe` [172800, 3600, 3600, 172800]
+    map (.asertActivationTime) [bch, bchTest3, bchTest4, bchRegTest] `shouldBe` replicate 4 (Just 1605441600)
+    map (.asertHalfLife) [bch, bchTest3, bchTest4, bchRegTest] `shouldBe` [172800, 3600, 3600, 172800]
+  it "knows the aserti3-2d anchor of mainnet and testnet4, as Bitcoin Cash Node does" $ do
+    -- asertAnchorParams: block 661647 on mainnet and 16844 on testnet4. The
+    -- checkpoint of testnet4 at 16845 is the first block after its anchor.
+    bch.asertAnchorBlock
+      `shouldBe` Just (661647, "00000000000000000083ed4b7a780d59e3983513215518ad75654bb02deee62f")
+    bchTest4.asertAnchorBlock
+      `shouldBe` Just (16844, "00000000602570ee2b66c1d3f75d404c234f8aacdcc784da97e65838a2daf0fc")
+    map (.asertAnchorBlock) [btc, btcTest, btcTest4, btcRegTest, bchTest3, bchRegTest] `shouldBe` replicate 6 Nothing
   it "halves the subsidy every 210000 blocks, and every 150 on regtest" $ do
-    map (.halvingInterval) [btc, btcTest, btcTest4, bch, bchTest, bchTest4] `shouldBe` replicate 6 210000
+    map (.halvingInterval) [btc, btcTest, btcTest4, bch, bchTest3, bchTest4] `shouldBe` replicate 6 210000
     map (.halvingInterval) [btcRegTest, bchRegTest] `shouldBe` [150, 150]
   it "pays 50 coins before block 210000 and 25 from it" $ do
     computeSubsidy btc 209999 `shouldBe` 5000000000
@@ -1627,11 +1689,27 @@
     -- 33 halvings: 5000000000 shifted right by 32 is 1, by 33 is 0
     computeSubsidy btc 6929999 `shouldBe` 1
     computeSubsidy btc 6930000 `shouldBe` 0
-  it "has the checkpoint of block 33333 on bitcoin" $ do
-    validCP btc 33333 "000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6" `shouldBe` True
-    validCP btc 33333 "000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a7" `shouldBe` False
+  it "has no checkpoints on bitcoin, as Bitcoin Core 32.1 has none" $ do
+    map (.checkpoints) [btc, btcTest, btcTest4, btcRegTest] `shouldBe` replicate 4 []
+    validCP btc 33333 "000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a7" `shouldBe` True
+  it "has the checkpoints of Bitcoin Cash Node on bitcoin cash" $ do
+    -- mapCheckpoints of chainparams.cpp: 39 on mainnet, 19 on each testnet
+    -- and the genesis block on regtest
+    map (length . (.checkpoints)) [bch, bchTest3, bchTest4, bchRegTest] `shouldBe` [39, 19, 19, 1]
+    validCP bch 33333 "000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6" `shouldBe` True
+    validCP bch 33333 "000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a7" `shouldBe` False
+    -- the first blocks of the DAA, not the blocks before them
+    lookup 504032 bch.checkpoints
+      `shouldBe` Just "00000000000000000343e9875012f2062554c8752929892c82a0c0743ac7dcfd"
+    lookup 504031 bch.checkpoints `shouldBe` Nothing
+    lookup 1188698 bchTest3.checkpoints
+      `shouldBe` Just "0000000000051b450faa75bb8e1ea30bc18c4b9736e765d2794259a53bc83f99"
+    lookup 1188697 bchTest3.checkpoints `shouldBe` Nothing
+  it "has the seeds of the nodes on regtest" $ do
+    btcRegTest.seeds `shouldBe` ["dummySeed.invalid"]
+    bchRegTest.seeds `shouldBe` []
   it "enforces BIP94 on bitcoin testnet4 only" $ do
-    map (.bip94) [btc, btcTest, btcTest4, btcRegTest, bch, bchTest, bchTest4, bchRegTest]
+    map (.bip94) [btc, btcTest, btcTest4, btcRegTest, bch, bchTest3, bchTest4, bchRegTest]
       `shouldBe` [False, False, True, False, False, False, False, False]
     -- the first block of a period may be at most 600 seconds before its parent
     validTimeWarp btcTest4 2016 10000 9400 `shouldBe` True
@@ -1725,7 +1803,7 @@
     btcRegTest.minimumChainWork `shouldBe` 0
     -- chainparamsconstants.h of Bitcoin Cash Node at 3d13ce8
     bch.minimumChainWork `shouldBe` 0x0000000000000000000000000000000000000000030fd678912166474fe93f14
-    bchTest.minimumChainWork `shouldBe` 0x00000000000000000000000000000000000000000000011fdbbe582349040762
+    bchTest3.minimumChainWork `shouldBe` 0x00000000000000000000000000000000000000000000011fdbbe582349040762
     bchTest4.minimumChainWork `shouldBe` 0x000000000000000000000000000000000000000000000000bd5a1b5bda45b5da
     bchRegTest.minimumChainWork `shouldBe` 0
 
diff --git a/test/Haskoin/Crypto/Keys/ExtendedSpec.hs b/test/Haskoin/Crypto/Keys/ExtendedSpec.hs
--- a/test/Haskoin/Crypto/Keys/ExtendedSpec.hs
+++ b/test/Haskoin/Crypto/Keys/ExtendedSpec.hs
@@ -3,6 +3,7 @@
 {-# LANGUAGE OverloadedRecordDot #-}
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE TupleSections #-}
+{-# OPTIONS_GHC -Wno-deprecations #-}
 
 module Haskoin.Crypto.Keys.ExtendedSpec (spec) where
 
@@ -38,6 +39,11 @@
 import Test.QuickCheck hiding ((.&.))
 import Text.Read (readMaybe)
 
+-- | The order of two paths by their index lists: the shorter list first, then
+-- index by index, where a hardened index has its high bit set.
+shortlex :: DerivPath -> DerivPath -> Ordering
+shortlex = comparing (\p -> (length (pathToList p), pathToList p))
+
 identityTests :: IdentityTests
 identityTests =
   def
@@ -136,7 +142,7 @@
       forM_ [btc, bch] $ \net -> do
         xPrvExport net xprv1 `shouldBe` xprv1Text
         xPubExport net xpub1 `shouldBe` xpub1Text
-      forM_ [btcTest, btcTest4, btcRegTest, bchTest, bchTest4, bchRegTest] $ \net -> do
+      forM_ [btcTest, btcTest4, btcRegTest, bchTest3, bchTest4, bchRegTest] $ \net -> do
         xPrvExport net xprv1 `shouldBe` tprv1Text
         xPubExport net xpub1 `shouldBe` tpub1Text
     it "refuses an xpub given to the private key importer, and the reverse" $ do
@@ -395,6 +401,11 @@
       let p = (Deriv :| 44 :| 0 :: HardPath) ++/ (Deriv :/ 0 :/ 5 :: SoftPath)
       p `shouldBe` (Deriv :| 44 :| 0 :/ 0 :/ 5)
       pathToStr p `shouldBe` "/44'/0'/0/5"
+    it "++/ keeps the hardened steps of the path on its right" $
+      (Deriv :/ 1 :: SoftPath) ++/ (Deriv :| 2 :/ 3 :| 4 :: DerivPath) `shouldBe` (Deriv :/ 1 :| 2 :/ 3 :| 4)
+    it "++/ with a path of no step gives the other path" $ do
+      (Deriv :: SoftPath) ++/ (Deriv :| 2 :/ 3 :: DerivPath) `shouldBe` (Deriv :| 2 :/ 3)
+      (Deriv :| 2 :/ 3 :: DerivPath) ++/ (Deriv :: HardPath) `shouldBe` (Deriv :| 2 :/ 3)
     it "toHard keeps a path only when every segment is hardened" $ do
       toHard (Deriv :| 1 :| 2 :: DerivPath) `shouldBe` Just (Deriv :| 1 :| 2)
       toHard (Deriv :| 1 :/ 2 :: DerivPath) `shouldBe` Nothing
@@ -421,14 +432,82 @@
     it "binary soft path refuses a hardened segment" $
       (runGetS deserialize (hex "0000000000000001" <> hex "80000001") :: Either String SoftPath)
         `shouldSatisfy` isLeft
-    it "sorts a shorter path first, then by segment, soft before hard" $ do
-      (Deriv :/ 9 :: DerivPath) < (Deriv :/ 0 :/ 1) `shouldBe` True
-      (Deriv :/ 5 :: DerivPath) < (Deriv :| 0) `shouldBe` True
-      (Deriv :/ 1 :: DerivPath) < (Deriv :/ 2) `shouldBe` True
+  describe "Path order" $ do
+    -- Each pair is given smaller first, and compared in both directions:
+    -- `<` alone calls `compare` with its arguments exchanged.
+    let sortsBefore :: DerivPath -> DerivPath -> Expectation
+        sortsBefore a b = (compare a b, compare b a) `shouldBe` (LT, GT)
+    it "a path sorts equal to itself" $ do
+      compare (Deriv :: DerivPath) Deriv `shouldBe` EQ
+      compare (Deriv :| 1 :/ 2 :: DerivPath) (Deriv :| 1 :/ 2) `shouldBe` EQ
+    it "a shorter path sorts first, whatever the steps" $ do
+      Deriv `sortsBefore` (Deriv :/ 0)
+      (Deriv :/ 9) `sortsBefore` (Deriv :/ 0 :/ 1)
+      (Deriv :| 9) `sortsBefore` (Deriv :/ 0 :/ 1)
+      (Deriv :| 9 :| 9) `sortsBefore` (Deriv :/ 0 :/ 0 :/ 0)
+    it "a soft step sorts before a hardened step, whatever the indices" $ do
+      (Deriv :/ 5) `sortsBefore` (Deriv :| 0)
+      (Deriv :| 7 :/ 5) `sortsBefore` (Deriv :| 7 :| 0)
+      (Deriv :/ 7 :/ 5) `sortsBefore` (Deriv :/ 7 :| 0)
+    it "two soft steps sort by their index" $ do
+      (Deriv :/ 1) `sortsBefore` (Deriv :/ 2)
+      (Deriv :| 7 :/ 1) `sortsBefore` (Deriv :| 7 :/ 2)
+    it "two hardened steps sort by their index" $ do
+      (Deriv :| 1) `sortsBefore` (Deriv :| 2)
+      (Deriv :/ 7 :| 1) `sortsBefore` (Deriv :/ 7 :| 2)
+    it "the first step that differs decides, whatever the steps after it" $ do
+      (Deriv :/ 1 :/ 9) `sortsBefore` (Deriv :/ 2 :/ 0)
+      (Deriv :| 1 :| 9) `sortsBefore` (Deriv :| 2 :| 0)
+      (Deriv :/ 9 :| 9) `sortsBefore` (Deriv :| 0 :/ 0)
+      (Deriv :/ 1 :| 9 :/ 4) `sortsBefore` (Deriv :/ 2 :/ 0 :/ 4)
+      (Deriv :/ 3 :/ 1 :/ 9 :| 9) `sortsBefore` (Deriv :/ 3 :/ 2 :/ 0 :/ 0)
+    it "a path of hardened steps only, or of soft steps only, sorts the same way" $ do
+      compare (Deriv :| 9 :: HardPath) (Deriv :| 0 :| 1) `shouldBe` LT
+      compare (Deriv :| 1 :| 9 :: HardPath) (Deriv :| 2 :| 0) `shouldBe` LT
+      compare (Deriv :| 2 :| 0 :: HardPath) (Deriv :| 1 :| 9) `shouldBe` GT
+      compare (Deriv :/ 9 :: SoftPath) (Deriv :/ 0 :/ 1) `shouldBe` LT
+      compare (Deriv :/ 1 :/ 9 :: SoftPath) (Deriv :/ 2 :/ 0) `shouldBe` LT
+      compare (Deriv :/ 2 :/ 0 :: SoftPath) (Deriv :/ 1 :/ 9) `shouldBe` GT
     prop "ordering agrees with the shortlex order of the index lists" $
       forAll arbitraryDerivPath $ \a ->
         forAll arbitraryDerivPath $ \b ->
-          compare a b == comparing (\p -> (length (pathToList p), pathToList p)) a b
+          compare a b == shortlex a b
+    -- Two random paths share no step. These two have the same steps before
+    -- and after the one step that differs.
+    prop "ordering agrees with the shortlex order of the index lists, for two paths that differ in one step" $
+      forAll (listOf arbitraryBip32PathIndex) $ \before ->
+        forAll (listOf arbitraryBip32PathIndex) $ \after ->
+          forAll arbitraryBip32PathIndex $ \stepA ->
+            forAll arbitraryBip32PathIndex $ \stepB ->
+              let a = concatBip32Segments (before <> [stepA] <> after)
+                  b = concatBip32Segments (before <> [stepB] <> after)
+               in compare a b == shortlex a b
+  describe "A path takes time by its length, and not by the square of its length: in under three seconds" $ do
+    let steps = 50000 :: Int
+        -- /1/5'/5/5'/... and /2/5'/5/5'/..., of as many steps
+        tailOf path = foldl (\p _ -> p :/ 5 :| 5) (path :| 5) [2 .. steps `div` 2]
+        low = tailOf (Deriv :/ 1) :: DerivPath
+        high = tailOf (Deriv :/ 2) :: DerivPath
+        -- Whether the work gives the answer, when it does within three
+        -- seconds. The paths are built before the time starts.
+        answers :: (Eq a) => a -> a -> IO (Maybe Bool)
+        answers work answer = do
+          _ <- evaluate (low == high)
+          timeout 3000000 (evaluate (work == answer))
+    -- The seconds are those of the code that walked the path again at each
+    -- step, built without optimisation as the tests are.
+    -- 38 seconds
+    it "pathToStr writes a path of 50000 steps" $
+      answers (pathToStr low) ("/1/5'" <> concat (replicate (steps `div` 2 - 1) "/5/5'")) `shouldReturn` Just True
+    -- 32 seconds
+    it "two paths of 50000 steps that differ at the first step are put in order" $
+      answers (compare low high, compare high low) (LT, GT) `shouldReturn` Just True
+    -- 25 seconds
+    it "++/ puts a path of 50000 steps after another" $
+      answers
+        (pathToList ((Deriv :| 44 :: HardPath) ++/ low))
+        ([0x8000002c, 1, 0x80000005] <> concat (replicate (steps `div` 2 - 1) [5, 0x80000005]))
+        `shouldReturn` Just True
   describe "Path parsing" $ do
     -- BIP32 writes a hardened index with a subscript H, as in m/0H/1. Bitcoin
     -- Core and BIP380 write an apostrophe or a small h.
diff --git a/test/Haskoin/Crypto/Keys/Slip39Spec.hs b/test/Haskoin/Crypto/Keys/Slip39Spec.hs
--- a/test/Haskoin/Crypto/Keys/Slip39Spec.hs
+++ b/test/Haskoin/Crypto/Keys/Slip39Spec.hs
@@ -19,7 +19,7 @@
 import Control.DeepSeq (force)
 import Control.Exception (evaluate)
 import Control.Monad (forM_)
-import Control.Monad.State.Strict (State, modify, runState)
+import Control.Monad.State.Strict (State, evalState, modify, runState, state)
 import Crypto.Hash (SHA256 (..), hashWith)
 import Crypto.Random (drgNewTest, getRandomBytes, withDRG)
 import Data.Aeson (FromJSON (..), withObject, (.:))
@@ -211,6 +211,29 @@
     it "encodes a 20-byte value as 23 words, with no padding" $
       -- 160 bits is 16 words exactly
       fmap (length . T.words) (encodeShare vector1 {value = B.replicate 20 0}) `shouldBe` Right 23
+    it "reads and writes a share whose header fields all have their highest value" $ do
+      -- The 40 bits of such a header are all set, which is four times the
+      -- word 1023, "zero": the identifier 32767, the flag, the exponent 15,
+      -- the two indices 15, and 15 for the two thresholds and the group
+      -- count, which the header holds as one less. The words of the value
+      -- and of the checksum are those of the verifier.
+      let highest =
+            Share
+              { identifier = 32767,
+                extendable = True,
+                iterationExponent = 15,
+                groupIndex = 15,
+                groupThreshold = 16,
+                groupCount = 16,
+                memberIndex = 15,
+                memberThreshold = 16,
+                value = hex "101112131415161718191a1b1c1d1e1f"
+              }
+          mnemonic =
+            "zero zero zero zero again beard entrance declare airline blue \
+            \frequent legend endorse bumpy hush soldier lunar expand pipeline dictate"
+      decodeShare mnemonic `shouldBe` Right highest
+      encodeShare highest `shouldBe` Right mnemonic
     it "reads words in upper case" $
       decodeShare (T.toUpper (mnemonicOf vectors 1)) `shouldBe` Right vector1
     it "refuses 19 words" $
@@ -363,6 +386,11 @@
       splitSecret 3 4 secret (SplitRandom [B.take 15 secret] digestRandom) `shouldBe` Left "A random share must be as long as the secret"
     it "refuses a random part of another length" $
       splitSecret 2 3 secret (SplitRandom [] (B.take 11 digestRandom)) `shouldBe` Left "The random part of the digest share must have 12 bytes"
+    it "refuses a random share given twice in one split" $
+      -- two members would hold the same value, so each knows the share of
+      -- the other and the threshold of 4 is in truth 3
+      splitSecret 4 4 secret (SplitRandom [B.replicate 16 0x61, B.replicate 16 0x61] digestRandom)
+        `shouldBe` Left "Two of the random values are equal: each one must be drawn on its own"
     it "shows the random values of a split without their bytes" $
       -- the random shares are real shares, and the random part is most of
       -- the digest share
@@ -397,6 +425,37 @@
       fmap (.ciphertext) (encryptMasterSecret 1 True 0 "TREZOR" secret) `shouldBe` Right (hex "c5462e7421d4c690de1668d6a3bfd337")
     it "gives another ciphertext under another iteration exponent" $
       fmap (.ciphertext) (encryptMasterSecret 1 True 1 "" secret) `shouldBe` Right (hex "d51a2d68cb0adf27958873071f5253ac")
+    it "decrypts under an iteration exponent of 4" $
+      -- 2500 × 2^4 = 40,000 iterations a round. The verifier's value: no
+      -- vector of the reference implementation has an exponent above 3.
+      decryptMasterSecret "TREZOR" ems {iterationExponent = 4, ciphertext = B.replicate 16 0x11}
+        `shouldBe` Right (hex "65dfcb7b12749b53e39e72600297a274")
+    it "encrypts under an iteration exponent of 5" $
+      -- 2500 × 2^5 = 80,000 iterations a round, the first count that 16
+      -- bits do not hold. The verifier's value.
+      fmap (.ciphertext) (encryptMasterSecret 1 True 5 "" secret)
+        `shouldBe` Right (hex "fe2efd8f0a0d4ea564cc86c509b1bbf5")
+    it "runs 2500 iterations a round at the exponent 0, and twice as many at each exponent after it" $
+      -- 2500 × 2^15 = 2500 × 32768 = 81,920,000 at the last one. The cipher
+      -- is not run above the exponent 5 here: at 15 it takes minutes.
+      map roundIterations [0 .. 15]
+        `shouldBe` [ 2500,
+                     5000,
+                     10000,
+                     20000,
+                     40000,
+                     80000,
+                     160000,
+                     320000,
+                     640000,
+                     1280000,
+                     2560000,
+                     5120000,
+                     10240000,
+                     20480000,
+                     40960000,
+                     81920000
+                   ]
     it "decrypts to another master secret under a wrong passphrase, without an error" $
       decryptMasterSecret "trezor" ems `shouldSatisfy` \r -> r /= Right (hex "bb54aac4b89dc868ba37d9cc21b2cece") && either (const False) (const True) r
     it "accepts the first and the last printable ASCII characters" $
@@ -462,6 +521,11 @@
       it ("combines any threshold of the shares of " <> T.unpack c.caseDescription) $
         forM_ (thresholdSubsets c) $ \subset ->
           combineMnemonics c.casePassphrase subset `shouldBe` Right c.caseMasterSecret
+      it ("draws the shares of " <> T.unpack c.caseDescription <> " from the verifier's random values") $
+        -- every value that the source gives is in the shares, and the
+        -- source is asked for no byte more
+        runState (fmap (>>= traverse (traverse encodeShare)) (generateSharesFromCase scripted c)) (drawnBytes c)
+          `shouldBe` (Right c.caseMnemonics, B.empty)
     it "gives the 2-of-3 case these three mnemonics" $
       -- The second split case, written out: the first three words are the
       -- identifier 42, the flag and the exponent 1; the fourth differs by
@@ -492,6 +556,38 @@
     it "refuses random values for the wrong number of splits" $
       generateSharesWith (Scheme 1 [(1, 1)]) 1 True 0 "" "ABCDEFGHIJKLMNOP" [SplitRandom [] B.empty]
         `shouldBe` Left "A scheme of 1 groups takes 2 sets of random values: one for the split among the groups, then one per group"
+    it "refuses one random share given to every split" $
+      -- Four splits at a threshold of 3: each takes one random share, and
+      -- a random part that is its own here. The member of index 0 of each
+      -- group would get the random share as its share, and it is also the
+      -- share of the group of index 0: one member of another group would
+      -- hold what three members of that group are needed for.
+      generateSharesWith
+        (Scheme 3 [(3, 3), (3, 3), (3, 3)])
+        1
+        True
+        0
+        ""
+        "ABCDEFGHIJKLMNOP"
+        (map (SplitRandom [B.pack [0x61 .. 0x70]] . B.replicate 12) [0x41, 0x42, 0x43, 0x44])
+        `shouldBe` Left "Two of the random values are equal: each one must be drawn on its own"
+    it "refuses one random part of a digest share given to two splits" $
+      -- three splits at a threshold of 2: each takes a random part of
+      -- 16 - 4 = 12 bytes and no random share
+      generateSharesWith
+        (Scheme 2 [(2, 2), (2, 2)])
+        1
+        True
+        0
+        ""
+        "ABCDEFGHIJKLMNOP"
+        (map (SplitRandom [] . B.replicate 12) [0x41, 0x42, 0x41])
+        `shouldBe` Left "Two of the random values are equal: each one must be drawn on its own"
+    it "refuses a source of random bytes that gives the same bytes twice" $
+      -- a source that gives zeros: the random parts of the three splits at
+      -- a threshold of 2 are equal
+      evalState (generateSharesFrom recordedZeros (Scheme 2 [(2, 2), (2, 2)]) True 0 "" "ABCDEFGHIJKLMNOP") []
+        `shouldBe` Left "Two of the random values are equal: each one must be drawn on its own"
     it "asks its source for nothing when the master secret has 15 bytes" $
       runState (generateSharesFrom recordedZeros (Scheme 1 [(2, 3)]) True 0 "" "ABCDEFGHIJKLMNO") []
         `shouldBe` (Left "The master secret must have at least 16 bytes, not 15", [])
@@ -515,6 +611,16 @@
     it "refuses a source that gives fewer bytes than asked" $
       fst (runState (generateSharesFrom (\_ -> return "x") (Scheme 1 [(2, 3)]) True 0 "" "ABCDEFGHIJKLMNOP") ())
         `shouldBe` Left "The source of random bytes gave 1 bytes where 2 were asked for"
+    it "refuses a source that gives more bytes than asked" $
+      fst (runState (generateSharesFrom (\_ -> return "xyz") (Scheme 1 [(2, 3)]) True 0 "" "ABCDEFGHIJKLMNOP") ())
+        `shouldBe` Left "The source of random bytes gave 3 bytes where 2 were asked for"
+    it "reads the identifier from the first two bytes of its source, the high byte first" $
+      -- 0x30 × 256 + 0x39 = 12345
+      drawnIdentifier "\x30\x39" `shouldBe` Right [[12345]]
+    it "drops the top bit of those two bytes, for an identifier of 15 bits" $ do
+      -- 0xffff - 0x8000 = 0x7fff = 32767
+      drawnIdentifier "\xff\xff" `shouldBe` Right [[32767]]
+      drawnIdentifier "\x80\x00" `shouldBe` Right [[0]]
     it "draws a 15-bit identifier and shares of which any two of three rebuild the secret" $ do
       let secret = "ABCDEFGHIJKLMNOP"
           drawn = fst (withDRG (drgNewTest (1, 2, 3, 4, 5)) (generateSharesFrom getRandomBytes (Scheme 1 [(2, 3)]) True 0 "" secret))
@@ -552,6 +658,15 @@
           let ws = T.words (mnemonicOf vectors 1)
               changed = T.unwords (take position ws ++ [word] ++ drop (position + 1) ws)
            in ws !! position /= word ==> decodeShare changed === Left "The checksum of the mnemonic is invalid"
+    it "draws other shares from the system's randomness each time" $ do
+      -- Each draw has 15 bits of identifier and 96 bits of random part of
+      -- its own, so two draws that are the same mean a source that is not
+      -- random
+      let draw = generateMnemonics (Scheme 1 [(2, 3)]) True 0 "" "ABCDEFGHIJKLMNOP"
+      first <- draw
+      second <- draw
+      fmap (map length) first `shouldBe` Right [3]
+      first `shouldNotBe` second
     it "draws shares with the system's randomness that rebuild a two-level scheme" $ do
       let secret = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"
       drawn <- generateMnemonics (Scheme 2 [(1, 1), (2, 3), (3, 5)]) True 0 "pass" secret
@@ -583,6 +698,28 @@
     it "refuses more shares than the member threshold of a group" $
       combineShares [vector1, vector1 {memberIndex = 1}] `shouldBe` Left "Group 0 has 2 shares, but its member threshold is 1"
 
+    it "names the member index whose second share comes first, when two indices come twice" $ do
+      let member i = vector1 {memberIndex = i, memberThreshold = 2}
+      combineShares [member 1, member 2, member 1, member 2]
+        `shouldBe` Left "Group 0 has two shares with the member index 1"
+    it "refuses 257 shares, one more than 16 groups of 16 members give" $
+      combineShares (replicate 257 vector1)
+        `shouldBe` Left "There are 257 shares, but a backup has at most 256"
+    it "refuses 257 mnemonics by their number, before it reads them" $
+      combineMnemonics "" (replicate 257 "not a share")
+        `shouldBe` Left "There are 257 shares, but a backup has at most 256"
+    it "rebuilds a secret from 256 shares, all the members of 16 groups of 16" $ do
+      let secret = "ABCDEFGHIJKLMNOP"
+      drawn <- generateMnemonics (Scheme 16 (replicate 16 (16, 16))) True 0 "" secret
+      fmap (map length) drawn `shouldBe` Right (replicate 16 16)
+      (combineMnemonics "" . concat =<< drawn) `shouldBe` Right secret
+    it "refuses 100,000 shares within a second" $
+      -- The shares of each group used to be put in a list one after the
+      -- other, each at its end, in time that grew with the square of their
+      -- number: 6.7 seconds for 32,000 shares.
+      timeout 1000000 (evaluate (force (fmap (const ()) (combineShares (replicate 100000 vector1)))))
+        `shouldReturn` Just (Left "There are 100000 shares, but a backup has at most 256")
+
   describe "the shares of another implementation" $ do
     -- From the tests of Sparrow's library: eight groups of one member, five
     -- of them needed, and the value of the fifth share starts with a zero
@@ -739,6 +876,33 @@
 -- each request asked for, in order.
 recordedZeros :: Int -> State [Int] ByteString
 recordedZeros n = modify (++ [n]) >> return (B.replicate n 0)
+
+-- | A source of random bytes that gives the bytes of its state from the
+-- front, as many as asked for, and fewer when they run out.
+scripted :: Int -> State ByteString ByteString
+scripted n = state (B.splitAt n)
+
+-- | The bytes that the split of a case draws, in the order of the
+-- reference implementation: two bytes of identifier with the high byte
+-- first, then, for the split among the groups and for each group in turn,
+-- the random shares and the random part of the digest share.
+drawnBytes :: SplitCase -> ByteString
+drawnBytes c =
+  B.pack [fromIntegral (c.caseIdentifier `div` 256), fromIntegral (c.caseIdentifier `mod` 256)]
+    <> mconcat [mconcat r.randomShares <> r.digestRandom | r <- c.caseRandom]
+
+-- | 'generateSharesFrom' on the scheme, the flag, the exponent, the
+-- passphrase and the master secret of a split case.
+generateSharesFromCase :: (Monad m) => (Int -> m ByteString) -> SplitCase -> m (Either String [[Share]])
+generateSharesFromCase source c =
+  generateSharesFrom source c.caseScheme c.caseExtendable c.caseIterationExponent c.casePassphrase c.caseMasterSecret
+
+-- | The identifier of each share of a 1-of-1 split, which draws nothing
+-- but the two bytes of the identifier, from a source that gives the bytes.
+drawnIdentifier :: ByteString -> Either String [[Int]]
+drawnIdentifier bytes =
+  map (map (.identifier))
+    <$> evalState (generateSharesFrom scripted (Scheme 1 [(1, 1)]) True 0 "" "ABCDEFGHIJKLMNOP") bytes
 
 -- | The last n elements of a list.
 lastN :: Int -> [a] -> [a]
diff --git a/test/Haskoin/Crypto/KeysSpec.hs b/test/Haskoin/Crypto/KeysSpec.hs
--- a/test/Haskoin/Crypto/KeysSpec.hs
+++ b/test/Haskoin/Crypto/KeysSpec.hs
@@ -2,6 +2,7 @@
 {-# LANGUAGE ImportQualifiedPost #-}
 {-# LANGUAGE OverloadedRecordDot #-}
 {-# LANGUAGE OverloadedStrings #-}
+{-# OPTIONS_GHC -Wno-deprecations #-}
 
 module Haskoin.Crypto.KeysSpec (spec) where
 
diff --git a/test/Haskoin/Crypto/SignatureSpec.hs b/test/Haskoin/Crypto/SignatureSpec.hs
--- a/test/Haskoin/Crypto/SignatureSpec.hs
+++ b/test/Haskoin/Crypto/SignatureSpec.hs
@@ -119,6 +119,24 @@
       -- DER: 30 26 | 02 21 00 <n> | 02 01 01
       decodeStrictSig (hex "3026022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141020101")
         `shouldBe` Nothing
+  -- Bitcoin Cash Node reads a signature of 64 bytes as a Schnorr signature,
+  -- also when the bytes are an ECDSA signature in DER.
+  describe "The length that Bitcoin Cash reads as a Schnorr signature" $ do
+    -- an r or an s of this many bytes: 0x01 and then zero bytes
+    let number n = BS.pack [0x02, n, 0x01] <> BS.replicate (fromIntegral n - 1) 0x00
+        -- DER: 30, the length of what follows, then r and s
+        der r s = BS.pack [0x30, 4 + r + s] <> number r <> number s
+    it "is the length of an ECDSA signature whose r and s take 29 bytes each" $
+      -- 2 + (2 + 29) + (2 + 29) = 64
+      fmap isCashSchnorrLength (decodeStrictSig (der 29 29)) `shouldBe` Just True
+    it "is not the length of a signature one byte shorter or longer" $ do
+      -- 2 + (2 + 29) + (2 + 28) = 63
+      fmap isCashSchnorrLength (decodeStrictSig (der 29 28)) `shouldBe` Just False
+      -- 2 + (2 + 29) + (2 + 30) = 65
+      fmap isCashSchnorrLength (decodeStrictSig (der 29 30)) `shouldBe` Just False
+    it "is not the length of an ordinary signature, of 70 bytes" $
+      -- 2 + (2 + 32) + (2 + 32) = 70
+      fmap isCashSchnorrLength (decodeStrictSig (der 32 32)) `shouldBe` Just False
   describe "Binary signature decoding" $ do
     it "decodes the smallest signature" $
       fmap exportSig (decodeSerial (hex "3006020101020101"))
diff --git a/test/Haskoin/Network/Protocol/BitcoinCashNodeSpec.hs b/test/Haskoin/Network/Protocol/BitcoinCashNodeSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Haskoin/Network/Protocol/BitcoinCashNodeSpec.hs
@@ -0,0 +1,724 @@
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoFieldSelectors #-}
+{-# OPTIONS_GHC -Wno-deprecations #-}
+
+module Haskoin.Network.Protocol.BitcoinCashNodeSpec (spec) where
+
+import Data.ByteString qualified as B
+import Data.Int (Int32, Int64)
+import Data.List (foldl')
+import Data.Maybe (isJust, isNothing)
+import Data.Sequence qualified as S
+import Data.Set qualified as Set
+import Data.Word (Word64)
+import Haskoin.Block
+import Haskoin.Network
+import Haskoin.Network.Protocol.BitcoinCashNode qualified as BCHN
+import Haskoin.Network.Protocol.Types
+import Haskoin.Transaction
+import Network.Socket (SockAddr (..))
+import Test.Hspec
+
+-- Helpers -------------------------------------------------------------------
+
+-- | The time of the tests, in seconds.
+t0 :: Micros
+t0 = seconds 1700000000
+
+-- | What the node knows of the genesis block of a network.
+genesisInfo :: Network -> BlockInfo
+genesisInfo net =
+  BlockInfo
+    { hash = headerHash net.genesisHeader,
+      height = 0,
+      status = HaveData,
+      inActiveChain = True,
+      work = 1,
+      time = net.genesisHeader.timestamp
+    }
+
+-- | A node out of initial block download with only the genesis block, at
+-- some seconds after 't0'.
+envAt :: Network -> Micros -> Env
+envAt net dt =
+  (defaultEnv (genesisInfo net) (genesisBlock net) (t0 + dt))
+    { initialBlockDownload = False
+    }
+
+-- | A connection of a type, with permissions.
+setupOf :: ConnectionType -> [Permission] -> Setup
+setupOf ct ps =
+  Setup
+    { connectionType = ct,
+      permissions = Set.fromList ps,
+      peerNetwork = AddrIPv4,
+      peerIsLocal = False,
+      transport = TransportV1,
+      openedAt = t0,
+      seed = 7
+    }
+
+-- | The null address of a @version@.
+nullAddress :: NetworkAddress
+nullAddress = NetworkAddress 0 (sockToHostAddress (SockAddrInet6 0 0 (0, 0, 0, 0) 0))
+
+-- | The @version@ of a peer of protocol 70016 that serves the chain.
+peerVersion :: Version
+peerVersion =
+  Version
+    { version = 70016,
+      services = 1 + 32,
+      timestamp = 1700000000,
+      addrRecv = nullAddress,
+      addrSend = nullAddress,
+      nonce = 42,
+      userAgent = VarString "/test:1.0/",
+      startHeight = 0,
+      relay = True
+    }
+
+-- | 'peerVersion' with another protocol version.
+versionOf :: Int32 -> Version
+versionOf n = let Version _ s t a b o u h r = peerVersion in Version n s t a b o u h r
+
+-- | 'peerVersion' with other services.
+withServices :: Word64 -> Version
+withServices x = let Version n _ t a b o u h r = peerVersion in Version n x t a b o u h r
+
+-- | 'peerVersion' with another time.
+withTime :: Int64 -> Version
+withTime x = let Version n s _ a b o u h r = peerVersion in Version n s x a b o u h r
+
+-- | 'peerVersion' with another relay flag.
+withRelay :: Bool -> Version
+withRelay x = let Version n s t a b o u h _ = peerVersion in Version n s t a b o u h x
+
+-- | A machine on a network with its options, and the state of a connection.
+data Peer = Peer
+  { net :: Network,
+    opts :: BCHN.Options,
+    st :: BCHN.State
+  }
+
+-- | Open a connection.
+open :: Network -> (BCHN.Options -> BCHN.Options) -> ConnectionType -> [Permission] -> Peer
+open n f ct ps =
+  let o = f (BCHN.defaultOptions n)
+   in Peer n o (BCHN.start o (setupOf ct ps))
+
+-- | Feed an input at some seconds after 't0', with a change to the
+-- environment.
+feedWith :: (Env -> Env) -> Micros -> Input -> Peer -> (Peer, [Effect])
+feedWith f dt i p =
+  let (s', es) = BCHN.step p.opts (f (envAt p.net dt)) p.st i
+   in (p {st = s'}, es)
+
+-- | Feed an input at some seconds after 't0'.
+feed :: Micros -> Input -> Peer -> (Peer, [Effect])
+feed = feedWith id
+
+-- | Feed inputs in order, keeping only the last effects.
+feeds :: Micros -> [Input] -> Peer -> (Peer, [Effect])
+feeds dt is p = foldl' (\(q, _) i -> feed dt i q) (p, []) is
+
+-- | The actions of some effects.
+actions :: [Effect] -> [Action]
+actions = map (.action)
+
+-- | The messages sent.
+sent :: [Effect] -> [Message]
+sent es = [m | Send m <- actions es]
+
+-- | The commands of the messages sent.
+sentCommands :: [Effect] -> [MessageCommand]
+sentCommands = map msgType . sent
+
+-- | The nonce of the ping sent, or 0.
+pingNonce :: [Effect] -> Word64
+pingNonce es = case [x | MPing (Ping x) <- sent es] of
+  (x : _) -> x
+  [] -> 0
+
+-- | Some effect is a disconnect.
+disconnects :: [Effect] -> Bool
+disconnects es = not (null [() | Disconnect _ <- actions es])
+
+-- | Some effect discourages the peer.
+discourages :: [Effect] -> Bool
+discourages = elem Discourage . actions
+
+-- | The scores added.
+scores :: [Effect] -> [Int]
+scores es = [n | Misbehave n <- actions es]
+
+-- | An inbound peer past the handshake.
+inboundReady :: Network -> [Permission] -> Peer
+inboundReady n ps =
+  fst (feeds 1 [Receive (MVersion peerVersion), Receive MVerAck] (open n id Inbound ps))
+
+-- | An outbound peer past the handshake.
+outboundReady :: Network -> Peer
+outboundReady n =
+  fst (feeds 1 [Receive (MVersion peerVersion), Receive MVerAck] (open n id OutboundFullRelay []))
+
+-- | A @reject@ with this code was sent.
+rejects :: RejectCode -> [Effect] -> Bool
+rejects c es = not (null [() | MReject r <- sent es, r.code == c])
+
+-- | Every effect cites a line of the upstream source.
+allCited :: [Effect] -> Bool
+allCited = all (\e -> e.because.line > 0 && not (null e.because.file))
+
+-- | A transaction with one input and one output.
+someTx :: Tx
+someTx =
+  Tx
+    { version = 1,
+      inputs = [TxIn (OutPoint "0000000000000000000000000000000000000000000000000000000000000001" 0) "" 0],
+      outputs = [TxOut 1000 "\x51"],
+      witness = [],
+      locktime = 0
+    }
+
+-- Spec ----------------------------------------------------------------------
+
+spec :: Spec
+spec = describe "Haskoin.Network.Protocol.BitcoinCashNode" $ do
+  handshakeSpec
+  orderSpec
+  pingSpec
+  timeoutSpec
+  misbehaviourSpec
+  framingSpec
+  permissionSpec
+  networkSpec
+  blockSpec
+  relaySpec
+
+handshakeSpec :: Spec
+handshakeSpec = describe "handshake" $ do
+  it "answers the version of an inbound peer with version, sendaddrv2 and verack" $ do
+    let (_, es) = feed 1 (Receive (MVersion peerVersion)) (open bch id Inbound [])
+    sentCommands es `shouldBe` [MCVersion, MCSendAddrV2, MCVerAck]
+    allCited es `shouldBe` True
+  it "sends no sendaddrv2 to a peer older than 70016" $ do
+    let v = versionOf 70015
+        (_, es) = feed 1 (Receive (MVersion v)) (open bch id Inbound [])
+    sentCommands es `shouldBe` [MCVersion, MCVerAck]
+  it "sends sendheaders and sendcmpct on the peer's verack" $ do
+    let p = fst (feed 1 (Receive (MVersion peerVersion)) (open bch id Inbound []))
+        (p', es) = feed 1 (Receive MVerAck) p
+    sentCommands es `shouldBe` [MCSendHeaders, MCSendCmpct]
+    sent es `shouldContain` [MSendCompact (SendCompact False 1)]
+    BCHN.handshakeComplete p'.st `shouldBe` True
+  it "sends its version first to an outbound peer, then verack and getaddr" $ do
+    let p = open bch id OutboundFullRelay []
+        (p1, es1) = feed 0 Tick p
+        (_, es2) = feed 1 (Receive (MVersion peerVersion)) p1
+    sentCommands es1 `shouldBe` [MCVersion]
+    sentCommands es2 `shouldBe` [MCSendAddrV2, MCVerAck, MCGetAddr]
+  it "says relay false in its version in blocks-only mode" $ do
+    let p = open bch (\o -> o {BCHN.blocksOnly = True}) OutboundFullRelay []
+        (_, es) = feed 0 Tick p
+    [v.relay | MVersion v <- sent es] `shouldBe` [False]
+  it "refuses an outbound peer without the services it wants" $ do
+    let v = withServices (32)
+        (_, es) = feed 1 (Receive (MVersion v)) (open bch id OutboundFullRelay [])
+    rejects RejectNonStandard es `shouldBe` True
+    disconnects es `shouldBe` True
+  it "takes NODE_NETWORK_LIMITED from an outbound peer out of IBD" $ do
+    let v = withServices (1024 + 32)
+        (_, es) = feed 1 (Receive (MVersion v)) (open bch id OutboundFullRelay [])
+    disconnects es `shouldBe` False
+  it "refuses a version older than 31800" $ do
+    let v = versionOf 31799
+        (_, es) = feed 1 (Receive (MVersion v)) (open bch id Inbound [])
+    rejects RejectObsolete es `shouldBe` True
+    disconnects es `shouldBe` True
+    sentCommands es `shouldNotContain` [MCVersion]
+  it "disconnects a connection to itself" $ do
+    let (_, es) =
+          feedWith (\e -> e {ownNonce = (== 42)}) 1 (Receive (MVersion peerVersion)) (open bch id Inbound [])
+    disconnects es `shouldBe` True
+    sent es `shouldBe` []
+  it "disconnects a feeler after version" $ do
+    let (_, es) = feeds 1 [Tick, Receive (MVersion peerVersion)] (open bch id Feeler [])
+    disconnects es `shouldBe` True
+    sentCommands es `shouldContain` [MCVerAck]
+  it "disconnects a peer of a rejected sub-version, but not a manual one" $ do
+    let f o = o {BCHN.rejectSubVersions = ["test"]}
+        (_, es) = feed 1 (Receive (MVersion peerVersion)) (open bch f Inbound [])
+        (_, es') = feeds 1 [Tick, Receive (MVersion peerVersion)] (open bch f Manual [])
+    disconnects es `shouldBe` True
+    disconnects es' `shouldBe` False
+  it "uses extversion when both sides offer it" $ do
+    let f o = o {BCHN.useExtVersion = True}
+        v = withServices (1 + 32 + 2048)
+        p = open bch f Inbound []
+        (p1, es1) = feed 1 (Receive (MVersion v)) p
+        (p2, es2) = feed 1 (Receive (MOther "extversion" (B.pack [1, 0, 1, 100]))) p1
+    sentCommands es1 `shouldBe` [MCVersion, MCOther "extversion"]
+    sentCommands es2 `shouldBe` [MCSendAddrV2, MCVerAck]
+    BCHN.negotiatedExtVersion p2.st `shouldBe` True
+  it "answers verack with verack when the peer ignored extversion" $ do
+    let f o = o {BCHN.useExtVersion = True}
+        v = withServices (1 + 32 + 2048)
+        (_, es) = feeds 1 [Receive (MVersion v), Receive MVerAck] (open bch f Inbound [])
+    sentCommands es `shouldBe` [MCSendAddrV2, MCVerAck, MCSendHeaders, MCSendCmpct]
+  it "disconnects extversion after verack" $ do
+    let (_, es) = feed 2 (Receive (MOther "extversion" (B.pack [0]))) (inboundReady bch [])
+    disconnects es `shouldBe` True
+  it "takes sendaddrv2 before verack and disconnects it after" $ do
+    let p = fst (feed 1 (Receive (MVersion peerVersion)) (open bch id Inbound []))
+        (p1, _) = feed 1 (Receive MSendAddrV2) p
+        (_, es) = feed 1 (Receive MSendAddrV2) (fst (feed 1 (Receive MVerAck) p1))
+    BCHN.negotiatedAddrV2 p1.st `shouldBe` True
+    disconnects es `shouldBe` True
+
+orderSpec :: Spec
+orderSpec = describe "messages out of order" $ do
+  it "scores 10 for a message before version" $ do
+    let (_, es) = feed 1 (Receive (MPing (Ping 1))) (open bch id Inbound [])
+    scores es `shouldBe` [10]
+  it "only logs a reject before version" $ do
+    let r = Reject MCTx RejectInvalid (VarString "x") Nothing
+        (_, es) = feed 1 (Receive (MReject r)) (open bch id Inbound [])
+    actions es `shouldBe` [Ignore]
+  it "drops a ping between version and verack without a pong" $ do
+    let p = fst (feed 1 (Receive (MVersion peerVersion)) (open bch id Inbound []))
+        (_, es) = feed 1 (Receive (MPing (Ping 1))) p
+    actions es `shouldBe` [Ignore]
+  it "answers a second version with a reject and a score of 1" $ do
+    let (_, es) = feed 2 (Receive (MVersion peerVersion)) (inboundReady bch [])
+    rejects RejectDuplicate es `shouldBe` True
+    scores es `shouldBe` [1]
+  it "sends sendheaders again on a second verack" $ do
+    let (_, es) = feed 2 (Receive MVerAck) (inboundReady bch [])
+    sentCommands es `shouldBe` [MCSendHeaders, MCSendCmpct]
+  it "drops an unknown command after the handshake" $ do
+    let (_, es) = feed 2 (Receive (MOther "foo" "")) (inboundReady bch [])
+    actions es `shouldBe` [Ignore]
+  it "drops the messages of Bitcoin Core it does not know" $ do
+    let p = inboundReady bch []
+    actions (snd (feed 2 (Receive MWtxidRelay) p)) `shouldBe` [Ignore]
+    actions (snd (feed 2 (Receive (MSendTxRcncl (SendTxRcncl 1 2))) p)) `shouldBe` [Ignore]
+    actions (snd (feed 2 (Receive (MAlert (Alert (VarString "") (VarString "")))) p)) `shouldBe` [Ignore]
+
+pingSpec :: Spec
+pingSpec = describe "ping and pong" $ do
+  it "answers a ping with a pong after the handshake" $ do
+    let (_, es) = feed 2 (Receive (MPing (Ping 99))) (inboundReady bch [])
+    sent es `shouldBe` [MPong (Pong 99)]
+  it "pings at the first pass after the handshake" $ do
+    let (p, es) = feed 2 Tick (inboundReady bch [])
+    sentCommands es `shouldContain` [MCPing]
+    BCHN.pingOutstanding p.st `shouldSatisfy` isJust
+  it "ends the ping on the matching pong" $ do
+    let (p, es) = feed 2 Tick (inboundReady bch [])
+        n = pingNonce es
+        (p', _) = feed 3 (Receive (MPong (Pong n))) p
+    BCHN.pingOutstanding p'.st `shouldSatisfy` isNothing
+  it "keeps the ping on a pong of another nonce" $ do
+    let (p, es) = feed 2 Tick (inboundReady bch [])
+        n = pingNonce es
+        (p', _) = feed 3 (Receive (MPong (Pong (n + 1)))) p
+    BCHN.pingOutstanding p'.st `shouldBe` Just n
+  it "disconnects when the pong does not come in 20 minutes" $ do
+    let p = fst (feed 2 Tick (inboundReady bch []))
+        -- the peer keeps the connection busy with pings of its own
+        p' = fst (feed (seconds 1000) (Receive (MPing (Ping 5))) p)
+        (_, es) = feed (seconds 1203) Tick p'
+    [c.line | Effect (Disconnect Timeout) c <- es] `shouldBe` [1296]
+
+timeoutSpec :: Spec
+timeoutSpec = describe "timeouts" $ do
+  it "disconnects a peer that sends nothing in the first minute" $ do
+    let (_, es) = feed (seconds 61) Tick (open bch id Inbound [])
+    [c.line | Effect (Disconnect Timeout) c <- es] `shouldBe` [1280]
+  it "does nothing before the first minute" $ do
+    let (_, es) = feed (seconds 60) Tick (open bch id Inbound [])
+    es `shouldBe` []
+  it "disconnects a peer that does not finish the handshake in a minute" $ do
+    let p = fst (feed 1 (Receive (MVersion peerVersion)) (open bch id Inbound []))
+        (_, es) = feed (seconds 62) Tick p
+    [c.line | Effect (Disconnect Timeout) c <- es] `shouldBe` [1300]
+  it "follows -peertimeout" $ do
+    let p = open bch (\o -> o {BCHN.peerTimeout = 120}) Inbound []
+    snd (feed (seconds 100) Tick p) `shouldBe` []
+
+misbehaviourSpec :: Spec
+misbehaviourSpec = describe "misbehaviour" $ do
+  let early = Receive (MPing (Ping 1))
+  it "discourages and disconnects at a score of 100" $ do
+    let (p, es) = feeds 1 (replicate 10 early) (open bch id Inbound [])
+    discourages es `shouldBe` True
+    disconnects es `shouldBe` True
+    BCHN.banScoreOf p.st `shouldBe` 100
+  it "does not act below the threshold" $ do
+    let (_, es) = feeds 1 (replicate 9 early) (open bch id Inbound [])
+    discourages es `shouldBe` False
+  it "follows -banscore" $ do
+    let (_, es) = feeds 1 (replicate 5 early) (open bch (\o -> o {BCHN.banScore = 50}) Inbound [])
+    discourages es `shouldBe` True
+  it "processes nothing after the decision to disconnect" $ do
+    let (p, _) = feeds 1 (replicate 10 early) (open bch id Inbound [])
+        (_, es) = feed 1 (Receive (MVersion peerVersion)) p
+    actions es `shouldBe` [Ignore]
+  it "never punishes a noban peer" $ do
+    let (p, es) = feeds 1 (replicate 20 early) (open bch id Inbound [PermNoBan])
+    discourages es `shouldBe` False
+    disconnects es `shouldBe` False
+    BCHN.banScoreOf p.st `shouldBe` 200
+  it "never punishes a manual peer" $ do
+    let (_, es) = feeds 1 (Tick : replicate 10 early) (open bch id Manual [])
+    disconnects es `shouldBe` False
+  it "disconnects a local peer without discouraging it" $ do
+    let s = (setupOf Inbound []) {peerIsLocal = True}
+        o = BCHN.defaultOptions bch
+        p = Peer bch o (BCHN.start o s)
+        (_, es) = feeds 1 (replicate 10 early) p
+    disconnects es `shouldBe` True
+    discourages es `shouldBe` False
+  it "acts on a penalty from the rest of the node at the next pass" $ do
+    let p = inboundReady bch []
+        (p1, es1) = feed 2 (Notify (Penalty 100 "bad-dsproof")) p
+        (_, es2) = feed 2 Tick p1
+    scores es1 `shouldBe` [100]
+    discourages es2 `shouldBe` True
+
+framingSpec :: Spec
+framingSpec = describe "framing" $ do
+  it "discourages a peer for the wrong magic, even with noban" $ do
+    let (_, es) = feed 1 (BadFrame (WrongMagic 0)) (open bch id Inbound [PermNoBan])
+    discourages es `shouldBe` True
+    disconnects es `shouldBe` True
+  it "discourages a peer for a bad checksum" $ do
+    let (_, es) = feed 1 (BadFrame (BadChecksum "ping")) (open bch id Inbound [])
+    discourages es `shouldBe` True
+  it "drops a message with a bad command" $ do
+    let (_, es) = feed 1 (BadFrame (BadCommand "\1")) (open bch id Inbound [])
+    actions es `shouldBe` [Ignore]
+  it "disconnects an oversized message without discouraging" $ do
+    let (_, es) = feed 1 (BadFrame (Oversized "tx" 3000000)) (open bch id Inbound [])
+    disconnects es `shouldBe` True
+    discourages es `shouldBe` False
+  it "answers a payload that does not parse with a malformed reject" $ do
+    let (_, es) = feed 2 (BadFrame (BadPayload "inv")) (inboundReady bch [])
+    rejects RejectMalformed es `shouldBe` True
+    scores es `shouldBe` []
+  it "scores a bad payload before version as a missing version" $ do
+    let (_, es) = feed 1 (BadFrame (BadPayload "inv")) (open bch id Inbound [])
+    scores es `shouldBe` [10]
+  it "rejects a version that does not parse" $ do
+    let (_, es) = feed 1 (BadFrame (BadPayload "version")) (open bch id Inbound [])
+    rejects RejectMalformed es `shouldBe` True
+  it "ends the ping on a short pong" $ do
+    let (p, _) = feed 2 Tick (inboundReady bch [])
+        (p', _) = feed 3 (BadFrame (BadPayload "pong")) p
+    BCHN.pingOutstanding p'.st `shouldSatisfy` isNothing
+
+permissionSpec :: Spec
+permissionSpec = describe "permissions" $ do
+  it "expands a bare whitelist to noban, mempool and relay" $ do
+    let p = open bch id Inbound [PermImplicit]
+    BCHN.permissionsOf p.st `shouldBe` Set.fromList [PermNoBan, PermMempool, PermRelay]
+  it "drops relay from a bare whitelist in blocks-only mode" $ do
+    let p = open bch (\o -> o {BCHN.blocksOnly = True}) Inbound [PermImplicit]
+    BCHN.permissionsOf p.st `shouldBe` Set.fromList [PermNoBan, PermMempool]
+  it "gives no permission to an outbound peer" $ do
+    let p = open bch id Manual [PermNoBan]
+    BCHN.permissionsOf p.st `shouldBe` Set.empty
+  it "offers NODE_BLOOM to a peer with the bloomfilter permission" $ do
+    let f o = o {BCHN.peerBloomFilters = False}
+    BCHN.servicesOffered (open bch f Inbound []).st `shouldBe` (1 + 32 + 1024)
+    BCHN.servicesOffered (open bch f Inbound [PermBloomFilter]).st `shouldBe` (1 + 4 + 32 + 1024)
+  it "drops transactions in blocks-only mode unless the peer has relay" $ do
+    let f o = o {BCHN.blocksOnly = True}
+        ready ps = fst (feeds 1 [Receive (MVersion peerVersion), Receive MVerAck] (open bch f Inbound ps))
+        (_, es1) = feed 2 (Receive (MTx someTx)) (ready [])
+        (_, es2) = feed 2 (Receive (MTx someTx)) (ready [PermRelay])
+    actions es1 `shouldBe` [Ignore]
+    actions es2 `shouldNotBe` [Ignore]
+  it "answers getheaders in IBD only to a noban peer" $ do
+    let gh = MGetHeaders (GetHeaders 70016 [] (headerHash bch.genesisHeader))
+        ibd e = e {initialBlockDownload = True}
+        (_, es1) = feedWith ibd 2 (Receive gh) (inboundReady bch [])
+        (_, es2) = feedWith ibd 2 (Receive gh) (inboundReady bch [PermNoBan])
+    actions es1 `shouldBe` [Ignore]
+    sentCommands es2 `shouldBe` [MCHeaders]
+  it "disconnects a mempool request without bloom filters, but not from noban" $ do
+    let f o = o {BCHN.peerBloomFilters = False}
+        ready ps = fst (feeds 1 [Receive (MVersion peerVersion), Receive MVerAck] (open bch f Inbound ps))
+    disconnects (snd (feed 2 (Receive MMempool) (ready []))) `shouldBe` True
+    actions (snd (feed 2 (Receive MMempool) (ready [PermNoBan]))) `shouldBe` [Ignore]
+
+networkSpec :: Spec
+networkSpec = describe "networks" $ do
+  it "has the default block size of each network" $ do
+    map (\n -> (BCHN.defaultOptions n).defaultBlockSize) [bch, bchTest3, bchTest4, bchRegTest]
+      `shouldBe` [32000000, 32000000, 2000000, 32000000]
+  it "has the same timeouts and scores on every network" $
+    mapM_
+      (\n -> (BCHN.defaultOptions n).banScore `shouldBe` 100)
+      [bch, bchTest3, bchTest4, bchRegTest]
+  it "scores a version older than the genesis block of the network" $ do
+    let v = withTime 1296688601
+        score n = scores (snd (feed 1 (Receive (MVersion v)) (open n id Inbound [])))
+    score bch `shouldBe` []
+    score bchTest3 `shouldBe` [20]
+    score bchTest4 `shouldBe` [20]
+    score bchRegTest `shouldBe` [20]
+  it "never finds too little work in headers on regtest" $ do
+    let p = outboundReady bchRegTest
+    (BCHN.defaultOptions bchRegTest).network.minimumChainWork `shouldBe` 0
+    BCHN.isClosing p.st `shouldBe` False
+
+blockSpec :: Spec
+blockSpec = describe "blocks" $ do
+  let g = headerHash bch.genesisHeader
+      gh = bch.genesisHeader
+      child = BlockHeader gh.version g gh.merkle 1700000000 gh.bits gh.nonce
+      childHash = headerHash child
+  it "answers getheaders with headers" $ do
+    let (_, es) = feed 2 (Receive (MGetHeaders (GetHeaders 70016 [g] childHash))) (inboundReady bch [])
+    sentCommands es `shouldBe` [MCHeaders]
+  it "disconnects a getheaders with a locator of more than 101" $ do
+    let gh = GetHeaders 70016 (replicate 102 g) g
+    disconnects (snd (feed 2 (Receive (MGetHeaders gh)) (inboundReady bch []))) `shouldBe` True
+  it "announces getblocks results by inv at the next pass" $ do
+    let p = inboundReady bch []
+        (p1, es1) = feed 2 (Receive (MGetBlocks (GetBlocks 70016 [] g))) p
+        (_, es2) = feed 2 Tick p1
+    sentCommands es1 `shouldBe` []
+    -- only the genesis block is known, so nothing follows the fork
+    sentCommands es2 `shouldNotContain` [MCInv]
+  it "scores more than 2000 headers" $ do
+    let hs = Headers (replicate 2001 (child, VarInt 0))
+    scores (snd (feed 2 (Receive (MHeaders hs)) (inboundReady bch []))) `shouldBe` [20]
+  it "asks for headers when a header does not connect" $ do
+    let lone = child {prev = childHash}
+        (_, es) = feed 2 (Receive (MHeaders (Headers [(lone, VarInt 0)]))) (inboundReady bch [])
+    sentCommands es `shouldBe` [MCGetHeaders]
+  it "scores every tenth header that does not connect" $ do
+    let lone = child {prev = childHash}
+        m = Receive (MHeaders (Headers [(lone, VarInt 0)]))
+        (_, es) = feeds 2 (replicate 10 m) (inboundReady bch [])
+    scores es `shouldBe` [20]
+  it "scores headers that do not follow one another" $ do
+    let hs = Headers [(child, VarInt 0), (child, VarInt 0)]
+    scores (snd (feed 2 (Receive (MHeaders hs)) (inboundReady bch []))) `shouldBe` [20]
+  it "scores invalid headers as validation says" $ do
+    let hs = Headers [(child, VarInt 0)]
+        (_, es) =
+          feedWith (\e -> e {checkHeaders = const (HeadersRejected 50 "high-hash")}) 2 (Receive (MHeaders hs)) $
+            inboundReady bch []
+    scores es `shouldBe` [50]
+  it "asks for headers after an inv of an unknown block" $ do
+    let iv = InvVector InvBlock childHash.get
+        (_, es) = feed 2 (Receive (MInv (Inv [iv]))) (inboundReady bch [])
+    sentCommands es `shouldBe` [MCGetHeaders]
+  it "serves a block it has" $ do
+    let iv = InvVector InvBlock g.get
+        (_, es) = feed 2 (Receive (MGetData (GetData [iv]))) (inboundReady bch [])
+    sent es `shouldBe` [MBlock (genesisBlock bch)]
+  it "sends nothing for an unknown block" $ do
+    let iv = InvVector InvBlock childHash.get
+        (_, es) = feed 2 (Receive (MGetData (GetData [iv]))) (inboundReady bch [])
+    sent es `shouldBe` []
+  it "rejects and scores an invalid block" $ do
+    let blk = Block child []
+        f e = e {checkBlock = const (BlockRejected 0x10 100 "bad-txnmrklroot")}
+        (_, es) = feedWith f 2 (Receive (MBlock blk)) (inboundReady bch [])
+    rejects RejectInvalid es `shouldBe` True
+    scores es `shouldBe` [100]
+    discourages es `shouldBe` True
+  it "does not punish a noban peer for an invalid block" $ do
+    let blk = Block child []
+        f e = e {checkBlock = const (BlockRejected 0x10 100 "bad-txnmrklroot")}
+        (_, es) = feedWith f 2 (Receive (MBlock blk)) (inboundReady bch [PermNoBan])
+    discourages es `shouldBe` False
+  it "asks for headers when a compact block does not connect" $ do
+    let cb = CompactBlock (child {prev = childHash}) 0 [] []
+        (_, es) = feed 2 (Receive (MCompactBlock cb)) (inboundReady bch [])
+    sentCommands es `shouldBe` [MCGetHeaders]
+  it "drops a blocktxn it did not ask for" $ do
+    let (_, es) = feed 2 (Receive (MBlockTxn (BlockTxn childHash []))) (inboundReady bch [])
+    actions es `shouldBe` [Ignore]
+  it "disconnects a getblocktxn without indexes" $ do
+    let (_, es) = feed 2 (Receive (MGetBlockTxn (GetBlockTxn g []))) (inboundReady bch [])
+    disconnects es `shouldBe` True
+  it "takes sendcmpct of version 1 and ignores others" $ do
+    let p = inboundReady bch []
+        (p1, _) = feed 2 (Receive (MSendCompact (SendCompact True 1))) p
+        (_, es) = feed 2 (Receive (MSendCompact (SendCompact True 2))) p
+    BCHN.highBandwidthFrom p1.st `shouldBe` True
+    actions es `shouldBe` [Ignore]
+  it "announces a new block with headers to a peer that sent sendheaders" $ do
+    let info = BlockInfo childHash 1 HaveData True 2 1700000000
+        f e =
+          e
+            { lookupBlock = \h -> if h == childHash then Just info else e.lookupBlock h,
+              headerOf = \h -> if h == childHash then Just child else e.headerOf h,
+              tip = info
+            }
+        known = Receive (MInv (Inv [InvVector InvBlock g.get]))
+        p = fst (feeds 2 [Tick, known] (inboundReady bch []))
+        p1 = fst (feed 2 (Receive MSendHeaders) p)
+        p2 = fst (feedWith f 3 (Notify (NewTip [child])) p1)
+        (_, es) = feedWith f 3 Tick p2
+    BCHN.prefersHeaders p1.st `shouldBe` True
+    sent es `shouldContain` [MHeaders (Headers [(child, VarInt 0)])]
+  it "announces a new block with inv to a peer that did not" $ do
+    let info = BlockInfo childHash 1 HaveData True 2 1700000000
+        f e =
+          e
+            { lookupBlock = \h -> if h == childHash then Just info else e.lookupBlock h,
+              headerOf = \h -> if h == childHash then Just child else e.headerOf h,
+              tip = info
+            }
+        p = fst (feed 2 Tick (inboundReady bch []))
+        p1 = fst (feedWith f 3 (Notify (NewTip [child])) p)
+        (_, es) = feedWith f 3 Tick p1
+    sent es `shouldContain` [MInv (Inv [InvVector InvBlock childHash.get])]
+  it "requests a block the node asks for at the next pass" $ do
+    let p = fst (feed 2 Tick (outboundReady bch))
+        p1 = fst (feed 3 (Notify (RequestBlock childHash)) p)
+        (p2, es) = feed 3 Tick p1
+    sent es `shouldContain` [MGetData (GetData [InvVector InvBlock childHash.get])]
+    BCHN.blocksInFlight p2.st `shouldBe` [childHash]
+  it "sends sendcmpct when the node picks the peer for high bandwidth" $ do
+    let p = fst (feed 2 (Receive (MSendCompact (SendCompact False 1))) (inboundReady bch []))
+        (p1, es1) = feed 3 (Notify (HighBandwidth True)) p
+        (_, es2) = feed 4 (Notify (HighBandwidth False)) p1
+    sent es1 `shouldBe` [MSendCompact (SendCompact True 1)]
+    sent es2 `shouldBe` [MSendCompact (SendCompact False 1)]
+  it "disconnects on the operator's request and on eviction" $ do
+    disconnects (snd (feed 2 (Notify OperatorDisconnect) (inboundReady bch []))) `shouldBe` True
+    disconnects (snd (feed 2 (Notify Evict) (inboundReady bch []))) `shouldBe` True
+  it "disconnects a peer that stalls the download for 2 seconds" $ do
+    let p = fst (feed 2 Tick (inboundReady bch []))
+        p1 = fst (feed (seconds 3) (Notify MarkStalling) p)
+        (_, es) = feed (seconds 6) Tick p1
+    [c.line | Effect (Disconnect Timeout) c <- es] `shouldBe` [4665]
+
+relaySpec :: Spec
+relaySpec = describe "relay" $ do
+  let txid = txHash someTx
+  it "sends feefilter at the first pass" $ do
+    let (_, es) = feed 2 Tick (inboundReady bch [])
+        -- the rounding moves the fee to the bucket below two times in three
+        values = [r | MFeeFilter (FeeFilter r) <- sent es]
+    values `shouldSatisfy` (`elem` [[1000], [1071]])
+  it "sends no feefilter to a forcerelay peer" $ do
+    let (_, es) = feed 2 Tick (inboundReady bch [PermForceRelay])
+    sentCommands es `shouldNotContain` [MCFeeFilter]
+  it "requests an announced transaction" $ do
+    let p = outboundReady bch
+        p1 = fst (feed 2 (Receive (MInv (Inv [InvVector InvTx txid.get]))) p)
+        (p2, es) = feed 2 Tick p1
+    sent es `shouldContain` [MGetData (GetData [InvVector InvTx txid.get])]
+    BCHN.txsInFlight p2.st `shouldBe` [txid]
+  it "waits 2 seconds more for a transaction from an inbound peer" $ do
+    let p = inboundReady bch []
+        p1 = fst (feed (seconds 1) (Receive (MInv (Inv [InvVector InvTx txid.get]))) p)
+        (p2, es1) = feed (seconds 2) Tick p1
+        (_, es2) = feed (seconds 4) Tick p2
+    sentCommands es1 `shouldNotContain` [MCGetData]
+    sentCommands es2 `shouldContain` [MCGetData]
+  it "scores an inv of more than 50000" $ do
+    let ivs = replicate 50001 (InvVector InvTx txid.get)
+    scores (snd (feed 2 (Receive (MInv (Inv ivs))) (inboundReady bch []))) `shouldBe` [20]
+  it "scores a getdata of more than 50000" $ do
+    let ivs = replicate 50001 (InvVector InvTx txid.get)
+    scores (snd (feed 2 (Receive (MGetData (GetData ivs))) (inboundReady bch []))) `shouldBe` [20]
+  it "answers notfound for a transaction it does not have" $ do
+    let iv = InvVector InvTx txid.get
+        (_, es) = feed 2 (Receive (MGetData (GetData [iv]))) (inboundReady bch [])
+    sent es `shouldBe` [MNotFound (NotFound [iv])]
+  it "serves a transaction it announced recently" $ do
+    let iv = InvVector InvTx txid.get
+        f e = e {relayedTx = \h -> if h == txid then Just someTx else Nothing}
+        (_, es) = feedWith f 2 (Receive (MGetData (GetData [iv]))) (inboundReady bch [])
+    sent es `shouldBe` [MTx someTx]
+  it "rejects and scores an invalid transaction" $ do
+    let f e = e {checkTx = const (TxRejected 0x10 100 "bad-txns-vin-empty")}
+        (_, es) = feedWith f 2 (Receive (MTx someTx)) (inboundReady bch [])
+    rejects RejectInvalid es `shouldBe` True
+    scores es `shouldBe` [100]
+  it "rejects a transaction refused by policy without a score" $ do
+    let f e = e {checkTx = const (TxPolicyReject "dust")}
+        (_, es) = feedWith f 2 (Receive (MTx someTx)) (inboundReady bch [])
+    rejects RejectNonStandard es `shouldBe` True
+    scores es `shouldBe` []
+  it "relays an accepted transaction" $ do
+    let f e = e {checkTx = const TxAcceptedToMempool}
+        (_, es) = feedWith f 2 (Receive (MTx someTx)) (inboundReady bch [])
+    [() | Process _ <- actions es] `shouldBe` [()]
+  it "announces a transaction from the mempool when the trickle fires" $ do
+    let f e = e {mempoolTx = \h -> if h == txid then Just someTx else Nothing}
+        p = fst (feed 2 Tick (inboundReady bch [PermNoBan]))
+        p1 = fst (feedWith f 3 (Notify (TxAccepted someTx)) p)
+        (_, es) = feedWith f 3 Tick p1
+    sent es `shouldContain` [MInv (Inv [InvVector InvTx txid.get])]
+  it "ends the request of a transaction on notfound" $ do
+    let p = outboundReady bch
+        p1 = fst (feed 2 (Receive (MInv (Inv [InvVector InvTx txid.get]))) p)
+        p2 = fst (feed 2 Tick p1)
+        (p3, _) = feed 3 (Receive (MNotFound (NotFound [InvVector InvTx txid.get]))) p2
+    BCHN.txsInFlight p3.st `shouldBe` []
+  it "scores an invalid double-spend proof, but not from noban" $ do
+    let m = Receive (MOther "dsproof-beta" "x")
+    scores (snd (feed 2 m (inboundReady bch []))) `shouldBe` [10]
+    scores (snd (feed 2 m (inboundReady bch [PermNoBan]))) `shouldBe` []
+  it "keeps the feefilter of the peer and ignores a bad one" $ do
+    let (_, es1) = feed 2 (Receive (MFeeFilter (FeeFilter 5000))) (inboundReady bch [])
+        (_, es2) = feed 2 (Receive (MFeeFilter (FeeFilter maxBound))) (inboundReady bch [])
+    es1 `shouldBe` []
+    actions es2 `shouldBe` [Ignore]
+  it "scores an oversized filterload" $ do
+    let f = BloomFilter (S.replicate 36001 0) 1 0 BloomUpdateNone
+    scores (snd (feed 2 (Receive (MFilterLoad (FilterLoad f))) (inboundReady bch []))) `shouldBe` [100]
+  it "disconnects a filterload before version when it offers no bloom" $ do
+    let f = BloomFilter (S.replicate 10 0) 1 0 BloomUpdateNone
+        p = open bch (\o -> o {BCHN.peerBloomFilters = False}) Inbound []
+        (_, es) = feed 1 (Receive (MFilterLoad (FilterLoad f))) p
+    disconnects es `shouldBe` True
+    scores es `shouldBe` []
+  it "scores a filterload after version when it offers no bloom" $ do
+    let f = BloomFilter (S.replicate 10 0) 1 0 BloomUpdateNone
+        noBloom o = o {BCHN.peerBloomFilters = False}
+        p = fst (feed 1 (Receive (MVersion peerVersion)) (open bch noBloom Inbound []))
+        (_, es) = feed 1 (Receive (MFilterLoad (FilterLoad f))) p
+    scores es `shouldBe` [100]
+  it "scores an oversized filteradd" $ do
+    let m = Receive (MFilterAdd (FilterAdd (B.replicate 521 0)))
+    scores (snd (feed 2 m (inboundReady bch []))) `shouldBe` [100]
+  it "turns on transaction relay with filterclear" $ do
+    let v = withRelay False
+        p = fst (feeds 1 [Receive (MVersion v), Receive MVerAck] (open bch id Inbound []))
+        (p1, _) = feed 2 (Receive MFilterClear) p
+    BCHN.relaysTransactions p.st `shouldBe` False
+    BCHN.relaysTransactions p1.st `shouldBe` True
+  it "scores an addr of more than 1000" $ do
+    let a = (1700000000, NetworkAddress 1 (sockToHostAddress (SockAddrInet 8333 0x01020304)))
+        m = Receive (MAddr (Addr (replicate 1001 a)))
+    scores (snd (feed 2 m (inboundReady bch []))) `shouldBe` [20]
+  it "takes addrv2 and disconnects an address fetch after it" $ do
+    let a = NetworkAddressV2 1700000000 1 AddrIPv4 (B.pack [1, 2, 3, 4]) 8333
+        p = fst (feeds 1 [Tick, Receive (MVersion peerVersion), Receive MVerAck] (open bch id AddrFetch []))
+        (_, es) = feed 2 (Receive (MAddrV2 (AddrV2 [a]))) p
+    disconnects es `shouldBe` True
+  it "answers getaddr once, and only from an inbound peer" $ do
+    let a = NetworkAddressV2 1700000000 1 AddrIPv4 (B.pack [1, 2, 3, 4]) 8333
+        f e = e {addressesForPeer = const [a]}
+        p = fst (feed 2 Tick (inboundReady bch []))
+        (p1, _) = feedWith f 3 (Receive MGetAddr) p
+        (_, es1) = feedWith f (seconds 1000) Tick p1
+        (_, es2) = feedWith f 4 (Receive MGetAddr) p1
+        (_, es3) = feedWith f 3 (Receive MGetAddr) (outboundReady bch)
+    sentCommands es1 `shouldContain` [MCAddr]
+    actions es2 `shouldBe` [Ignore]
+    actions es3 `shouldBe` [Ignore]
diff --git a/test/Haskoin/Network/Protocol/BitcoinCoreSpec.hs b/test/Haskoin/Network/Protocol/BitcoinCoreSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Haskoin/Network/Protocol/BitcoinCoreSpec.hs
@@ -0,0 +1,647 @@
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoFieldSelectors #-}
+{-# OPTIONS_GHC -Wno-deprecations #-}
+
+-- | Scenario tests of the protocol machine of Bitcoin Core 32.1: each one
+-- drives the machine through 'step' and checks the effects, and where it
+-- matters the upstream line that decided them.
+module Haskoin.Network.Protocol.BitcoinCoreSpec (spec) where
+
+import Data.ByteString qualified as B
+import Data.Int (Int32)
+import Data.List (foldl')
+import Data.Maybe (isJust, isNothing)
+import Data.Sequence qualified as Seq
+import Data.Set qualified as Set
+import Data.String (IsString, fromString)
+import Data.Word (Word32, Word64, Word8)
+import Haskoin.Block
+import Haskoin.Block.Headers (headerWork)
+import Haskoin.Network
+import Haskoin.Network.Protocol.BitcoinCore
+import Haskoin.Network.Protocol.Types
+import Haskoin.Transaction
+import Network.Socket (SockAddr (..))
+import Test.Hspec
+
+-- * Fixtures
+
+t0 :: Micros
+t0 = seconds 1700000000
+
+genesisInfo :: Network -> BlockInfo
+genesisInfo net =
+  BlockInfo
+    { hash = headerHash net.genesisHeader,
+      height = 0,
+      status = HaveData,
+      inActiveChain = True,
+      work = headerWork net.genesisHeader,
+      time = net.genesisHeader.timestamp
+    }
+
+mkEnv :: Network -> Env
+mkEnv net =
+  let gi = genesisInfo net
+      e = defaultEnv gi (Block net.genesisHeader [net.genesisTx]) t0
+   in e {headerOf = \h -> if h == gi.hash then Just net.genesisHeader else Nothing}
+
+at :: Micros -> Env -> Env
+at t e = e {now = t}
+
+setup :: ConnectionType -> [Permission] -> Setup
+setup ct ps =
+  Setup
+    { connectionType = ct,
+      permissions = Set.fromList ps,
+      peerNetwork = AddrIPv4,
+      peerIsLocal = False,
+      transport = TransportV1,
+      openedAt = t0,
+      seed = 7
+    }
+
+zeroAddr :: NetworkAddress
+zeroAddr = NetworkAddress 0 (sockToHostAddress (SockAddrInet6 0 0 (0, 0, 0, 0) 0))
+
+fullServices :: Word64
+fullServices = nodeNetwork + nodeWitness
+
+ver :: Int32 -> Word64 -> Bool -> Version
+ver v svc r =
+  Version
+    { version = v,
+      services = svc,
+      timestamp = 0,
+      addrRecv = zeroAddr,
+      addrSend = zeroAddr,
+      nonce = 42,
+      userAgent = VarString "/test/",
+      startHeight = 0,
+      relay = r
+    }
+
+peerVer :: Version
+peerVer = ver 70017 fullServices True
+
+-- | A header like the genesis header of a network, with another parent and
+-- nonce.
+headerAfter :: Network -> BlockHash -> Word32 -> BlockHeader
+headerAfter net p n =
+  let g = net.genesisHeader
+   in BlockHeader g.version p g.merkle g.timestamp g.bits n
+
+zero :: BlockHash
+zero = hashN 0
+
+-- | A made-up hash that ends in a digit.
+hashN :: (IsString a) => Int -> a
+hashN n = fromString (replicate 63 '0' ++ show (n `mod` 10))
+
+-- | A public IPv4 address that offers full services.
+ipv4 :: [Word8] -> NetworkAddressV2
+ipv4 bs =
+  NetworkAddressV2
+    { time = 0,
+      services = fullServices,
+      network = AddrIPv4,
+      address = B.pack bs,
+      port = 8333
+    }
+
+-- | Feed inputs one after another, collecting all effects.
+run :: Options -> Env -> State -> [Input] -> (State, [Effect])
+run o e s0 = foldl' go (s0, [])
+  where
+    go (s, acc) i = let (s', es) = step o e s i in (s', acc ++ es)
+
+sent :: [Effect] -> [Message]
+sent es = [m | Effect (Send m) _ <- es]
+
+actions :: [Effect] -> [Action]
+actions = map (.action)
+
+lines' :: [Effect] -> [Int]
+lines' = map (.because.line)
+
+isDisc :: Action -> Bool
+isDisc (Disconnect _) = True
+isDisc _ = False
+
+commands :: [Message] -> [MessageCommand]
+commands = map msgType
+
+-- | An inbound connection with the handshake done.
+inboundReady :: Options -> Env -> [Permission] -> State
+inboundReady o e ps =
+  fst $ run o e (start o (setup Inbound ps)) [Receive (MVersion peerVer), Receive MVerAck]
+
+-- | An outbound full relay connection with the handshake done.
+outboundReady :: Options -> Env -> State
+outboundReady o e =
+  fst $
+    run
+      o
+      e
+      (start o (setup OutboundFullRelay []))
+      [Tick, Receive (MVersion peerVer), Receive MVerAck]
+
+btcO :: Options
+btcO = defaultOptions btc
+
+btcE :: Env
+btcE = mkEnv btc
+
+hugeInv :: Message
+hugeInv = MInv (Inv (replicate 50001 (InvVector InvBlock (hashN 1))))
+
+aTx :: Tx
+aTx = btc.genesisTx
+
+spec :: Spec
+spec = do
+  handshakeSpec
+  pingSpec
+  timeoutSpec
+  misbehaviourSpec
+  permissionSpec
+  networkSpec
+  messageSpec
+  notificationSpec
+
+handshakeSpec :: Spec
+handshakeSpec = describe "handshake" $ do
+  it "answers an inbound version in upstream order" $ do
+    let s0 = start btcO (setup Inbound [])
+        (s1, es) = step btcO btcE s0 (Receive (MVersion peerVer))
+    commands (sent es) `shouldBe` [MCVersion, MCWtxidRelay, MCSendAddrV2, MCVerAck]
+    versionReceived s1 `shouldBe` True
+    handshakeComplete s1 `shouldBe` False
+    let (s2, es2) = step btcO btcE s1 (Receive MVerAck)
+    commands (sent es2) `shouldBe` [MCSendCmpct]
+    handshakeComplete s2 `shouldBe` True
+  it "sends its version first on an outbound connection" $ do
+    let s0 = start btcO (setup OutboundFullRelay [])
+        (s1, es) = step btcO btcE s0 Tick
+    commands (sent es) `shouldBe` [MCVersion]
+    let (_, es2) = step btcO btcE s1 (Receive (MVersion peerVer))
+    commands (sent es2) `shouldBe` [MCWtxidRelay, MCSendAddrV2, MCVerAck, MCGetAddr]
+  it "sends its version before processing an early outbound message" $ do
+    let s0 = start btcO (setup OutboundFullRelay [])
+        (_, es) = step btcO btcE s0 (Receive (MVersion peerVer))
+    take 1 (commands (sent es)) `shouldBe` [MCVersion]
+  it "drops any message before version" $ do
+    let (_, es) = step btcO btcE (start btcO (setup Inbound [])) (Receive (MPing (Ping 1)))
+    actions es `shouldBe` [Ignore]
+    lines' es `shouldBe` [4076]
+  it "drops a ping between version and verack" $ do
+    let (s1, _) = step btcO btcE (start btcO (setup Inbound [])) (Receive (MVersion peerVer))
+        (_, es) = step btcO btcE s1 (Receive (MPing (Ping 1)))
+    lines' es `shouldBe` [4321]
+  it "ignores a second version and a second verack" $ do
+    let s = inboundReady btcO btcE []
+        (_, es1) = step btcO btcE s (Receive (MVersion peerVer))
+        (_, es2) = step btcO btcE s (Receive MVerAck)
+    lines' es1 `shouldBe` [3839]
+    lines' es2 `shouldBe` [4082]
+  it "disconnects an obsolete version" $ do
+    let (s, es) = step btcO btcE (start btcO (setup Inbound [])) (Receive (MVersion (ver 31799 fullServices True)))
+    actions es `shouldBe` [Disconnect ProtocolViolation]
+    isDisconnected s `shouldBe` True
+  it "disconnects an outbound peer without the expected services" $ do
+    let s0 = start btcO (setup OutboundFullRelay [])
+        (_, es) = run btcO btcE s0 [Tick, Receive (MVersion (ver 70017 nodeWitness True))]
+    lines' (filter (isDisc . (.action)) es) `shouldBe` [3871]
+  it "accepts a manual peer without services" $ do
+    let s0 = start btcO (setup Manual [])
+        (s, _) = run btcO btcE s0 [Tick, Receive (MVersion (ver 70017 0 True))]
+    isDisconnected s `shouldBe` False
+  it "disconnects a connection to itself" $ do
+    let e = btcE {ownNonce = (== 42)}
+        (_, es) = step btcO e (start btcO (setup Inbound [])) (Receive (MVersion peerVer))
+    lines' es `shouldBe` [3904]
+  it "ends a feeler after the version" $ do
+    let s0 = start btcO (setup Feeler [])
+        (s, es) = run btcO btcE s0 [Tick, Receive (MVersion peerVer)]
+    last (actions es) `shouldBe` Disconnect Done
+    isDisconnected s `shouldBe` True
+  it "sends no getaddr and relay off to a block-relay-only peer" $ do
+    let s0 = start btcO (setup BlockRelayOnly [])
+        (_, es) = run btcO btcE s0 [Tick, Receive (MVersion peerVer)]
+    [v.relay | MVersion v <- sent es] `shouldBe` [False]
+    MCGetAddr `elem` commands (sent es) `shouldBe` False
+  it "sends the final alert to an old peer and no BIP 155 or 339 messages" $ do
+    let (_, es) = step btcO btcE (start btcO (setup Inbound [])) (Receive (MVersion (ver 70012 fullServices True)))
+    commands (sent es) `shouldBe` [MCVersion, MCVerAck, MCAlert]
+  it "closes the connection on wtxidrelay or sendaddrv2 after verack" $ do
+    let s = inboundReady btcO btcE []
+    lines' (snd (step btcO btcE s (Receive MWtxidRelay))) `shouldBe` [4196]
+    lines' (snd (step btcO btcE s (Receive MSendAddrV2))) `shouldBe` [4218]
+  it "records wtxidrelay and sendaddrv2 before verack" $ do
+    let (s1, _) = step btcO btcE (start btcO (setup Inbound [])) (Receive (MVersion peerVer))
+        (s2, _) = run btcO btcE s1 [Receive MWtxidRelay, Receive MSendAddrV2]
+        (_, es) = step btcO btcE s2 (Receive MWtxidRelay)
+    wtxidRelayOf s2 `shouldBe` True
+    wantsAddrV2Of s2 `shouldBe` True
+    lines' es `shouldBe` [4204]
+  it "checks the feature message" $ do
+    let (s1, _) = step btcO btcE (start btcO (setup Inbound [])) (Receive (MVersion peerVer))
+        good = B.concat [B.singleton 4, "abcd", B.singleton 0]
+        bad = B.concat [B.singleton 2, "ab", B.singleton 0]
+    lines' (snd (step btcO btcE s1 (Receive (MOther "feature" good)))) `shouldBe` [4260]
+    lines' (snd (step btcO btcE s1 (Receive (MOther "feature" bad)))) `shouldBe` [4250]
+    let s = inboundReady btcO btcE []
+    lines' (snd (step btcO btcE s (Receive (MOther "feature" good)))) `shouldBe` [4229]
+  it "negotiates Erlay only when enabled" $ do
+    let (s1, _) = step btcO btcE (start btcO (setup Inbound [])) (Receive (MVersion peerVer))
+    lines' (snd (step btcO btcE s1 (Receive (MSendTxRcncl (SendTxRcncl 1 5))))) `shouldBe` [4269]
+    let o = btcO {txReconciliation = True}
+        (r1, es1) = step o btcE (start o (setup Inbound [])) (Receive (MVersion peerVer))
+    MCSendTxRcncl `elem` commands (sent es1) `shouldBe` True
+    let (r2, es2) = step o btcE r1 (Receive (MSendTxRcncl (SendTxRcncl 1 5)))
+        (_, es3) = step o btcE r2 (Receive (MSendTxRcncl (SendTxRcncl 1 5)))
+    es2 `shouldBe` []
+    lines' es3 `shouldBe` [4310]
+  it "handles a private broadcast connection" $ do
+    let s0 = start btcO (setup PrivateBroadcast [])
+        (_, esNo) = run btcO btcE s0 [Tick, Receive (MVersion (ver 70017 fullServices False))]
+    lines' (filter (isDisc . (.action)) esNo) `shouldBe` [3961]
+    let e = btcE {privateBroadcastTx = Just aTx}
+        (s1, es) = run btcO e s0 [Tick, Receive (MVersion peerVer), Receive MVerAck]
+    commands (sent es) `shouldBe` [MCVersion, MCVerAck, MCInv]
+    [v.version | MVersion v <- sent es] `shouldBe` [70016]
+    let (_, es2) = step btcO e s1 (Receive (MGetData (GetData [InvVector InvTx (txHash aTx).get])))
+    commands (sent es2) `shouldBe` [MCTx, MCPing]
+    let (_, es3) = step btcO e s1 (Receive (MPing (Ping 3)))
+    lines' es3 `shouldBe` [4327]
+
+pingSpec :: Spec
+pingSpec = describe "ping" $ do
+  it "pings after the handshake and accepts the pong" $ do
+    let s = inboundReady btcO btcE []
+        (s1, es) = step btcO btcE s Tick
+        nonces = [n | MPing (Ping n) <- sent es]
+    isJust (pingOutstanding s1) `shouldBe` True
+    case nonces of
+      [n] -> do
+        let (s2, _) = step btcO btcE s1 (Receive (MPong (Pong n)))
+        pingOutstanding s2 `shouldBe` Nothing
+      _ -> expectationFailure "expected one ping"
+
+  it "answers a ping with a pong of the same nonce" $ do
+    let s = inboundReady btcO btcE []
+    sent (snd (step btcO btcE s (Receive (MPing (Ping 99))))) `shouldBe` [MPong (Pong 99)]
+  it "handles wrong pongs as upstream does" $ do
+    let s = inboundReady btcO btcE []
+        (s1, _) = step btcO btcE s Tick
+    lines' (snd (step btcO btcE s (Receive (MPong (Pong 5))))) `shouldBe` [5929]
+    let (s2, es2) = step btcO btcE s1 (Receive (MPong (Pong 12345)))
+    lines' es2 `shouldBe` [5921]
+    isJust (pingOutstanding s2) `shouldBe` True
+    let (s3, es3) = step btcO btcE s1 (Receive (MPong (Pong 0)))
+    lines' es3 `shouldBe` [5925]
+    pingOutstanding s3 `shouldBe` Nothing
+  it "disconnects after 20 minutes without a pong" $ do
+    let s = inboundReady btcO btcE []
+        (s1, _) = step btcO btcE s Tick
+        later = at (t0 + seconds (21 * 60)) btcE
+        (s2, es) = step btcO later s1 (Receive (MPing (Ping 1)))
+        (_, es2) = step btcO later s2 Tick
+    lines' (es ++ es2) `shouldContain` [5706]
+
+timeoutSpec :: Spec
+timeoutSpec = describe "timers" $ do
+  it "closes a handshake that takes more than 60 seconds" $ do
+    let (s1, _) = step btcO btcE (start btcO (setup Inbound [])) (Receive (MVersion peerVer))
+        (_, es) = step btcO (at (t0 + seconds 61) btcE) s1 Tick
+    lines' es `shouldBe` [2101]
+  it "closes a silent connection after the peer timeout" $ do
+    let (_, es) = step btcO (at (t0 + seconds 61) btcE) (start btcO (setup Inbound [])) Tick
+    lines' es `shouldBe` [2067]
+  it "keeps a quiet connection within the peer timeout" $ do
+    let (_, es) = step btcO (at (t0 + seconds 59) btcE) (start btcO (setup Inbound [])) Tick
+    es `shouldBe` []
+  it "ends an address fetch connection after 300 seconds" $ do
+    let s0 = start btcO (setup AddrFetch [])
+        (s1, _) = run btcO btcE s0 [Tick, Receive (MVersion peerVer), Receive MVerAck]
+        (_, es) = step btcO (at (t0 + seconds 301) btcE) (s1 {- recent traffic -}) (Receive (MPing (Ping 1)))
+        (_, es2) = step btcO (at (t0 + seconds 301) btcE) s1 Tick
+    length es `shouldSatisfy` (> 0)
+    lines' (filter (isDisc . (.action)) es2) `shouldBe` [6100]
+
+misbehaviourSpec :: Spec
+misbehaviourSpec = describe "misbehaviour" $ do
+  it "discourages a peer that sends an oversized inv" $ do
+    let s = inboundReady btcO btcE []
+        (s1, es) = step btcO btcE s (Receive hugeInv)
+    actions es `shouldBe` [Ignore, Discourage, Disconnect Misbehaviour]
+    (.because.line) (es !! 1) `shouldBe` 4352
+    isDisconnected s1 `shouldBe` True
+  it "never punishes a noban peer" $ do
+    let s = inboundReady btcO btcE [PermNoBan]
+        (s1, es) = step btcO btcE s (Receive hugeInv)
+    actions es `shouldBe` [Ignore]
+    isDisconnected s1 `shouldBe` False
+  it "never punishes a manual connection" $ do
+    let s0 = start btcO (setup Manual [])
+        (s, _) = run btcO btcE s0 [Tick, Receive (MVersion peerVer), Receive MVerAck]
+        (s1, _) = step btcO btcE s (Receive hugeInv)
+    isDisconnected s1 `shouldBe` False
+  it "disconnects a local or inbound Tor peer without discouraging it" $ do
+    let local = (setup Inbound []) {peerIsLocal = True}
+        tor = (setup Inbound []) {peerNetwork = AddrTorV3}
+    mapM_
+      ( \su -> do
+          let (s, _) = run btcO btcE (start btcO su) [Receive (MVersion peerVer), Receive MVerAck]
+              (_, es) = step btcO btcE s (Receive hugeInv)
+          actions es `shouldBe` [Ignore, Disconnect Misbehaviour]
+      )
+      [local, tor]
+  it "discourages oversized headers" $ do
+    let s = inboundReady btcO btcE []
+        hdr = (btc.genesisHeader, VarInt 0)
+        (_, es) = step btcO btcE s (Receive (MHeaders (Headers (replicate 2001 hdr))))
+    Discourage `elem` actions es `shouldBe` True
+  it "discourages an announce byte above 1 in sendcmpct, even before verack" $ do
+    let (s1, _) = step btcO btcE (start btcO (setup Inbound [])) (Receive (MVersion peerVer))
+        payload = B.concat [B.singleton 2, B.replicate 8 0]
+        (_, es) = step btcO btcE s1 (Receive (MOther "sendcmpct" payload))
+    actions es `shouldBe` [Ignore, Discourage, Disconnect Misbehaviour]
+
+permissionSpec :: Spec
+permissionSpec = describe "permissions and blocks-only" $ do
+  it "expands a bare whitelist" $ do
+    expandPermissions btcO (Set.fromList [PermImplicit])
+      `shouldBe` Set.fromList [PermNoBan, PermDownload, PermMempool, PermRelay]
+    let o = btcO {blocksOnly = True}
+    expandPermissions o (Set.fromList [PermImplicit])
+      `shouldBe` Set.fromList [PermNoBan, PermDownload, PermMempool]
+    let f = btcO {whitelistForceRelay = True}
+    expandPermissions f (Set.fromList [PermImplicit])
+      `shouldBe` Set.fromList [PermNoBan, PermDownload, PermMempool, PermRelay, PermForceRelay]
+  it "gives noban the download permission" $
+    expandPermissions btcO (Set.fromList [PermNoBan]) `shouldBe` Set.fromList [PermNoBan, PermDownload]
+  it "tells peers not to relay in blocks-only mode, unless they have relay" $ do
+    let o = btcO {blocksOnly = True}
+        relayOf ps =
+          let (_, es) = step o btcE (start o (setup Inbound ps)) (Receive (MVersion peerVer))
+           in [v.relay | MVersion v <- sent es]
+    relayOf [] `shouldBe` [False]
+    relayOf [PermRelay] `shouldBe` [True]
+  it "disconnects a peer that sends a transaction in blocks-only mode" $ do
+    let o = btcO {blocksOnly = True}
+        e = btcE {initialBlockDownload = False}
+        s = inboundReady o e []
+    lines' (snd (step o e s (Receive (MTx aTx)))) `shouldBe` [4711]
+    let r = inboundReady o e [PermRelay]
+    isDisconnected (fst (step o e r (Receive (MTx aTx)))) `shouldBe` False
+  it "offers NODE_BLOOM to a peer with the bloomfilter permission" $ do
+    let s = start btcO (setup Inbound [PermBloomFilter])
+    ourServicesOf s `shouldSatisfy` (\x -> x `div` nodeBloom `mod` 2 == 1)
+
+networkSpec :: Spec
+networkSpec = describe "networks" $ do
+  it "takes the minimum chain work of each network" $
+    mapM_
+      (\n -> (defaultOptions n).minimumChainWork `shouldBe` n.minimumChainWork)
+      [btc, btcTest, btcTest4, btcRegTest]
+  it "has the same defaults on the four networks otherwise" $
+    mapM_
+      ( \n -> do
+          let o = defaultOptions n
+          (o.blocksOnly, o.peerBloomFilters, o.txReconciliation, o.listen, o.peerTimeout)
+            `shouldBe` (False, False, False, True, seconds 60)
+      )
+      [btc, btcTest, btcTest4, btcRegTest]
+  it "sends empty headers while the tip has too little work, except on regtest" $ do
+    let check n expected = do
+          let o = defaultOptions n
+              e = mkEnv n
+              s = inboundReady o e []
+              gh' = GetHeaders 70016 [headerHash n.genesisHeader] zero
+          lines' (snd (step o e s (Receive (MGetHeaders gh')))) `shouldBe` [expected]
+    check btc 4655
+    check btcTest 4655
+    check btcTest4 4655
+    check btcRegTest 4704
+  it "lets a download peer have headers while the tip has too little work" $ do
+    let s = inboundReady btcO btcE [PermDownload]
+        gh = GetHeaders 70016 [headerHash btc.genesisHeader] zero
+    lines' (snd (step btcO btcE s (Receive (MGetHeaders gh)))) `shouldBe` [4704]
+
+messageSpec :: Spec
+messageSpec = describe "messages" $ do
+  let s = inboundReady btcO btcE []
+      reg = defaultOptions btcRegTest
+      regE = mkEnv btcRegTest
+  it "drops a bad checksum and closes on a wrong magic" $ do
+    lines' (snd (step btcO btcE s (BadFrame (BadChecksum "ping")))) `shouldBe` [836]
+    actions (snd (step btcO btcE s (BadFrame (WrongMagic 1)))) `shouldBe` [Disconnect ProtocolViolation]
+    actions (snd (step btcO btcE s (BadFrame (Oversized "block" 5000000)))) `shouldBe` [Disconnect ProtocolViolation]
+    lines' (snd (step btcO btcE s (BadFrame (BadPayload "inv")))) `shouldBe` [5493]
+  it "ignores unknown and retired messages" $ do
+    lines' (snd (step btcO btcE s (Receive (MOther "dsproof-beta" "x")))) `shouldBe` [5360]
+    let rej = MReject (Reject MCTx RejectInvalid (VarString "") Nothing)
+    lines' (snd (step btcO btcE s (Receive rej))) `shouldBe` [5360]
+  it "records sendheaders" $
+    prefersHeadersOf (fst (step btcO btcE s (Receive MSendHeaders))) `shouldBe` True
+  it "records sendcmpct of version 2 only" $ do
+    compactBlocksOf (fst (step btcO btcE s (Receive (MSendCompact (SendCompact True 2)))))
+      `shouldBe` (True, True, False)
+    lines' (snd (step btcO btcE s (Receive (MSendCompact (SendCompact True 1))))) `shouldBe` [4178]
+  it "closes on a getheaders locator over 101 entries" $ do
+    let gh = GetHeaders 70016 (replicate 102 (hashN 1)) zero
+    lines' (snd (step btcO btcE s (Receive (MGetHeaders gh)))) `shouldBe` [4636]
+  it "asks for headers when a header does not connect" $ do
+    let r = inboundReady reg regE []
+        hdr = headerAfter btcRegTest (hashN 9) 1
+        (_, es) = step reg regE r (Receive (MHeaders (Headers [(hdr, VarInt 0)])))
+    lines' es `shouldBe` [2903]
+  it "takes an empty headers message silently" $
+    snd (step btcO btcE s (Receive (MHeaders (Headers [])))) `shouldBe` []
+  it "answers getblocks with an inv at the next pass" $ do
+    let e = regE {blockAtHeight = \n -> if n == 0 then Just (genesisInfo btcRegTest) else Nothing}
+        r = inboundReady reg e []
+        (r1, es) = step reg e r (Receive (MGetBlocks (GetBlocks 70016 [] zero)))
+    es `shouldBe` []
+    isDisconnected r1 `shouldBe` False
+  it "serves a transaction or a notfound" $ do
+    let e = btcE {mempoolTx = \h -> if h == txHash aTx then Just aTx else Nothing}
+        r = inboundReady btcO e []
+        have = InvVector InvTx (txHash aTx).get
+        lack = InvVector InvTx (hashN 2)
+        (_, es) = step btcO e r (Receive (MGetData (GetData [have, lack])))
+    commands (sent es) `shouldBe` [MCTx, MCNotFound]
+  it "serves a block" $ do
+    let r = inboundReady btcO btcE []
+        iv = InvVector InvWitnessBlock (headerHash btc.genesisHeader).get
+    commands (sent (snd (step btcO btcE r (Receive (MGetData (GetData [iv])))))) `shouldBe` [MCBlock]
+  it "discourages a mutated block" $ do
+    let e = btcE {checkBlock = const BlockMutated}
+        r = inboundReady btcO e []
+        blk = Block (headerAfter btc (headerHash btc.genesisHeader) 1) []
+    Discourage `elem` actions (snd (step btcO e r (Receive (MBlock blk)))) `shouldBe` True
+  it "punishes an invalid block but not a duplicate" $ do
+    let bad = btcE {checkBlock = const (BlockInvalid True "bad-txns")}
+        dup = btcE {checkBlock = const BlockDuplicate}
+        blk = Block btc.genesisHeader []
+    Discourage `elem` actions (snd (step btcO bad (inboundReady btcO bad []) (Receive (MBlock blk)))) `shouldBe` True
+    Discourage `elem` actions (snd (step btcO dup (inboundReady btcO dup []) (Receive (MBlock blk)))) `shouldBe` False
+  it "ignores a cmpctblock from a peer that did not offer compact blocks" $ do
+    let cb = CompactBlock btc.genesisHeader 0 [] []
+    lines' (snd (step btcO btcE s (Receive (MCompactBlock cb)))) `shouldBe` [4799]
+  it "closes on an empty getblocktxn and ignores an unexpected blocktxn" $ do
+    let h = headerHash btc.genesisHeader
+    lines' (snd (step btcO btcE s (Receive (MGetBlockTxn (GetBlockTxn h []))))) `shouldBe` [4567]
+    lines' (snd (step btcO btcE s (Receive (MBlockTxn (BlockTxn h []))))) `shouldBe` [3721]
+  it "closes on BIP 157 requests without -peerblockfilters" $ do
+    let h = headerHash btc.genesisHeader
+    lines' (snd (step btcO btcE s (Receive (MGetCFilters (GetCFilters 0 0 h))))) `shouldBe` [3530]
+    lines' (snd (step btcO btcE s (Receive (MGetCFHeaders (GetCFHeaders 0 0 h))))) `shouldBe` [3530]
+    lines' (snd (step btcO btcE s (Receive (MGetCFCheckpt (GetCFCheckpt 0 h))))) `shouldBe` [3530]
+  it "drops transactions during initial block download" $
+    lines' (snd (step btcO btcE s (Receive (MTx aTx)))) `shouldBe` [4718]
+  it "hands a valid transaction to the node" $ do
+    let e = btcE {initialBlockDownload = False, checkTx = const TxAcceptedToMempool}
+    actions (snd (step btcO e (inboundReady btcO e []) (Receive (MTx aTx))))
+      `shouldBe` [Process "transaction accepted"]
+  it "passes notfound to the transaction download" $ do
+    let nf = NotFound [InvVector InvTx (txHash aTx).get]
+    lines' (snd (step btcO btcE s (Receive (MNotFound nf)))) `shouldBe` [5355]
+  it "refuses mempool without bloom filters, quietly for noban" $ do
+    lines' (snd (step btcO btcE s (Receive MMempool))) `shouldBe` [5195]
+    let nb = inboundReady btcO btcE [PermNoBan]
+    lines' (snd (step btcO btcE nb (Receive MMempool))) `shouldBe` [5197]
+    let mp = inboundReady btcO btcE [PermMempool]
+    snd (step btcO btcE mp (Receive MMempool)) `shouldBe` []
+  it "records a fee filter" $
+    feeFilterOf (fst (step btcO btcE s (Receive (MFeeFilter (FeeFilter 2000))))) `shouldBe` Just 2000
+  it "checks the Bloom filter messages" $ do
+    let bf = bloomCreate 10 0.001 0 BloomUpdateNone
+    lines' (snd (step btcO btcE s (Receive (MFilterLoad (FilterLoad bf))))) `shouldBe` [5245]
+    lines' (snd (step btcO btcE s (Receive (MFilterAdd (FilterAdd "abc"))))) `shouldBe` [5271]
+    lines' (snd (step btcO btcE s (Receive MFilterClear))) `shouldBe` [5299]
+    let o = btcO {peerBloomFilters = True}
+        b = inboundReady o btcE []
+        big = BloomFilter (Seq.replicate 36001 0) 1 0 BloomUpdateNone
+    take 1 (lines' (snd (step o btcE b (Receive (MFilterLoad (FilterLoad big)))))) `shouldBe` [5254]
+    take 1 (lines' (snd (step o btcE b (Receive (MFilterAdd (FilterAdd "abc")))))) `shouldBe` [5291]
+    let (b1, es1) = step o btcE b (Receive (MFilterLoad (FilterLoad bf)))
+    es1 `shouldBe` []
+    txRelayEnabled b1 `shouldBe` True
+    snd (step o btcE b1 (Receive (MFilterAdd (FilterAdd "abc")))) `shouldBe` []
+    snd (step o btcE b1 (Receive MFilterClear)) `shouldBe` []
+  it "rate-limits and checks addresses" $ do
+    let a = ipv4 [8, 8, 8, 8]
+        (_, es) = step btcO btcE s (Receive (MAddrV2 (AddrV2 (replicate 1001 a))))
+    take 1 (lines' es) `shouldBe` [5984]
+    Discourage `elem` actions es `shouldBe` True
+    let s0 = start btcO (setup BlockRelayOnly [])
+        (br, _) = run btcO btcE s0 [Tick, Receive (MVersion peerVer), Receive MVerAck]
+    lines' (snd (step btcO btcE br (Receive (MAddrV2 (AddrV2 [a]))))) `shouldBe` [5978]
+    let f0 = start btcO (setup AddrFetch [])
+        (af, _) = run btcO btcE f0 [Tick, Receive (MVersion peerVer), Receive MVerAck]
+        a2 = ipv4 [8, 8, 4, 4]
+        (af1, es2) = step btcO btcE af (Receive (MAddrV2 (AddrV2 [a, a2])))
+    last (lines' es2) `shouldBe` 6055
+    isDisconnected af1 `shouldBe` True
+  it "answers getaddr once, from inbound peers only" $ do
+    let a = ipv4 [8, 8, 8, 8]
+        e = btcE {addressesForPeer = const [a]}
+        r = inboundReady btcO e []
+        (r1, es1) = step btcO e r (Receive MGetAddr)
+    es1 `shouldBe` []
+    addrRelayEnabled r1 `shouldBe` True
+    commands (sent (snd (step btcO e r1 Tick))) `shouldContain` [MCAddr]
+    lines' (snd (step btcO e r1 (Receive MGetAddr))) `shouldBe` [5169]
+    let ob = outboundReady btcO e
+    lines' (snd (step btcO e ob (Receive MGetAddr))) `shouldBe` [5158]
+  it "disconnects a transaction inv on a block-relay-only connection" $ do
+    let s0 = start btcO (setup BlockRelayOnly [])
+        (br, _) = run btcO btcE s0 [Tick, Receive (MVersion peerVer), Receive MVerAck]
+        inv = MInv (Inv [InvVector InvTx (txHash aTx).get])
+    lines' (snd (step btcO btcE br (Receive inv))) `shouldBe` [4394]
+  it "asks for headers after a block inv" $ do
+    let inv = MInv (Inv [InvVector InvBlock (hashN 5)])
+    commands (sent (snd (step btcO btcE s (Receive inv)))) `shouldBe` [MCGetHeaders]
+
+notificationSpec :: Spec
+notificationSpec = describe "sending and notifications" $ do
+  it "sends a fee filter and starts the headers sync on the first pass" $ do
+    let s = inboundReady btcO btcE []
+        cmds = commands (sent (snd (step btcO btcE s Tick)))
+    cmds `shouldContain` [MCPing]
+    cmds `shouldContain` [MCGetHeaders]
+    cmds `shouldContain` [MCFeeFilter]
+  it "sends no fee filter in blocks-only mode or on block-relay-only connections" $ do
+    let o = btcO {blocksOnly = True}
+        s = inboundReady o btcE []
+    commands (sent (snd (step o btcE s Tick))) `shouldNotContain` [MCFeeFilter]
+  it "requests a block from the peer with the witness flag" $ do
+    let s = inboundReady btcO btcE []
+        h = (hashN 7)
+        (s1, es) = step btcO btcE s (Notify (RequestBlock h))
+    sent es `shouldBe` [MGetData (GetData [InvVector InvWitnessBlock h.get])]
+    blocksInFlight s1 `shouldBe` [h]
+  it "disconnects a peer that holds a block too long" $ do
+    let s = inboundReady btcO btcE []
+        h = (hashN 7)
+        (s1, _) = step btcO btcE s (Notify (RequestBlock h))
+        later = at (t0 + seconds 601) btcE
+        (s2, _) = step btcO later s1 (Receive (MPing (Ping 1)))
+        (_, es) = step btcO later s2 Tick
+    lines' es `shouldContain` [6465]
+  it "disconnects a staller after 2 seconds" $ do
+    let s = inboundReady btcO btcE []
+        h = (hashN 7)
+        (s1, _) = run btcO btcE s [Notify (RequestBlock h), Notify MarkStalling]
+        (_, es) = step btcO (at (t0 + seconds 3) btcE) s1 Tick
+    lines' es `shouldContain` [6446]
+  it "announces an accepted transaction at the next trickle" $ do
+    let inPool h = if h `elem` [txHash aTx, txWitnessHash aTx] then Just aTx else Nothing
+        e = btcE {initialBlockDownload = False, mempoolTx = inPool}
+        s = inboundReady btcO e []
+        (s1, _) = step btcO e s Tick
+        (s2, _) = step btcO e s1 (Notify (TxAccepted aTx))
+        (_, es) = step btcO (at (t0 + seconds 600) e) s2 Tick
+    [length l | MInv (Inv l) <- sent es] `shouldBe` [1]
+  it "queues new blocks and announces them by inv to a plain peer" $ do
+    let gi = genesisInfo btc
+        hdr = headerAfter btc gi.hash 1
+        h = headerHash hdr
+        bi =
+          BlockInfo
+            { hash = h,
+              height = 1,
+              status = HaveData,
+              inActiveChain = True,
+              work = gi.work * 2,
+              time = gi.time
+            }
+        e =
+          btcE
+            { initialBlockDownload = False,
+              lookupBlock = \x -> if x == h then Just bi else if x == gi.hash then Just gi else Nothing,
+              headerOf = \x -> if x == h then Just hdr else Nothing
+            }
+        s = inboundReady btcO e []
+        (s1, _) = step btcO e s Tick
+        (s2, _) = step btcO e s1 (Notify (NewTip [hdr]))
+        (_, es) = step btcO e s2 Tick
+    [l | MInv (Inv l) <- sent es] `shouldBe` [[InvVector InvBlock h.get]]
+  it "closes the connection when the operator asks" $ do
+    let s = inboundReady btcO btcE []
+        (s1, es) = step btcO btcE s (Notify OperatorDisconnect)
+    actions es `shouldBe` [Disconnect Resources]
+    snd (step btcO btcE s1 Tick) `shouldBe` []
+  it "pings at once when asked" $ do
+    let s = inboundReady btcO btcE []
+        (s1, _) = step btcO btcE s Tick
+        (s2, _) = step btcO btcE s1 (Receive (MPing (Ping 1)))
+        (s3, _) = step btcO btcE s2 (Notify PingRequested)
+    commands (sent (snd (step btcO btcE s3 Tick))) `shouldContain` [MCPing]
+  it "has no ping outstanding before the handshake" $
+    isNothing (pingOutstanding (start btcO (setup Inbound []))) `shouldBe` True
diff --git a/test/Haskoin/NetworkSpec.hs b/test/Haskoin/NetworkSpec.hs
--- a/test/Haskoin/NetworkSpec.hs
+++ b/test/Haskoin/NetworkSpec.hs
@@ -3,6 +3,7 @@
 {-# LANGUAGE OverloadedRecordDot #-}
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE NoFieldSelectors #-}
+{-# OPTIONS_GHC -Wno-deprecations #-}
 
 module Haskoin.NetworkSpec (spec) where
 
@@ -1083,7 +1084,7 @@
 constantsSpec :: Spec
 constantsSpec = describe "network constants" $ do
   it "lists eight networks with distinct names and magics" $ do
-    map (.name) allNets `shouldBe` ["btc", "bch", "btctest", "btctest4", "bchtest4", "bchtest", "btcreg", "bchreg"]
+    map (.name) allNets `shouldBe` ["btc", "bch", "btctest", "btctest4", "bchtest4", "bchtest3", "btcreg", "bchreg"]
     length (nub (map (.magic) allNets)) `shouldBe` 8
   it "finds every network by name" $
     forM_ allNets $
@@ -1091,13 +1092,13 @@
   it "finds nothing for an unknown name" $
     netByName "ltc" `shouldBe` Nothing
   it "uses the magic bytes of each network" $
-    map (.magic) [btc, btcTest, btcTest4, btcRegTest, bch, bchTest, bchTest4, bchRegTest]
+    map (.magic) [btc, btcTest, btcTest4, btcRegTest, bch, bchTest3, bchTest4, bchRegTest]
       `shouldBe` [0xf9beb4d9, 0x0b110907, 0x1c163f28, 0xfabfb5da, 0xe3e1f3e8, 0xf4e5f3f4, 0xe2b7daaf, 0xdab5bffa]
   it "uses the default port of each network" $
-    map (.defaultPort) [btc, btcTest, btcTest4, btcRegTest, bch, bchTest, bchTest4, bchRegTest]
+    map (.defaultPort) [btc, btcTest, btcTest4, btcRegTest, bch, bchTest3, bchTest4, bchRegTest]
       `shouldBe` [8333, 18333, 48333, 18444, 8333, 18333, 28333, 18444]
   it "has the genesis block of each network" $
-    map (headerHash . (.genesisHeader)) [btc, btcTest, btcTest4, btcRegTest, bch, bchTest, bchTest4, bchRegTest]
+    map (headerHash . (.genesisHeader)) [btc, btcTest, btcTest4, btcRegTest, bch, bchTest3, bchTest4, bchRegTest]
       `shouldBe` [ "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
                    "000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943",
                    "00000000da84f2bafbbc53dee25a72ae507ff4914b867c565be350b0da8bf043",
@@ -1108,10 +1109,10 @@
                    "0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"
                  ]
   it "limits messages to 4 MB on bitcoin and twice the block size on bitcoin cash" $
-    map (.maxMessageSize) [btc, btcTest, btcTest4, btcRegTest, bch, bchTest, bchTest4, bchRegTest]
+    map (.maxMessageSize) [btc, btcTest, btcTest4, btcRegTest, bch, bchTest3, bchTest4, bchRegTest]
       `shouldBe` [4000000, 4000000, 4000000, 4000000, 64000000, 64000000, 4000000, 64000000]
   it "knows the block size of each network" $
-    map (.maxBlockSize) [btc, bch, bchTest, bchTest4, bchRegTest]
+    map (.maxBlockSize) [btc, bch, bchTest3, bchTest4, bchRegTest]
       `shouldBe` [1000000, 32000000, 32000000, 2000000, 32000000]
   it "activates BIP34, BIP65 and BIP66 at height 1 on bitcoin regtest, as Bitcoin Core does" $ do
     btcRegTest.bip34Height `shouldBe` 1
@@ -1133,7 +1134,7 @@
     btcTest4.bip34Height `shouldBe` 1
     btcTest4.bip34Hash `shouldBe` Nothing
   it "uses the BIP44 coin type of each network" $
-    map (.bip44Coin) [btc, btcTest, btcTest4, btcRegTest, bch, bchTest, bchTest4, bchRegTest]
+    map (.bip44Coin) [btc, btcTest, btcTest4, btcRegTest, bch, bchTest3, bchTest4, bchRegTest]
       `shouldBe` [0, 1, 1, 1, 145, 1, 1, 1]
   it "lists the Bitcoin Forks seed for bitcoin cash" $
     bch.seeds `shouldSatisfy` elem "seed-bch.bitcoinforks.org"
@@ -1214,7 +1215,7 @@
     maxPayloadSize bchTest4 MCInv `shouldBe` 2097152
   it "limits messages without block content to 4 MB on bitcoin and 2 MiB on bitcoin cash" $
     -- MAX_PROTOCOL_MESSAGE_LENGTH: 4 * 1000 * 1000 in Bitcoin Core, 2 * 1024 * 1024 in Bitcoin Cash Node
-    map (.maxProtocolMessageSize) [btc, btcTest, btcTest4, btcRegTest, bch, bchTest, bchTest4, bchRegTest]
+    map (.maxProtocolMessageSize) [btc, btcTest, btcTest4, btcRegTest, bch, bchTest3, bchTest4, bchRegTest]
       `shouldBe` [4000000, 4000000, 4000000, 4000000, 2097152, 2097152, 2097152, 2097152]
   it "checks the magic before the command name" $
     -- magic 00000000 and the command "ping" followed by a line feed
@@ -1312,7 +1313,7 @@
     counts (runGetS (getMessage bch) (frame bch "cmpctblock" (compact 65535 (hex "0100" <> tx))))
       `shouldBe` Right (65535, [0])
   it "allows positions of 16 bits on bitcoin and of 32 bits on bitcoin cash" $
-    map (.maxCompactBlockIndex) [btc, btcTest, btcTest4, btcRegTest, bch, bchTest, bchTest4, bchRegTest]
+    map (.maxCompactBlockIndex) [btc, btcTest, btcTest4, btcRegTest, bch, bchTest3, bchTest4, bchRegTest]
       `shouldBe` [65535, 65535, 65535, 65535, 4294967295, 4294967295, 4294967295, 4294967295]
   it "keeps 32-bit positions in the form without a network" $ do
     parse (hex (bh1Hex <> "01feffffffff")) `shouldBe` Right (GetBlockTxn bh1 [4294967295])
diff --git a/test/Haskoin/Script/CashTokenSpec.hs b/test/Haskoin/Script/CashTokenSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Haskoin/Script/CashTokenSpec.hs
@@ -0,0 +1,129 @@
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+module Haskoin.Script.CashTokenSpec (spec) where
+
+import Control.DeepSeq (force)
+import Control.Exception (evaluate)
+import Control.Monad (forM_)
+import Data.Aeson (Value, eitherDecode, parseJSON, toJSON, (.:))
+import Data.Aeson.Types (Parser, parseEither, withObject)
+import Data.ByteString (ByteString)
+import Data.ByteString.Lazy qualified as BL
+import Data.Default (def)
+import Data.Either (isLeft)
+import Data.Maybe (fromJust, isNothing)
+import Data.Text (Text)
+import Data.Text qualified as T
+import Data.Text.Encoding (encodeUtf8)
+import Haskoin.Script
+import Haskoin.Transaction.Common (TxHash, hexToTxHash)
+import Haskoin.Util
+import Haskoin.Util.Arbitrary
+import System.Timeout (timeout)
+import Test.Hspec
+import Test.Hspec.QuickCheck (prop)
+import Test.QuickCheck (forAll)
+
+identityTests :: IdentityTests
+identityTests =
+  def
+    { readTests = [ReadBox arbitraryTokenData],
+      jsonTests = [JsonBox arbitraryTokenData],
+      serialTests = [SerialBox arbitraryTokenData]
+    }
+
+spec :: Spec
+spec = do
+  testIdentity identityTests
+  describe "splitTokenData" $ do
+    prop "reads back what encodeTokenPrefix writes, with any script after it" $
+      forAll arbitraryTokenData $ \t ->
+        forAll arbitraryBS $ \script -> do
+          let prefix = fromJust (encodeTokenPrefix t)
+          splitTokenData (prefix <> script) `shouldBe` Right (Just t, script)
+          splitTokenPrefix (prefix <> script) `shouldBe` Just (prefix, script)
+    it "gives a script without the prefix byte back whole" $ do
+      splitTokenData "" `shouldBe` Right (Nothing, "")
+      splitTokenData p2pkh `shouldBe` Right (Nothing, p2pkh)
+    it "reads the prefix of output 4 of the example transaction" $ do
+      let field = fromJust (decodeHex (prefixHex <> p2pkhHex))
+      splitTokenData field `shouldBe` Right (Just (TokenData category 110830 Nothing), p2pkh)
+  describe "encodeTokenPrefix" $ do
+    it "refuses data without tokens" $
+      encodeTokenPrefix (TokenData category 0 Nothing) `shouldSatisfy` isNothing
+    it "refuses an amount above the maximum" $
+      encodeTokenPrefix (TokenData category (maxTokenAmount + 1) Nothing)
+        `shouldSatisfy` isNothing
+    it "writes an NFT without a commitment or an amount" $ do
+      let t = TokenData category 0 (Just (NFToken MintingCapability ""))
+      -- the prefix byte and the category, then the flags: NFT and minting
+      fmap encodeHex (encodeTokenPrefix t) `shouldBe` Just (T.take 66 prefixHex <> "22")
+  describe "JSON" $ do
+    it "takes the amount as a number too" $
+      eitherDecode (tokenJson "110830") `shouldBe` Right (TokenData category 110830 Nothing)
+    it "refuses data without tokens" $
+      (eitherDecode (tokenJson "\"0\"") :: Either String TokenData) `shouldSatisfy` isLeft
+    it "refuses a negative amount" $
+      (eitherDecode (tokenJson "-1") :: Either String TokenData) `shouldSatisfy` isLeft
+    it "refuses an amount above the maximum, as a string or a number" $ do
+      (eitherDecode (tokenJson "\"9223372036854775808\"") :: Either String TokenData) `shouldSatisfy` isLeft
+      (eitherDecode (tokenJson "9223372036854775808") :: Either String TokenData) `shouldSatisfy` isLeft
+      eitherDecode (tokenJson "\"9223372036854775807\"")
+        `shouldBe` Right (TokenData category maxTokenAmount Nothing)
+    it "takes only decimal digits in a string amount" $
+      forM_ ["0x10", "0o20", "0b1", " 16", "16 ", "(16)", "016", "+16", "1e1", "", "\x0661"] $ \a ->
+        (eitherDecode (tokenJson ("\"" <> a <> "\"")) :: Either String TokenData) `shouldSatisfy` isLeft
+    it "refuses a number with a huge exponent at once" $ do
+      -- Building this number would take seconds and hundreds of megabytes.
+      result <- timeout 1000000 (evaluate (force (eitherDecode (tokenJson "1e100000000") :: Either String TokenData)))
+      fmap isLeft result `shouldBe` Just True
+    it "refuses a number that is not whole" $
+      (eitherDecode (tokenJson "1.5") :: Either String TokenData) `shouldSatisfy` isLeft
+  describe "CashTokens test vectors" $ do
+    it "reads and writes every valid token prefix" $ do
+      vectors <- readTestFile "cashtokens_prefix_valid.json" :: IO [Value]
+      length vectors `shouldBe` 62
+      forM_ vectors $ \v -> do
+        (hex, json) <- either fail return (parseEither validVector v)
+        t <- either fail return (parseEither parseJSON json)
+        splitTokenData (fromJust (decodeHex hex)) `shouldBe` Right (Just t, "")
+        fmap encodeHex (encodeTokenPrefix t) `shouldBe` Just hex
+        toJSON t `shouldBe` json
+    it "refuses every invalid token prefix" $ do
+      vectors <- readTestFile "cashtokens_prefix_invalid.json" :: IO [Value]
+      length vectors `shouldBe` 55
+      forM_ vectors $ \v -> do
+        hex <- either fail return (parseEither (withObject "vector" (.: "prefix")) v)
+        let bytes = fromJust (decodeHex hex)
+        splitTokenData bytes `shouldSatisfy` isLeft
+        splitTokenPrefix bytes `shouldBe` Nothing
+  where
+    validVector :: Value -> Parser (Text, Value)
+    validVector = withObject "vector" $ \o -> (,) <$> o .: "prefix" <*> o .: "data"
+
+-- | The JSON of tokens of 'category' with an amount, given as JSON.
+tokenJson :: Text -> BL.ByteString
+tokenJson amount =
+  BL.fromStrict . encodeUtf8 $
+    "{\"category\":\"" <> categoryHex <> "\",\"amount\":" <> amount <> "}"
+
+-- | Category of the tokens in BCH transaction
+-- e3abdbdc093c08cab3d6c23c320ca61f23c6e2cf4d8b3058398dcf0e78f5a809.
+category :: TxHash
+category = fromJust (hexToTxHash categoryHex)
+
+categoryHex :: Text
+categoryHex = "7fe0cd5197494e47ade81eb164dcdbd51859ffbe581fe4a818085d56b2f3062c"
+
+-- | Token prefix of output 4 of that transaction: 110,830 fungible tokens.
+prefixHex :: Text
+prefixHex =
+  "ef2c06f3b2565d0818a8e41f58beff5918d5dbdc6\
+  \4b11ee8ad474e499751cde07f10feeeb00100"
+
+p2pkhHex :: Text
+p2pkhHex = "76a9146e0810ceea13412b73feb41566a3d2d0ce54e10188ac"
+
+p2pkh :: ByteString
+p2pkh = fromJust (decodeHex p2pkhHex)
diff --git a/test/Haskoin/ScriptSpec.hs b/test/Haskoin/ScriptSpec.hs
--- a/test/Haskoin/ScriptSpec.hs
+++ b/test/Haskoin/ScriptSpec.hs
@@ -149,6 +149,15 @@
 sigDer :: Sig
 sigDer = fromJust $ decodeStrictSig $ hex sigDerHex
 
+-- | An ECDSA signature whose DER form is 64 bytes, without its hash type
+-- byte: r and s take 0x1d = 29 bytes each. Bitcoin Core 32.1 put it in a
+-- block on regtest, and Bitcoin Cash Node 29.2.0 refused it, in the
+-- transactions of "Haskoin.Transaction.VerdictSpec".
+shortDerHex :: Text
+shortDerHex =
+  "303e021d412389f0428046438bea9c0e2427db23ab0bce6fe36d851e0dc86b41ed\
+  \021d20576521b06f9bc52aacf1dee9900a53c82c9e9ad11dae4edc0d6164db"
+
 -- | The signature with SIGHASH_ALL, pushed in a script.
 sigAllPushHex :: Text
 sigAllPushHex = "47" <> sigDerHex <> "01"
@@ -162,6 +171,15 @@
   \c95a783a76ac7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2\
   \f0167faa815988ac11000000"
 
+-- | That transaction without its second output, so that its second input
+-- has no output at its index.
+bip143OneOutputTx :: Tx
+bip143OneOutputTx =
+  "0100000002fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f\
+  \0000000000eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57\
+  \b90ec68a0100000000ffffffff01202cb206000000001976a9148280b37df378db99f66f85\
+  \c95a783a76ac7a6d5988ac11000000"
+
 -- | The scriptCode of the second input of that transaction: the P2PKH script
 -- of the key that the P2WPKH output pays to.
 bip143ScriptCode :: Script
@@ -170,6 +188,13 @@
     runGetS deserialize $
       hex "76a9141d0f172a0ecb48aee1be1f2687d2963ae33f71a188ac"
 
+-- | The private key of that input in BIP 143. Its public key hashes to
+-- 1d0f172a0ecb48aee1be1f2687d2963ae33f71a1.
+bip143Key :: PrivateKey
+bip143Key =
+  wrapSecKey True . fromJust . secKey $
+    hex "619c335025c7f4012e556c2a58b2506e30b8511b53ade95ea316fd8c3286feb9"
+
 -- | The value of the output that the second input spends: 6 BTC.
 bip143Value :: Word64
 bip143Value = 600000000
@@ -178,6 +203,19 @@
 bip143Digest :: Hash256
 bip143Digest = "c37af31116d1b27caf68aae9e3ac82f1477929014d5b917657d0eb49478cb670"
 
+-- | The fork id digest of Bitcoin Cash for the second input of that
+-- transaction, for each of the six hash types. They were computed with
+-- Python (hashlib) from the text of BIP 143.
+bip143CashDigests :: [(SigHash, Hash256)]
+bip143CashDigests =
+  [ (0x41, "467f411d178762db122a6aced76370a1c8324355bf0796502bf82eeaeda86a35"),
+    (0x42, "c0876aa9dfd131ac207be062e389741416a87a5d1b28e4857c178990454dd498"),
+    (0x43, "abb61ba86e14313425d25846ed3a30904de1f081e013d80c385e165c2af1e020"),
+    (0xc1, "a5890ce40dc95a89717ae6fa3c9d60bcf9372539058c7e9a0cd8ff7909723326"),
+    (0xc2, "e58ebfd50f957a45c5f68439e55c6ae6054a3310ff2a116efa07d2bda2527bd3"),
+    (0xc3, "4e303851715b6ee36582740f43cc288c969e88afc641f14e3e8e68d32c406c1b")
+  ]
+
 -- | Opcodes by their byte, from the script specification.
 namedOpcodes :: [(Word8, ScriptOp)]
 namedOpcodes =
@@ -228,12 +266,88 @@
     (0xbb, OP_CHECKDATASIGVERIFY),
     (0xbc, OP_REVERSEBYTES),
     (0xbd, OP_INVALIDOPCODE 0xbd),
+    (0xc0, OP_INPUTINDEX),
+    (0xc1, OP_ACTIVEBYTECODE),
+    (0xc2, OP_TXVERSION),
+    (0xc3, OP_TXINPUTCOUNT),
+    (0xc4, OP_TXOUTPUTCOUNT),
+    (0xc5, OP_TXLOCKTIME),
+    (0xc6, OP_UTXOVALUE),
+    (0xc7, OP_UTXOBYTECODE),
+    (0xc8, OP_OUTPOINTTXHASH),
+    (0xc9, OP_OUTPOINTINDEX),
+    (0xca, OP_INPUTBYTECODE),
+    (0xcb, OP_INPUTSEQUENCENUMBER),
+    (0xcc, OP_OUTPUTVALUE),
+    (0xcd, OP_OUTPUTBYTECODE),
+    (0xce, OP_UTXOTOKENCATEGORY),
+    (0xcf, OP_UTXOTOKENCOMMITMENT),
+    (0xd0, OP_UTXOTOKENAMOUNT),
+    (0xd1, OP_OUTPUTTOKENCATEGORY),
+    (0xd2, OP_OUTPUTTOKENCOMMITMENT),
+    (0xd3, OP_OUTPUTTOKENAMOUNT),
+    (0xd4, OP_RESERVED3),
+    (0xd5, OP_RESERVED4),
+    (0xd6, OP_INVALIDOPCODE 0xd6),
     (0xfc, OP_INVALIDOPCODE 0xfc),
     (0xfd, OP_PUBKEYHASH),
     (0xfe, OP_PUBKEY),
     (0xff, OP_INVALIDOPCODE 0xff)
   ]
 
+-- | The bytes that Bitcoin Cash names differently, with the constructor and
+-- the pattern synonym of the Bitcoin Cash name.
+bitcoinCashNames :: [(Word8, ScriptOp, ScriptOp)]
+bitcoinCashNames =
+  [ (0x65, OP_VERIF, OP_BEGIN),
+    (0x66, OP_VERNOTIF, OP_UNTIL),
+    (0x7f, OP_SUBSTR, OP_SPLIT),
+    (0x80, OP_LEFT, OP_NUM2BIN),
+    (0x81, OP_RIGHT, OP_BIN2NUM),
+    (0x89, OP_RESERVED1, OP_DEFINE),
+    (0x8a, OP_RESERVED2, OP_INVOKE),
+    (0x8d, OP_2MUL, OP_LSHIFTNUM),
+    (0x8e, OP_2DIV, OP_RSHIFTNUM),
+    (0x98, OP_LSHIFT, OP_LSHIFTBIN),
+    (0x99, OP_RSHIFT, OP_RSHIFTBIN),
+    (0xba, OP_CHECKDATASIG, OP_CHECKSIGADD)
+  ]
+
+-- | Opcodes with the names that @GetOpName@ gives them in Bitcoin Core 32.1
+-- and in Bitcoin Cash Node 29.2.0.
+opNames :: [(ScriptOp, Text, Text)]
+opNames =
+  [ (OP_0, "0", "0"),
+    (OP_1NEGATE, "-1", "-1"),
+    (OP_16, "16", "16"),
+    (OP_PUSHDATA "a" OPCODE, "OP_UNKNOWN", "OP_UNKNOWN"),
+    (OP_PUSHDATA "a" OPDATA1, "OP_PUSHDATA1", "OP_PUSHDATA1"),
+    (OP_PUSHDATA "a" OPDATA4, "OP_PUSHDATA4", "OP_PUSHDATA4"),
+    (OP_DUP, "OP_DUP", "OP_DUP"),
+    (OP_CHECKSIG, "OP_CHECKSIG", "OP_CHECKSIG"),
+    (OP_VERIF, "OP_VERIF", "OP_BEGIN"),
+    (OP_VERNOTIF, "OP_VERNOTIF", "OP_UNTIL"),
+    (OP_SUBSTR, "OP_SUBSTR", "OP_SPLIT"),
+    (OP_LEFT, "OP_LEFT", "OP_NUM2BIN"),
+    (OP_RIGHT, "OP_RIGHT", "OP_BIN2NUM"),
+    (OP_RESERVED1, "OP_RESERVED1", "OP_DEFINE"),
+    (OP_RESERVED2, "OP_RESERVED2", "OP_INVOKE"),
+    (OP_2MUL, "OP_2MUL", "OP_LSHIFTNUM"),
+    (OP_2DIV, "OP_2DIV", "OP_RSHIFTNUM"),
+    (OP_LSHIFT, "OP_LSHIFT", "OP_LSHIFTBIN"),
+    (OP_RSHIFT, "OP_RSHIFT", "OP_RSHIFTBIN"),
+    (OP_CHECKDATASIG, "OP_CHECKSIGADD", "OP_CHECKDATASIG"),
+    (OP_CHECKDATASIGVERIFY, "OP_UNKNOWN", "OP_CHECKDATASIGVERIFY"),
+    (OP_REVERSEBYTES, "OP_UNKNOWN", "OP_REVERSEBYTES"),
+    (OP_INPUTINDEX, "OP_UNKNOWN", "OP_INPUTINDEX"),
+    (OP_OUTPUTTOKENAMOUNT, "OP_UNKNOWN", "OP_OUTPUTTOKENAMOUNT"),
+    (OP_RESERVED4, "OP_UNKNOWN", "OP_RESERVED4"),
+    (OP_PUBKEYHASH, "OP_UNKNOWN", "OP_UNKNOWN"),
+    (OP_INVALIDOPCODE 0xef, "OP_UNKNOWN", "SPECIAL_TOKEN_PREFIX"),
+    (OP_INVALIDOPCODE 0xff, "OP_INVALIDOPCODE", "OP_UNKNOWN"),
+    (OP_INVALIDOPCODE 0xac, "OP_CHECKSIG", "OP_CHECKSIG")
+  ]
+
 {- Opcodes and pushes -}
 
 opcodeSpec :: Spec
@@ -252,6 +366,16 @@
     OP_CHECKSIGADD `shouldBe` OP_CHECKDATASIG
     runPutS (serialize OP_CHECKSIGADD) `shouldBe` B.singleton 0xba
     (case OP_CHECKDATASIG of OP_CHECKSIGADD -> True; _ -> False) `shouldBe` True
+  it "calls the twelve bytes that Bitcoin Cash renamed by both names" $
+    forM_ bitcoinCashNames $ \(b, op, alias) -> do
+      (b, alias) `shouldBe` (b, op)
+      (b, runPutS (serialize alias)) `shouldBe` (b, B.singleton b)
+  it "names opcodes as the reference node of each network does" $
+    forM_ opNames $ \(op, core, bchn) -> do
+      -- Every network of a chain, its testnets included, names them alike.
+      forM_ allNets $ \net -> do
+        let name = if isJust net.sigHashForkId then bchn else core
+        (op, net.name, opName net op) `shouldBe` (op, net.name, name)
   it "shows and reads opcode names" $ do
     show OP_CHECKLOCKTIMEVERIFY `shouldBe` "OP_CHECKLOCKTIMEVERIFY"
     readMaybe "OP_DUP" `shouldBe` Just OP_DUP
@@ -465,6 +589,14 @@
     -- Non-standard in Bitcoin Core.
     ("P2PKH with OP_PUSHDATA1", "76a94c14" <> twenty <> "88ac"),
     ("P2PK with OP_PUSHDATA1", "4c21" <> gKeyHex <> "ac"),
+    -- The same keys as a multisig of direct pushes, in other bytes: a value
+    -- of 'ScriptOutput' has no place for the form of a push. Bitcoin Core
+    -- calls these multisig, and Bitcoin Cash Node does not. 0x21 = 33, the
+    -- length of the key, in one, two and four bytes.
+    ("multisig with a key pushed with OP_PUSHDATA1", "514c21" <> gKeyHex <> "51ae"),
+    ("multisig with a key pushed with OP_PUSHDATA2", "514d2100" <> gKeyHex <> "51ae"),
+    ("multisig with a key pushed with OP_PUSHDATA4", "514e21000000" <> gKeyHex <> "51ae"),
+    ("multisig with one of two keys pushed with OP_PUSHDATA1", "5121" <> gKeyHex <> "4c21" <> gKeyHex <> "52ae"),
     -- Wrong lengths.
     ("witness v0 of 25 bytes", "0019" <> T.replicate 25 "01"),
     ("witness v1 of 41 bytes", "5129" <> T.replicate 41 "01"),
@@ -516,13 +648,6 @@
   it "rejects scripts that only look like a standard output" $
     forM_ nonStandardOutputs $ \(name, h) ->
       (name, decodeHexOutput h) `shouldSatisfy` (isLeft . snd)
-  it "accepts a multisig key pushed with OP_PUSHDATA1, as the solver of Bitcoin Core does" $
-    decodeHexOutput ("514c21" <> gKeyHex <> "51ae") `shouldBe` Right (PayMulSig [g] 1)
-  it "writes such a multisig back with direct pushes, which are other bytes" $
-    -- A ScriptOutput does not keep the form of a push. The result must not
-    -- be hashed or signed in place of the script that was read.
-    (encodeHexOutput =<< decodeHexOutput ("514c21" <> gKeyHex <> "51ae"))
-      `shouldBe` Right ("5121" <> gKeyHex <> "51ae")
   it "writes a data carrier back with the shortest pushes, which can be other bytes" $
     (encodeHexOutput =<< decodeHexOutput "6a4c0401020304") `shouldBe` Right "6a0401020304"
   it "does not decode a key that is not a point of the curve, where Bitcoin Core only checks its size" $ do
@@ -834,6 +959,59 @@
 
 {- Digests -}
 
+-- | The digests of every input of a transaction, from the hashes that the
+-- inputs share. Each digest is the one that the test of the function for
+-- one digest states.
+sharedHashesSpec :: Spec
+sharedHashesSpec = do
+  let hashes = txSigHashes bip143Tx
+  it "computes the BIP 143 digests of the P2WPKH example from the hashes that its inputs share" $ do
+    txSigHashForkIdWith btc hashes bip143ScriptCode bip143Value 1 sigHashAll
+      `shouldBe` Right bip143Digest
+    txSigHashForkIdWith btc hashes bip143ScriptCode bip143Value 1 (setAnyoneCanPay sigHashAll)
+      `shouldBe` Right "fc5b6bbc855883bcfdaefb77071740ccde4929f15e6a13286584e779b2529d91"
+  it "computes the fork id digests of Bitcoin Cash for its six hash types from those hashes" $
+    forM_ bip143CashDigests $ \(sh, digest) -> do
+      (sh, txSigHashWith bch hashes bip143ScriptCode bip143Value 1 sh) `shouldBe` (sh, Right digest)
+      (sh, txSigHashCashTokenWith bch hashes "" bip143ScriptCode bip143Value 1 sh) `shouldBe` (sh, Right digest)
+  it "computes the legacy digest of Bitcoin for the transaction of those hashes" $
+    txSigHashWith btc hashes bip143ScriptCode bip143Value 1 sigHashAll
+      `shouldBe` Right "c46030820cbc48402a47cc5b5d3d41648f4e3a711f56b804d601d09dc112a6a4"
+  it "puts no output in the digest of SIGHASH_SINGLE when the input has no output at its index, from those hashes" $ do
+    let oneOutput = txSigHashes bip143OneOutputTx
+    txSigHashForkIdWith btc oneOutput bip143ScriptCode bip143Value 1 sigHashSingle
+      `shouldBe` Right "471a6e7963aa0c328ee12392fb1a345148edf326b4223660e1a770fdc2826435"
+    txSigHashForkIdWith btc oneOutput bip143ScriptCode bip143Value 0 sigHashSingle
+      `shouldBe` Right "0ef4fc221b524ce37251444160588c6989d6bc88b60c47a6ff7ded04173636c4"
+  it "fails with those hashes for an input index the transaction does not have" $ do
+    let legacy i = txSigHashWith btc hashes bip143ScriptCode bip143Value i sigHashAll
+        bip143 i = txSigHashForkIdWith btc hashes bip143ScriptCode bip143Value i sigHashAll
+    legacy 2 `shouldBe` Left "txSigHash: input index out of range"
+    legacy (-1) `shouldBe` Left "txSigHash: input index out of range"
+    bip143 2 `shouldBe` Left "txSigHashForkId: input index out of range"
+    bip143 (-1) `shouldBe` Left "txSigHashForkId: input index out of range"
+  it "requires SIGHASH_FORKID on Bitcoin Cash with those hashes" $
+    txSigHashWith bch hashes bip143ScriptCode bip143Value 1 sigHashAll
+      `shouldBe` Left "txSigHash: SIGHASH_FORKID is required on this network"
+  it "gives back the transaction that the hashes were made from" $
+    sigHashesTx hashes `shouldBe` bip143Tx
+  -- The signature that BIP 143 gives for the second input of its example
+  it "makeSignatureWith signs the P2WPKH example of BIP 143 with the signature of the BIP, from those hashes" $ do
+    let coin = PayWitnessPKHash "1d0f172a0ecb48aee1be1f2687d2963ae33f71a1"
+        outpoint = (bip143Tx.inputs !! 1).outpoint
+        sigInput = SigInput coin bip143Value outpoint sigHashAll Nothing
+    fmap (encodeHex . encodeTxSig btc) (makeSignatureWith btc hashes 1 sigInput bip143Key)
+      `shouldBe` Right
+        "304402203609e17b84f6a7d30c80bfa610b5b4542f32a8a0d5447a12fb1366d7f01cc44a\
+        \0220573a954c4518331561406f90300e8f3358f51928d43c212a8caed02de67eebee01"
+  -- The digest of that case is the constant 1, which commits to nothing
+  it "makeSignatureWith refuses SIGHASH_SINGLE on a legacy input without an output at its index" $ do
+    let coin = PayPKHash "1d0f172a0ecb48aee1be1f2687d2963ae33f71a1"
+        outpoint = (bip143OneOutputTx.inputs !! 1).outpoint
+        sigInput = SigInput coin bip143Value outpoint sigHashSingle Nothing
+    makeSignatureWith btc (txSigHashes bip143OneOutputTx) 1 sigInput bip143Key
+      `shouldBe` Left "makeSignature: SIGHASH_SINGLE without an output at the input index"
+
 digestSpec :: Spec
 digestSpec = do
   it "computes the BIP 143 digest of the P2WPKH example" $
@@ -854,20 +1032,12 @@
       `shouldBe` Right "c46030820cbc48402a47cc5b5d3d41648f4e3a711f56b804d601d09dc112a6a4"
     txSigHash btc bip143Tx bip143ScriptCode bip143Value 1 0x101
       `shouldBe` Right "8e4ac2d7b4f759fdd01de9b78a2c46fe361316f397b214c7f0f98f073128aa4c"
-  it "computes the fork id digest of Bitcoin Cash for each of its six hash types"
-    $
+  it "computes the fork id digest of Bitcoin Cash for each of its six hash types" $
     -- The fork id of Bitcoin Cash is 0, so the last four bytes of the
     -- preimage are the hash type byte and three zero bytes
-    forM_
-      [ (0x41, "467f411d178762db122a6aced76370a1c8324355bf0796502bf82eeaeda86a35"),
-        (0x42, "c0876aa9dfd131ac207be062e389741416a87a5d1b28e4857c178990454dd498"),
-        (0x43, "abb61ba86e14313425d25846ed3a30904de1f081e013d80c385e165c2af1e020"),
-        (0xc1, "a5890ce40dc95a89717ae6fa3c9d60bcf9372539058c7e9a0cd8ff7909723326"),
-        (0xc2, "e58ebfd50f957a45c5f68439e55c6ae6054a3310ff2a116efa07d2bda2527bd3"),
-        (0xc3, "4e303851715b6ee36582740f43cc288c969e88afc641f14e3e8e68d32c406c1b")
-      ]
-    $ \(sh, digest) ->
-      (sh, txSigHashForkId bch bip143Tx bip143ScriptCode bip143Value 1 sh) `shouldBe` (sh, Right digest)
+    forM_ bip143CashDigests $
+      \(sh, digest) ->
+        (sh, txSigHashForkId bch bip143Tx bip143ScriptCode bip143Value 1 sh) `shouldBe` (sh, Right digest)
   it "fails for an input index the transaction does not have" $ do
     txSigHash btc bip143Tx bip143ScriptCode bip143Value 2 sigHashAll `shouldSatisfy` isLeft
     txSigHash btc bip143Tx bip143ScriptCode bip143Value (-1) sigHashAll `shouldSatisfy` isLeft
@@ -881,6 +1051,18 @@
     -- The script code is then 26 bytes: ab, then the 25 bytes of the script
     txSigHashForkId btc bip143Tx (Script (OP_CODESEPARATOR : bip143ScriptCode.ops)) bip143Value 1 sigHashAll
       `shouldBe` Right "f58633c60526565d17f4a38d202ab3cfc26fb900abd2f49cf2252488b5240964"
+  -- BIP 143: hashOutputs is 32 zero bytes when the type is SINGLE and the
+  -- input index is not below the number of outputs. The transaction is the
+  -- example without its second output, and the digests were computed with
+  -- Python (hashlib) from the text of the BIP.
+  it "puts no output in the BIP 143 digest of SIGHASH_SINGLE when the input has no output at its index" $ do
+    txSigHashForkId btc bip143OneOutputTx bip143ScriptCode bip143Value 1 sigHashSingle
+      `shouldBe` Right "471a6e7963aa0c328ee12392fb1a345148edf326b4223660e1a770fdc2826435"
+    txSigHashForkId btc bip143OneOutputTx bip143ScriptCode bip143Value 0 sigHashSingle
+      `shouldBe` Right "0ef4fc221b524ce37251444160588c6989d6bc88b60c47a6ff7ded04173636c4"
+    txSigHashForkId bch bip143OneOutputTx bip143ScriptCode bip143Value 1 0x43
+      `shouldBe` Right "655196fc3fcfa9cfc37922e03bf9ff86e1ad2892e18065f032b11afd6c9902d0"
+  sharedHashesSpec
   it "requires SIGHASH_FORKID on Bitcoin Cash" $
     txSigHash bch bip143Tx bip143ScriptCode bip143Value 1 sigHashAll `shouldSatisfy` isLeft
   it "uses the fork id digest on Bitcoin Cash" $
@@ -939,6 +1121,14 @@
     -- 64 bytes and the hash type byte 0x41. Bitcoin Cash Node takes a
     -- 64-byte signature as Schnorr.
     decodeTxSig bch (B.replicate 64 0x11 <> "\x41") `shouldSatisfy` isLeft
+  it "does not read an ECDSA signature of 64 bytes on Bitcoin Cash, where a node reads a Schnorr signature" $
+    -- r and s take 29 bytes each: 6 + 29 + 29 = 64
+    decodeTxSig bch (hex (shortDerHex <> "41"))
+      `shouldBe` Left
+        "Failed reading: Non-canonical signature: a signature of 64 bytes is a Schnorr signature on this network\n\
+        \Empty call stack\n"
+  it "reads an ECDSA signature of 64 bytes on Bitcoin, where a block may hold it" $
+    decodeTxSig btc (hex (shortDerHex <> "01")) `shouldSatisfy` isRight
   it "does not read SIGHASH_UTXOS on Bitcoin Cash, which the digest does not support" $
     -- 0x61 is SIGHASH_ALL with SIGHASH_UTXOS and SIGHASH_FORKID
     decodeTxSig bch (hex (sigDerHex <> "61"))
diff --git a/test/Haskoin/Transaction/JudgeSpec.hs b/test/Haskoin/Transaction/JudgeSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Haskoin/Transaction/JudgeSpec.hs
@@ -0,0 +1,254 @@
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+module Haskoin.Transaction.JudgeSpec (spec) where
+
+import Crypto.Secp256k1
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as B
+import Data.Bytes.Put (runPutS)
+import Data.Bytes.Serial (serialize)
+import Data.Maybe (fromJust)
+import Data.Serialize (encode)
+import Data.Word (Word32, Word64, Word8)
+import Haskoin.Address
+import Haskoin.Crypto
+import Haskoin.Network.Constants
+import Haskoin.Network.Data
+import Haskoin.Script
+import Haskoin.Transaction hiding (Coin (..))
+import Haskoin.Transaction.Judge
+import Haskoin.Util
+import Test.Hspec
+
+-- | An output, told apart by a number.
+output :: Word32 -> OutPoint
+output n = OutPoint (TxHash (doubleSHA256 (encode n))) n
+
+-- | A transaction that spends outputs and pays a value.
+spending :: [OutPoint] -> Word64 -> Tx
+spending ins v =
+  Tx
+    { version = 2,
+      inputs = [TxIn {outpoint = o, script = "", sequence = maxBound} | o <- ins],
+      outputs = [TxOut {value = v, script = B.replicate 25 1}],
+      witness = [],
+      locktime = 0
+    }
+
+-- | A coin of a value that nothing is known of: not in a block, and with
+-- a script whose spending cannot be judged.
+held :: Word64 -> Coin
+held v = Coin {output = TxOut v "", mined = Nothing, coinbase = False}
+
+-- | An input script that pushes a word, which 'rulesOf' reads.
+saying :: ByteString -> ByteString
+saying word = encode (Script [opPushData word])
+
+-- | The chain at block 1000.
+--
+-- The signatures are judged by the scripts of the test: an input script
+-- that pushes @forged@ is forged, one that pushes @script@ cannot be told,
+-- and any other verifies. 'judgeInputs' itself is tested in
+-- "Haskoin.Transaction.VerdictSpec".
+rulesOf :: Rules
+rulesOf = Rules {net = btc, inputs = \tx _ -> map verdict tx.inputs, height = 1000, medianTime = 1600000000}
+  where
+    verdict :: TxIn -> InputVerdict
+    verdict i
+      | i.script == saying "forged" = InputForged
+      | i.script == saying "script" = InputUndecided
+      | otherwise = InputVerified
+
+-- | The front of the script of an output that holds tokens: the category,
+-- the flags, the commitment if there is one, and the amount if not zero.
+withTokens :: ByteString -> Maybe (Word8, ByteString) -> Word64 -> ByteString
+withTokens category nft amount =
+  B.concat
+    [ "\xef",
+      category,
+      B.singleton (nftFlags .|. (if amount > 0 then 0x10 else 0)),
+      maybe "" (\(_, c) -> if B.null c then "" else B.singleton (fromIntegral (B.length c)) <> c) nft,
+      if amount > 0 then compact amount else "",
+      "\x76\xa9\x14" <> B.replicate 20 7 <> "\x88\xac"
+    ]
+  where
+    nftFlags = case nft of
+      Nothing -> 0
+      Just (capability, c) -> 0x20 .|. capability .|. (if B.null c then 0 else 0x40)
+    compact v
+      | v < 0xfd = B.singleton (fromIntegral v)
+      | otherwise = "\xfd" <> B.pack [fromIntegral v, fromIntegral (v `div` 256)]
+    a .|. b = a + b
+
+-- | A secret key, and the compressed bytes of its public key.
+secret :: SecKey
+secret = fromJust (secKey (B.replicate 31 0 <> B.singleton 7))
+
+public :: ByteString
+public = exportPubKey True (derivePubKey secret)
+
+-- | A coin of 100,000 locked to the hash of that key.
+keyCoin :: TxOut
+keyCoin = TxOut 100000 (encodeSerial (PayPKHash (addressHash public)))
+
+-- | A coin of 100,000 locked by a script, which nothing here runs.
+scriptCoin :: TxOut
+scriptCoin = TxOut 100000 ("\xa9\x14" <> B.replicate 20 7 <> "\x87")
+
+-- | A transaction of Bitcoin that spends output 1, signed by the key as
+-- the spend of 'keyCoin'.
+signed :: Tx
+signed = unsigned {inputs = [TxIn (output 1) (runPutS (serialize (Script (map opPushData [sig, public])))) maxBound]}
+  where
+    unsigned = spending [output 1] 90000
+    locking = either error id (encodeOutput (PayPKHash (addressHash public)))
+    digest = either error id (txSigHash btc unsigned locking 100000 0 sigHashAll)
+    sig = exportSig (signHash secret digest) <> B.singleton 0x01
+
+spec :: Spec
+spec = do
+  let check = judge rulesOf
+  describe "a transaction to publish" $ do
+    let tx = spending [output 1, output 2] 1500
+    it "lets through a transaction that spends what is there" $
+      check tx [held 1000, held 500] `shouldBe` Right Nothing
+    it "refuses an output it does not know, and one spent in a block" $ do
+      check tx [held 1000, Missing] `shouldBe` Left (UnknownOutput (output 2))
+      let by = (output 9).hash
+      check tx [Spent by, held 1000] `shouldBe` Left (SpentOutput (output 1) by)
+    it "refuses outputs worth more than the inputs" $
+      check tx [held 1000, held 499] `shouldBe` Left Overspent
+    it "refuses the same output twice, a coinbase, and nothing to spend or pay" $ do
+      check (spending [output 1, output 1] 1) [held 1, held 1] `shouldBe` Left (DuplicateInput (output 1))
+      check (spending [nullOutPoint] 1) [Missing] `shouldBe` Left IsCoinbase
+      check (spending [] 1) [] `shouldBe` Left NoInputs
+      check (spending [output 1] 1) {outputs = []} [held 1] `shouldBe` Left NoOutputs
+    it "refuses a coinbase that is not a hundred blocks old" $ do
+      let young h = Coin {output = TxOut 1000 "", mined = Just h, coinbase = True}
+          one = spending [output 1] 900
+      check one [young 902] `shouldBe` Left (Immature (output 1))
+      check one [young 901] `shouldBe` Right Nothing
+      check one [(young 902) {coinbase = False}] `shouldBe` Right Nothing
+    it "refuses a lock time that has not passed, unless every input waives it" $ do
+      let locked n = (spending [output 1] 900) {locktime = n, inputs = [TxIn (output 1) "" 0]} :: Tx
+      check (locked 1000) [held 1000] `shouldBe` Right Nothing
+      check (locked 1001) [held 1000] `shouldBe` Left (NotFinal 1001)
+      check (locked 1599999999) [held 1000] `shouldBe` Right Nothing
+      check (locked 1600000000) [held 1000] `shouldBe` Left (NotFinal 1600000000)
+      check ((locked 1001) {inputs = [TxIn (output 1) "" maxBound]} :: Tx) [held 1000] `shouldBe` Right Nothing
+    it "refuses an output worth less than it costs to spend, and not one that holds data" $ do
+      let paying v script = (spending [output 1] 0) {outputs = [TxOut v script]} :: Tx
+          keyHash = "\x76\xa9\x14" <> B.replicate 20 7 <> "\x88\xac"
+          witnessKeyHash = "\x00\x14" <> B.replicate 20 7
+      check (paying 545 keyHash) [held 1000] `shouldBe` Left (Dust 0)
+      check (paying 546 keyHash) [held 1000] `shouldBe` Right Nothing
+      check (paying 293 witnessKeyHash) [held 1000] `shouldBe` Left (Dust 0)
+      check (paying 294 witnessKeyHash) [held 1000] `shouldBe` Right Nothing
+      check (paying 0 "\x6a\x04data") [held 1000] `shouldBe` Right Nothing
+    it "refuses a forged signature, and names the input it cannot judge" $ do
+      let signedBy items = (spending [output 1, output 2] 900) {inputs = zipWith input [1 ..] items} :: Tx
+          input n item = TxIn (output n) (saying item) maxBound
+      check (signedBy ["good", "forged"]) [held 1000, held 1000] `shouldBe` Left (Forged 1)
+      check (signedBy ["good", "script"]) [held 1000, held 1000] `shouldBe` Right (Just 1)
+      check (signedBy ["good", "good"]) [held 1000, held 1000] `shouldBe` Right Nothing
+    it "refuses a version that nodes do not take: 1 to 3 on Bitcoin, 1 and 2 on Bitcoin Cash" $ do
+      let versioned v = (spending [output 1] 900) {version = v} :: Tx
+          cash = judge rulesOf {net = bch}
+      check (versioned 3) [held 1000] `shouldBe` Right Nothing
+      check (versioned 0) [held 1000] `shouldBe` Left (BadVersion 0)
+      check (versioned 4) [held 1000] `shouldBe` Left (BadVersion 4)
+      cash (versioned 2) [held 1000] `shouldBe` Right Nothing
+      cash (versioned 3) [held 1000] `shouldBe` Left (BadVersion 3)
+    it "refuses an input script that does more than push, or pushes in a longer form than it needs" $ do
+      let scripted ops = (spending [output 1] 900) {inputs = [TxIn (output 1) (encode (Script ops)) maxBound]} :: Tx
+          signature = B.replicate 71 1
+      check (scripted [opPushData signature, opPushData (B.replicate 33 2)]) [held 1000] `shouldBe` Right Nothing
+      -- a push of 71 bytes takes one byte for its length, not two
+      check (scripted [OP_PUSHDATA signature OPDATA1]) [held 1000] `shouldBe` Left (NotMinimal 0)
+      -- the number 1 is OP_1, and the empty string OP_0
+      check (scripted [OP_PUSHDATA "\x01" OPCODE]) [held 1000] `shouldBe` Left (NotMinimal 0)
+      check (scripted [OP_0, OP_1, OP_1NEGATE]) [held 1000] `shouldBe` Right Nothing
+      check (scripted [opPushData signature, OP_DUP]) [held 1000] `shouldBe` Left (NotPushOnly 0)
+      -- bytes that are not a script at all
+      check ((spending [output 1] 900) {inputs = [TxIn (output 1) "\x4c" maxBound]} :: Tx) [held 1000]
+        `shouldBe` Left (NotPushOnly 0)
+
+  describe "the tokens of Bitcoin Cash" $ do
+    let category = B.replicate 32 9
+        -- a category made by this transaction: the id of what its first
+        -- input spends, whose index is 0
+        newCategory = encode (OutPoint (TxHash (doubleSHA256 ("genesis" :: ByteString))) 0).hash
+        from n = OutPoint (output n).hash n
+        tx ins outs = (spending ins 0) {outputs = [TxOut 1000 s | s <- outs]} :: Tx
+        coin s = TxOut 1000 s
+        plain = "\x76\xa9\x14" <> B.replicate 20 7 <> "\x88\xac"
+        fungible c n = withTokens c Nothing n
+        nft c capability commitment = withTokens c (Just (capability, commitment)) 0
+    it "lets tokens through as the inputs hold them" $ do
+      tokenRules (tx [from 1] [fungible category 400, fungible category 600]) [coin (fungible category 1000)]
+        `shouldBe` Right ()
+      -- burnt: fewer out than in
+      tokenRules (tx [from 1] [fungible category 10]) [coin (fungible category 1000)] `shouldBe` Right ()
+      tokenRules (tx [from 1] [plain]) [coin plain] `shouldBe` Right ()
+    it "refuses more fungible tokens out than in" $
+      tokenRules (tx [from 1, from 2] [fungible category 2000]) [coin (fungible category 1000), coin plain]
+        `shouldBe` Left (TokensUnbacked (concatMap (const "09") [1 .. 32 :: Int]))
+    it "makes tokens of a new category at will, from an input that spends an output 0" $ do
+      let genesisId = TxHash (doubleSHA256 ("genesis" :: ByteString))
+          genesis =
+            (tx [] [fungible newCategory 5000, nft newCategory 2 ""])
+              { inputs = [TxIn (OutPoint genesisId 0) "" maxBound]
+              } ::
+              Tx
+      tokenRules genesis [coin plain] `shouldBe` Right ()
+      -- the same category from an input that spends an output 1 is not new
+      let notNew = genesis {inputs = [TxIn (OutPoint genesisId 1) "" maxBound]} :: Tx
+      tokenRules notNew [coin plain] `shouldSatisfy` either (const True) (const False)
+    it "refuses tokens not written as tokens are" $
+      tokenRules (tx [from 1] ["\xef\x01"]) [coin plain] `shouldBe` Left (BadTokens 0)
+    it "keeps non-fungible tokens to what the inputs allow" $ do
+      let keep = tx [from 1] [nft category 0 "a"]
+      -- the same immutable token passes on; another commitment does not
+      tokenRules keep [coin (nft category 0 "a")] `shouldBe` Right ()
+      tokenRules keep [coin (nft category 0 "b")] `shouldSatisfy` either (const True) (const False)
+      -- a mutable one becomes any one token, not two
+      tokenRules keep [coin (nft category 1 "x")] `shouldBe` Right ()
+      tokenRules (tx [from 1] [nft category 0 "a", nft category 0 "b"]) [coin (nft category 1 "x")]
+        `shouldSatisfy` either (const True) (const False)
+      -- a minting one makes any, and only a minting one makes one that mints
+      tokenRules (tx [from 1] [nft category 0 "a", nft category 2 "b"]) [coin (nft category 2 "")]
+        `shouldBe` Right ()
+      tokenRules (tx [from 1] [nft category 2 "b"]) [coin (nft category 1 "")]
+        `shouldSatisfy` either (const True) (const False)
+
+  describe "a transaction that a peer sent" $ do
+    let relayed = judgeRelayed btc
+    it "says that every signature verifies of a spend of a coin locked to one key" $
+      relayed signed [keyCoin] `shouldBe` Right Nothing
+    it "refuses it when what was signed is not what is there" $ do
+      let tampered = signed {outputs = [o {value = o.value - 1} | o <- signed.outputs]} :: Tx
+      relayed tampered [keyCoin] `shouldBe` Left (Forged 0)
+    it "names the input that spends a coin locked by a script, which it cannot judge" $
+      relayed signed [scriptCoin] `shouldBe` Right (Just 0)
+    it "refuses outputs worth more than the inputs, whatever the signatures" $
+      relayed signed [keyCoin {value = 89999}] `shouldBe` Left Overspent
+    it "refuses the same output twice, a coinbase, and nothing to spend or pay" $ do
+      relayed (spending [output 1, output 1] 1) [keyCoin, keyCoin] `shouldBe` Left (DuplicateInput (output 1))
+      relayed (spending [nullOutPoint] 1) [keyCoin] `shouldBe` Left IsCoinbase
+      relayed (spending [] 1) [] `shouldBe` Left NoInputs
+      relayed (spending [output 1] 1) {outputs = []} [keyCoin] `shouldBe` Left NoOutputs
+    it "does not hold it to the policy of a node: dust, a version, a lock time that has not passed" $ do
+      -- 'judge' refuses each of these; of a transaction that a node
+      -- relayed they say nothing
+      let odd' = (spending [output 1] 1) {version = 9, locktime = 4000000000, inputs = [TxIn (output 1) "" 0]} :: Tx
+      judge rulesOf odd' [held 100000] `shouldSatisfy` either (const True) (const False)
+      relayed odd' [scriptCoin] `shouldBe` Right (Just 0)
+    it "holds a transaction of Bitcoin Cash to the rules of the tokens" $ do
+      let category = B.replicate 32 9
+          made = (spending [output 1] 0) {outputs = [TxOut 1000 (withTokens category Nothing 5)]} :: Tx
+      judgeRelayed bch made [scriptCoin] `shouldBe` Left (TokensUnbacked (concatMap (const "09") [1 .. 32 :: Int]))
+      -- on Bitcoin those bytes are a script like any other
+      judgeRelayed btc made [scriptCoin] `shouldBe` Right (Just 0)
diff --git a/test/Haskoin/Transaction/PsbtSpec.hs b/test/Haskoin/Transaction/PsbtSpec.hs
--- a/test/Haskoin/Transaction/PsbtSpec.hs
+++ b/test/Haskoin/Transaction/PsbtSpec.hs
@@ -1,1889 +1,3109 @@
 {-# LANGUAGE DuplicateRecordFields #-}
 {-# LANGUAGE ImportQualifiedPost #-}
-{-# LANGUAGE OverloadedRecordDot #-}
-{-# LANGUAGE OverloadedStrings #-}
-
--- | The PSBT format of BIP 174, and its version 2 of BIP 370: the vectors
--- of both BIPs, the bytes of a PSBT and the refusals of what breaks the
--- spec, the fields of the spec, the roles: combining, signing, finalizing
--- and extracting, and the inputs and outputs a PSBT of version 2 takes.
-module Haskoin.Transaction.PsbtSpec (spec) where
-
-import Control.Monad (foldM, forM_)
-import Crypto.Hash (Digest, SHA256, digestFromByteString)
-import Data.Aeson ((.:), (.:?))
-import Data.Aeson qualified as Json
-import Data.Bits (xor)
-import Data.ByteString (ByteString)
-import Data.ByteString qualified as B
-import Data.Bytes.Put (runPutS)
-import Data.Bytes.Serial (serialize)
-import Data.List (isPrefixOf, isSuffixOf)
-import Data.Map.Strict qualified as Map
-import Data.Maybe (fromJust, fromMaybe, isJust, listToMaybe, mapMaybe)
-import Data.Serialize qualified as S
-import Data.Text (Text)
-import Data.Text qualified as T
-import Data.Text.Encoding (encodeUtf8)
-import Data.Word (Word32, Word64, Word8)
-import Haskoin.Address
-import Haskoin.Crypto
-import Haskoin.Network.Constants
-import Haskoin.Network.Data
-import Haskoin.Script
-import Haskoin.Transaction
-import Haskoin.Util
-import Haskoin.Util.Arbitrary
-import Test.Hspec
-import Test.Hspec.QuickCheck (prop)
-import Test.QuickCheck
-
-{- The vectors of the BIP -}
-
--- The vectors live in data/psbt_bip174.json, copied from the BIP. Each has
--- the case the BIP gives, its hex, and its base64 when the BIP gives it.
-data Vector = Vector
-  { vecCase :: String,
-    vecHex :: Text,
-    vecBase64 :: Maybe Text
-  }
-
-instance Json.FromJSON Vector where
-  parseJSON = Json.withObject "vector" $ \o -> Vector <$> o .: "case" <*> o .: "hex" <*> o .:? "base64"
-
--- | The invalid PSBTs, the valid ones, the PSBTs of the walk-through of the
--- roles, in the order of the BIP, and the transaction its extractor gives
-data Vectors = Vectors
-  { invalid :: [Vector],
-    valid :: [Vector],
-    roles :: [Vector],
-    extracted :: Vector
-  }
-
-instance Json.FromJSON Vectors where
-  parseJSON = Json.withObject "vectors" $ \o -> Vectors <$> o .: "invalid" <*> o .: "valid" <*> o .: "roles" <*> o .: "extracted"
-
--- The PSBTs of the walk-through, by their place in it
-creator, updater, updaterWithSigHash, firstSigner, secondSigner, combiner, finalizer, unknownA, unknownB, unknownCombined, toCombineA, toCombineB, combined :: Vectors -> Vector
-creator v = roles v !! 0
-updater v = roles v !! 1
-updaterWithSigHash v = roles v !! 2
-firstSigner v = roles v !! 3
-secondSigner v = roles v !! 4
-combiner v = roles v !! 5
-finalizer v = roles v !! 6
-unknownA v = roles v !! 7
-unknownB v = roles v !! 8
-unknownCombined v = roles v !! 9
-toCombineA v = roles v !! 10
-toCombineB v = roles v !! 11
-combined v = roles v !! 12
-
-hexBytes :: Text -> ByteString
-hexBytes = fromJust . decodeHex
-
-bytesOf :: Vector -> ByteString
-bytesOf = hexBytes . vecHex
-
-expectRight :: Either String a -> IO a
-expectRight = either fail return
-
-forceRight :: Either String a -> a
-forceRight = either error id
-
-fingerprintOf :: Text -> Fingerprint
-fingerprintOf = forceRight . textToFingerprint
-
--- | The PSBT of a vector, which must decode
-psbtOfVector :: Vector -> IO Psbt
-psbtOfVector v = expectRight (decodePsbt (bytesOf v))
-
--- | The secret keys 1, 2 and 3 of the signer tests. Their public keys are
--- the points G, 2G and 3G of the curve.
-secretOne, secretTwo, secretThree :: SecKey
-secretOne = "0000000000000000000000000000000000000000000000000000000000000001"
-secretTwo = "0000000000000000000000000000000000000000000000000000000000000002"
-secretThree = "0000000000000000000000000000000000000000000000000000000000000003"
-
--- | The compressed public key of a secret key
-compressedKey :: SecKey -> PublicKey
-compressedKey secret = PublicKey (derivePubKey secret) True
-
--- | The map of the input, or of the output, at the index
-inputAt, outputAt :: Int -> Psbt -> PsbtMap
-inputAt i psbt = psbt.inputs !! i
-outputAt i psbt = psbt.outputs !! i
-
--- | A PSBT with the maps of its inputs replaced
-withInputs :: [PsbtMap] -> Psbt -> Psbt
-withInputs inputs psbt = Psbt psbt.version psbt.unsignedTx psbt.globals inputs psbt.outputs
-
--- | The PSBT with the flags given in its global map
-withFlags :: Modifiable -> Psbt -> Psbt
-withFlags flags psbt = Psbt psbt.version psbt.unsignedTx (insertTxModifiable flags psbt.globals) psbt.inputs psbt.outputs
-
-spec :: Spec
-spec = do
-  vectors <- runIO (readTestFile "psbt_bip174.json" :: IO Vectors)
-  vectors370 <- runIO (readTestFile "psbt_bip370.json" :: IO Vectors370)
-  vectors371 <- runIO (readTestFile "psbt_bip371.json" :: IO Vectors371)
-  do
-    vectorsSpec vectors
-    vectors370Spec vectors370
-    rolesSpec vectors
-    version2Spec
-    bytesSpec vectors
-    fieldsSpec vectors
-    signingSpec
-    signerChecksSpec
-    signerScopeSpec
-    coinsSpec
-    version2FieldsSpec
-    taprootChecksSpec vectors371
-    decoderChecksSpec
-    taprootSpec vectors371
-    complexSpec
-    core32Spec
-    propertiesSpec
-
-{- The vectors of BIP 370 -}
-
--- The vectors of BIP 370 live in data/psbt_bip370.json: the invalid
--- PSBTs, the valid ones, and the PSBTs of its lock time cases, each with
--- the lock time the BIP computes, none when it cannot be computed
-data LockTimeVector = LockTimeVector
-  { ltCase :: String,
-    ltHex :: Text,
-    ltLockTime :: Maybe Word32
-  }
-
-instance Json.FromJSON LockTimeVector where
-  parseJSON = Json.withObject "vector" $ \o -> LockTimeVector <$> o .: "case" <*> o .: "hex" <*> o .:? "locktime"
-
-data Vectors370 = Vectors370
-  { refused :: [Vector],
-    accepted :: [Vector],
-    lockTimes :: [LockTimeVector]
-  }
-
-instance Json.FromJSON Vectors370 where
-  parseJSON = Json.withObject "vectors" $ \o -> Vectors370 <$> o .: "invalid" <*> o .: "valid" <*> o .: "locktime"
-
--- | Why each invalid PSBT of BIP 370 is refused, in the order of the BIP:
--- a field of the other version, a field version 2 requires missing, a
--- lock time out of its range
-refusals370 :: [String]
-refusals370 =
-  [ "The global map: the key 0x00 is not of PSBT version 2",
-    "The global map: the key 0x02 is not of PSBT version 0",
-    "The global map: the key 0x03 is not of PSBT version 0",
-    "The global map: the key 0x04 is not of PSBT version 0",
-    "The global map: the key 0x05 is not of PSBT version 0",
-    "The global map: the key 0x06 is not of PSBT version 0",
-    "Input 0: the key 0x0e is not of PSBT version 0",
-    "Input 0: the key 0x0f is not of PSBT version 0",
-    "Input 0: the key 0x10 is not of PSBT version 0",
-    "Input 0: the key 0x11 is not of PSBT version 0",
-    "Input 0: the key 0x12 is not of PSBT version 0",
-    "Output 0: the key 0x03 is not of PSBT version 0",
-    "Output 0: the key 0x04 is not of PSBT version 0",
-    "The global map: the key 0x00 is not of PSBT version 2",
-    "The global map has no input count",
-    "The global map has no output count",
-    "The global map has no transaction version",
-    "Input 0 has no previous transaction id",
-    "Input 0 has no output index",
-    "Output 0 has no amount",
-    "Output 0 has no script",
-    "Input 0: the value of the key 0x11 is a time lock below 500000000",
-    "Input 0: the value of the key 0x12 is not a height between 1 and 499999999",
-    "Input 0: the value of the key 0x12 is not a height between 1 and 499999999"
-  ]
-
-vectors370Spec :: Vectors370 -> Spec
-vectors370Spec vectors = do
-  describe "The invalid PSBTs of BIP 370 are refused, each for its reason" $
-    forM_ (zip vectors.refused refusals370) $ \(v, reason) ->
-      it v.vecCase $ decodePsbt (bytesOf v) `shouldBe` Left reason
-
-  describe "The valid PSBTs of BIP 370 are read as version 2, and written back byte for byte" $
-    forM_ vectors.accepted $ \v ->
-      it v.vecCase $ do
-        psbt <- psbtOfVector v
-        psbt.version `shouldBe` Version2
-        encodePsbt psbt `shouldBe` bytesOf v
-
-  describe "The transaction of a PSBT of version 2 is the one its fields describe" $
-    -- The first valid PSBT of the BIP: one input, two outputs, nothing
-    -- else. Its input has no sequence field, so its sequence is final,
-    -- and no input requires a lock time, nor is a fallback given: lock
-    -- time 0.
-    it "for the first valid PSBT of the BIP, with a sequence and a lock time that no field gives" $ do
-      psbt <- psbtOfVector (vectors.accepted !! 0)
-      psbt.unsignedTx
-        `shouldBe` Tx
-          2
-          [TxIn (OutPoint "c85f81844094f9f0eec1e41f8d63e0a99e9f73dc725d7319871c9c4121d90a0b" 0) "" 0xffffffff]
-          [ TxOut 800000000 (hexBytes "0014c430f64c4756da310dbd1a085572ef299926272c"),
-            TxOut 199998859 (hexBytes "00144dd193ac964a56ac1b9e1cca8454fe2f474f8513")
-          ]
-          []
-          0
-
-  describe "The lock time of a PSBT of version 2 is the one BIP 370 determines" $
-    forM_ vectors.lockTimes $ \v ->
-      it v.ltCase $
-        ((.unsignedTx.locktime) <$> decodePsbt (hexBytes v.ltHex))
-          `shouldBe` maybe (Left "No lock time fits every input: some require a height, others a time") Right v.ltLockTime
-
-{- The vectors -}
-
--- | Why each invalid PSBT of BIP 174 is refused, in the order of the BIP,
--- as the start of the reason. The cases are: no magic bytes, a map
--- missing, a script in the unsigned transaction, no unsigned transaction,
--- a key twice, twelve keys whose data is not what their type takes, and
--- an unsigned transaction that is not in the serialization without witness
--- or not whole.
-refusals174 :: [String]
-refusals174 =
-  [ "Not a PSBT: the bytes do not start with the magic bytes of BIP 174",
-    "The PSBT ends inside output 0",
-    "The unsigned transaction has an input with a script",
-    "The global map has no unsigned transaction",
-    "Input 0 has the key 0x00 twice",
-    "The global map: the key 0x00 with the data 01 carries data",
-    "Input 0: the key 0x01 with the data 00 carries data",
-    "Input 0: the key 0x02 with the data 03b1341ccba7683b6af4f1238cd6e97e7167d569fac47f1e48d47541844355bd is not a public key",
-    "Input 0: the key 0x04 with the data 00 carries data",
-    "Input 0: the key 0x05 with the data 00 carries data",
-    "Input 0: the key 0x06 with the data 03b1341ccba7683b6af4f1238cd6e97e7167d569fac47f1e48d47541844355bd is not a public key",
-    "Input 0: the key 0x00 with the data 00 carries data",
-    "Input 0: the key 0x07 with the data 00 carries data",
-    "Input 1: the key 0x08 with the data 00 carries data",
-    "Output 0: the key 0x02 with the data 03a9a4c37f5996d3aa25dbac6b570af0650394492942460b354753ed9eeca587 is not a public key",
-    "Input 0: the key 0x03 with the data 00 carries data",
-    "Output 0: the key 0x00 with the data 00 carries data",
-    "Output 1: the key 0x01 with the data 0025512103b7ce23a01c5b4bf00a642537cdfabb315b668332867478ef51309d",
-    "The unsigned transaction does not decode",
-    "The unsigned transaction does not decode"
-  ]
-
-vectorsSpec :: Vectors -> Spec
-vectorsSpec vectors = do
-  describe "The invalid PSBTs of BIP 174 are refused, each for its reason" $
-    forM_ (zip vectors.invalid refusals174) $ \(v, reason) ->
-      it v.vecCase $ decodePsbt (bytesOf v) `shouldSatisfy` either (reason `isPrefixOf`) (const False)
-
-  describe "The valid PSBTs of BIP 174 are read, and written back byte for byte" $
-    forM_ vectors.valid $ \v ->
-      it v.vecCase $ (encodePsbt <$> decodePsbt (bytesOf v)) `shouldBe` Right (bytesOf v)
-
-  describe "The valid PSBTs of BIP 174 read the same from their base64 text" $
-    forM_ [(v, text) | v <- vectors.valid, Just text <- [v.vecBase64]] $ \(v, text) ->
-      it v.vecCase $ (encodePsbt <$> decodePsbtBase64 (encodeUtf8 text)) `shouldBe` Right (bytesOf v)
-
-  -- The combiner's PSBT of the two signed ones lists the signatures of
-  -- its second input out of order: see 'rolesSpec'
-  describe "The PSBTs of the roles of BIP 174 are read, and written back byte for byte" $
-    forM_ [v | v <- vectors.roles, v.vecCase /= (combiner vectors).vecCase] $ \v ->
-      it v.vecCase $ (encodePsbt <$> decodePsbt (bytesOf v)) `shouldBe` Right (bytesOf v)
-
-rolesSpec :: Vectors -> Spec
-rolesSpec vectors =
-  describe "The roles of BIP 174" $ do
-    it "the creator's PSBT is the unsigned transaction with empty maps" $ do
-      psbt <- psbtOfVector (creator vectors)
-      psbtOf psbt.unsignedTx `shouldBe` psbt
-
-    it "the transaction extractor gives the transaction of the finalizer's PSBT" $ do
-      psbt <- psbtOfVector (finalizer vectors)
-      (S.encode <$> psbtTransaction psbt) `shouldBe` Right (bytesOf (extracted vectors))
-
-    -- BIP 174: the extractor "checks whether all inputs have complete
-    -- scriptSigs and scriptWitnesses", and otherwise "must not modify the
-    -- PSBT". Bitcoin Core gives no transaction then (FinalizeAndExtractPSBT).
-    it "the transaction extractor refuses a PSBT with an input that is not final" $ do
-      psbt <- psbtOfVector (creator vectors)
-      psbtTransaction psbt `shouldBe` Left "Input 0 is not final"
-
-    it "the transaction of a PSBT that is still being signed has the final scripts of the inputs that have them" $ do
-      unsigned <- psbtOfVector (creator vectors)
-      psbtPartialTransaction unsigned `shouldBe` Right unsigned.unsignedTx
-      final <- psbtOfVector (finalizer vectors)
-      -- The second input loses its final script and witness
-      let halfFinal = withInputs [inputAt 0 final, Map.delete (Key 0x07 "") (Map.delete (Key 0x08 "") (inputAt 1 final))] final
-      psbtTransaction halfFinal `shouldBe` Left "Input 1 is not final"
-      (map (B.null . (.script)) . (.inputs) <$> psbtPartialTransaction halfFinal) `shouldBe` Right [False, True]
-      ((.witness) <$> psbtPartialTransaction halfFinal) `shouldBe` Right []
-
-    -- The updater's PSBT gives the coin of its second input, a P2SH-P2WSH
-    -- one, as a witness output only, as BIP 174 did before CVE-2020-14199
-    -- was known. A signer that wants previous transactions refuses it.
-    it "a signer that trusts witness outputs makes the first signer's PSBT of the BIP from the updater's, and the second signer's" $ do
-      psbt <- psbtOfVector (updaterWithSigHash vectors)
-      let master = fromJust (xPrvImport btcTest "tprv8ZgxMBicQKsPd9TeAdPADNnSyH9SSUUbTVeFszDE23Ki6TBB5nCefAdHkK8Fm3qMQR6sHwA56zqRmKmxnHk37JkiFzvncDqoKmPWubu7hDF")
-          trusting = (xPrvSigner master Nothing) {requirePreviousTx = False}
-          holding paths = trusting {keyOfRecord = \public derivation -> if derivation.path `elem` paths then trusting.keyOfRecord public derivation else Nothing}
-      (encodePsbt <$> signPsbt btcTest (holding ["m/0'/0'/0'", "m/0'/0'/2'"]) psbt) `shouldBe` Right (bytesOf (firstSigner vectors))
-      (encodePsbt <$> signPsbt btcTest (holding ["m/0'/0'/1'", "m/0'/0'/3'"]) psbt) `shouldBe` Right (bytesOf (secondSigner vectors))
-      signPsbt btcTest (xPrvSigner master Nothing) psbt
-        `shouldBe` Left "Input 1: the coin is given as a witness output only, and the signer requires the previous transaction of a SegWit version 0 coin"
-
-    -- The four cases the BIP lists under "Fails Signer checks", signed
-    -- with the master key of the BIP. The input at fault never gains a
-    -- signature. The numbers are the partial signatures of each input.
-    describe "a signer adds no signature to the input at fault of the PSBTs that fail the signer checks of the BIP" $ do
-      let master = fromJust (xPrvImport btcTest "tprv8ZgxMBicQKsPd9TeAdPADNnSyH9SSUUbTVeFszDE23Ki6TBB5nCefAdHkK8Fm3qMQR6sHwA56zqRmKmxnHk37JkiFzvncDqoKmPWubu7hDF")
-          trusting = (xPrvSigner master Nothing) {requirePreviousTx = False}
-          counts = mapM (fmap length . partialSignatures) . (.inputs)
-          failing i = psbtOfVector (vectors.valid !! i)
-      -- No record names a key, so the signer holds none: nothing is signed
-      it "a witness output for a legacy coin" $ do
-        psbt <- failing 10
-        counts psbt `shouldBe` Right [0, 0]
-        (counts =<< signPsbt btcTest trusting psbt) `shouldBe` Right [0, 0]
-      -- The redeem script of input 0 is no standard script, and does not
-      -- hash to the coin. Input 1 is sound and is signed.
-      it "a redeem script that does not match the coin, with the previous transaction" $ do
-        psbt <- failing 11
-        counts psbt `shouldBe` Right [1, 1]
-        (counts =<< signPsbt btcTest trusting psbt) `shouldBe` Right [1, 2]
-      it "a redeem script that does not match the coin, with the witness output" $ do
-        psbt <- failing 12
-        signPsbt btcTest trusting psbt `shouldBe` Left "Input 1: the redeem script of the input does not hash to its coin"
-      -- The witness script of input 1 is no standard script. Input 0 is
-      -- sound and is signed.
-      it "a witness script that does not match the redeem script" $ do
-        psbt <- failing 13
-        counts psbt `shouldBe` Right [1, 1]
-        (counts =<< signPsbt btcTest trusting psbt) `shouldBe` Right [2, 1]
-
-    -- The spec does not say in which order a combiner writes the keys of a
-    -- map. The BIP's combiner lists the two signatures of the second input
-    -- out of order; the keys of a map are written in order here, as
-    -- Bitcoin Core writes them. The PSBTs are the same, byte for byte once
-    -- the BIP's is written back.
-    it "the combiner's PSBT is that of the two signers combined, whatever the order of its inputs" $ do
-      a <- psbtOfVector (firstSigner vectors)
-      b <- psbtOfVector (secondSigner vectors)
-      both <- psbtOfVector (combiner vectors)
-      combinePsbt a b `shouldBe` Right both
-      combinePsbt b a `shouldBe` Right both
-      encodePsbt both `shouldNotBe` bytesOf (combiner vectors)
-      decodePsbt (encodePsbt both) `shouldBe` Right both
-
-    it "the two PSBTs with unknown keys combine as the combiner of the BIP that orders keys lexicographically does" $ do
-      a <- psbtOfVector (unknownA vectors)
-      b <- psbtOfVector (unknownB vectors)
-      (encodePsbt <$> combinePsbt a b) `shouldBe` Right (bytesOf (unknownCombined vectors))
-      (encodePsbt <$> combinePsbt b a) `shouldBe` Right (bytesOf (unknownCombined vectors))
-
-    it "the two PSBTs to combine give the combiner's PSBT" $ do
-      a <- psbtOfVector (toCombineA vectors)
-      b <- psbtOfVector (toCombineB vectors)
-      (encodePsbt <$> combinePsbt a b) `shouldBe` Right (bytesOf (combined vectors))
-
-    it "PSBTs of different transactions are not combined" $ do
-      a <- psbtOfVector (creator vectors)
-      combinePsbt a (psbtOf emptyTx) `shouldBe` Left "The PSBTs are not of the same transaction"
-
-    it "the updater's PSBT with SIGHASH_ALL is the updater's PSBT with the sighash type on every input" $ do
-      psbt <- psbtOfVector (updater vectors)
-      encodePsbt (withInputs (insertSigHashType sigHashAll <$> psbt.inputs) psbt) `shouldBe` bytesOf (updaterWithSigHash vectors)
-
-    it "the finalizer's PSBT is the combiner's PSBT finalized" $ do
-      psbt <- psbtOfVector (combiner vectors)
-      (encodePsbt <$> finalizePsbt btc psbt) `shouldBe` Right (bytesOf (finalizer vectors))
-
-    it "the finalizer leaves an input without enough signatures as it is" $ do
-      psbt <- psbtOfVector (firstSigner vectors)
-      finalizePsbt btc psbt `shouldBe` Right psbt
-
-{- The roles of version 2 -}
-
--- | The input and output of the PSBTs below: the coin and the first output
--- of the first valid PSBT of BIP 370, and another output of the same
--- transaction as the coin
-coinInput, otherInput :: TxIn
-coinInput = TxIn (OutPoint "c85f81844094f9f0eec1e41f8d63e0a99e9f73dc725d7319871c9c4121d90a0b" 0) "" 0xfffffffd
-otherInput = TxIn (OutPoint "c85f81844094f9f0eec1e41f8d63e0a99e9f73dc725d7319871c9c4121d90a0b" 1) "" 0xfffffffd
-
-paidOutput :: TxOut
-paidOutput = TxOut 800000000 (hexBytes "0014c430f64c4756da310dbd1a085572ef299926272c")
-
-version2Spec :: Spec
-version2Spec =
-  describe "A PSBT of version 2" $ do
-    -- A creator of BIP 370 starts with no input and no output. The
-    -- created one, with its flags set so that inputs and outputs can be
-    -- added, and with the input and the output added.
-    let created = withVersion Version2 (psbtOf (Tx 2 [] [] [] 0))
-        modifiable = withFlags (Modifiable True True False 0) created
-        built = forceRight (addOutput paidOutput Map.empty =<< addInput coinInput Map.empty modifiable)
-        -- The same without its flags, as a constructor leaves it once
-        -- nothing is to be added
-        unflagged = Psbt Version2 built.unsignedTx (deleteTxModifiable built.globals) built.inputs built.outputs
-        requiring field value = addInput otherInput (field value Map.empty)
-
-    -- The fields of the global map: the transaction version 2, the
-    -- fallback lock time 0, the two counts of 0, and the PSBT version 2
-    it "is created with no input and no output, and the fields that describe its transaction" $
-      encodeHex (encodePsbt created) `shouldBe` "70736274ff0102040200000001030400000000010401000105010001fb040200000000"
-
-    it "takes no input or output unless its flags allow it" $ do
-      addInput coinInput Map.empty created `shouldBe` Left "The inputs of the PSBT may not be modified"
-      addOutput paidOutput Map.empty created `shouldBe` Left "The outputs of the PSBT may not be modified"
-
-    -- The input is described by the id of the transaction it spends from,
-    -- in the byte order of a transaction, the index of the output and its
-    -- sequence; the output by its amount and its script
-    it "takes an input and an output at the end, counted, described in their maps, and in its transaction" $ do
-      built.unsignedTx `shouldBe` Tx 2 [coinInput] [paidOutput] [] 0
-      Map.lookup (Key 0x04 "") built.globals `shouldBe` Just "\x01"
-      Map.lookup (Key 0x05 "") built.globals `shouldBe` Just "\x01"
-      inputAt 0 built
-        `shouldBe` Map.fromList
-          [ (Key 0x0e "", hexBytes "0b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8"),
-            (Key 0x0f "", hexBytes "00000000"),
-            (Key 0x10 "", hexBytes "fdffffff")
-          ]
-      outputAt 0 built `shouldBe` Map.fromList [(Key 0x03 "", hexBytes "0008af2f00000000"), (Key 0x04 "", hexBytes "0014c430f64c4756da310dbd1a085572ef299926272c")]
-
-    it "refuses an input that spends an output it spends already" $
-      addInput coinInput Map.empty built `shouldBe` Left "An input of the PSBT spends that output already"
-
-    it "is not of version 0, which takes no input or output" $
-      addInput coinInput Map.empty (psbtOf emptyTx) `shouldBe` Left "A PSBT of version 0 takes no input or output: its transaction is fixed"
-
-    it "takes the lock time its inputs require: the greatest height when every one that requires a lock time takes a height" $ do
-      withHeight <- expectRight (addInput coinInput (insertRequiredHeightLockTime 10000 Map.empty) modifiable)
-      withHeight.unsignedTx.locktime `shouldBe` 10000
-      ((.unsignedTx.locktime) <$> requiring insertRequiredHeightLockTime 9000 withHeight) `shouldBe` Right 10000
-      requiring insertRequiredTimeLockTime 1657048460 withHeight `shouldBe` Left "No lock time fits every input: some require a height, others a time"
-
-    -- The input of the PSBT has its final script
-    it "refuses an input that changes the lock time once an input is signed, and takes one that keeps it" $ do
-      let signed = withInputs [insertFinalScriptSig "\x00" (inputAt 0 built)] built
-      requiring insertRequiredHeightLockTime 10000 signed `shouldBe` Left "An input is signed already: the lock time may not change"
-      ((.unsignedTx.locktime) <$> addInput otherInput Map.empty signed) `shouldBe` Right 0
-
-    it "takes a sequence for an input, in its transaction and in its map, as an updater sets one" $ do
-      updated <- expectRight (setInputSequence 0 1 built)
-      map (.sequence) updated.unsignedTx.inputs `shouldBe` [1]
-      Map.lookup (Key 0x10 "") (inputAt 0 updated) `shouldBe` Just (hexBytes "01000000")
-      setInputSequence 1 1 built `shouldBe` Left "The PSBT has no input 1"
-      setInputSequence 0 1 (psbtOf emptyTx) `shouldBe` Left "The sequences of a PSBT of version 0 are in its unsigned transaction, which is fixed"
-      -- A signature commits to the sequence of its input
-      setInputSequence 0 1 (withInputs [insertFinalScriptSig "\x00" (inputAt 0 built)] built) `shouldBe` Left "Input 0 is signed already: its sequence may not change"
-
-    -- The id of its transaction with the sequence of its input at 0: the
-    -- same whatever the sequence. A PSBT of version 0 is identified by
-    -- its transaction as it is, with the sequence 0xfffffffd here.
-    it "is identified by its transaction with every sequence at 0" $ do
-      psbtId built `shouldBe` "79dd9a151a6cfc0dc3b7779a697817a80544e2c9dc0cfb399ecc7fa3b4da8f2c"
-      (psbtId <$> setInputSequence 0 1 built) `shouldBe` Right "79dd9a151a6cfc0dc3b7779a697817a80544e2c9dc0cfb399ecc7fa3b4da8f2c"
-      psbtId (withVersion Version0 built) `shouldBe` "7ca9f2c2ff60a7a3f7efdaa703bfb23b9415639e07b71e194bafb4d592e2c405"
-
-    it "combines with the same PSBT whose sequence an updater changed, and keeps the sequence of the first" $ do
-      updated <- expectRight (setInputSequence 0 1 built)
-      (map (.sequence) . (.unsignedTx.inputs) <$> combinePsbt built updated) `shouldBe` Right [0xfffffffd]
-      (map (.sequence) . (.unsignedTx.inputs) <$> combinePsbt updated built) `shouldBe` Right [1]
-
-    it "does not combine with a PSBT of version 0" $
-      combinePsbt built (withVersion Version0 built) `shouldBe` Left "The PSBTs are not of the same version"
-
-    -- The first lets inputs be added and has a SIGHASH_SINGLE signature;
-    -- the second lets inputs and outputs be added, with the undefined
-    -- bit 3 set
-    it "combines its flags as Bitcoin Core does: modifiable only when both say so, with a SIGHASH_SINGLE signature of either" $ do
-      (txModifiable . (.globals) <$> combinePsbt (withFlags (Modifiable True False True 0) built) (withFlags (Modifiable True True False 8) built))
-        `shouldBe` Right (Right (Just (Modifiable True False True 0)))
-      (txModifiable . (.globals) <$> combinePsbt unflagged (withFlags (Modifiable True False True 0) built))
-        `shouldBe` Right (Right (Just (Modifiable False False True 0)))
-
-    it "once signed, takes no more inputs unless the sighash has ANYONECANPAY, no more outputs unless it is NONE, and tells a SIGHASH_SINGLE signature" $ do
-      let open = withFlags (Modifiable True True False 0) built
-          flagsAfter sighash psbt = txModifiable (afterSignature sighash psbt).globals
-      flagsAfter sigHashAll open `shouldBe` Right (Just (Modifiable False False False 0))
-      flagsAfter (setAnyoneCanPay sigHashNone) open `shouldBe` Right (Just (Modifiable True True False 0))
-      flagsAfter sigHashSingle open `shouldBe` Right (Just (Modifiable False False True 0))
-      flagsAfter sigHashAll unflagged `shouldBe` Right Nothing
-      flagsAfter sigHashSingle unflagged `shouldBe` Right (Just (Modifiable False False True 0))
-
-    it "converted to version 0 is the PSBT of its transaction" $
-      withVersion Version0 built `shouldBe` psbtOf (Tx 2 [coinInput] [paidOutput] [] 0)
-
-{- Bytes -}
-
--- | A transaction with nothing in it: version 0, no input, no output, lock
--- time 0, which is "0000000000000000000000" over ten bytes
-emptyTx :: Tx
-emptyTx = Tx 0 [] [] [] 0
-
--- | The global map of the PSBT of 'emptyTx': the key of the unsigned
--- transaction, one byte of type 0x00, and the ten bytes of the transaction
-emptyTxEntry :: Text
-emptyTxEntry = "01000a00000000000000000000"
-
-bytesSpec :: Vectors -> Spec
-bytesSpec vectors =
-  describe "The bytes of a PSBT" $ do
-    -- The vector of the BIP for a transaction without inputs or outputs
-    it "are the magic bytes, the unsigned transaction, and a map for each input and output" $
-      encodePsbt (psbtOf emptyTx) `shouldBe` hexBytes ("70736274ff" <> emptyTxEntry <> "00")
-
-    -- The key is 7 bytes: the type 0xfc, the identifier "test" after its
-    -- length 4, and the subtype 0. The value is the 3 bytes of "btc".
-    it "write a key as its length, its type and its data, and its value after its length" $
-      encodePsbt (Psbt Version0 emptyTx (insertProprietary "test" 0 "btc" Map.empty) [] [])
-        `shouldBe` hexBytes ("70736274ff" <> emptyTxEntry <> "07fc047465737400" <> "03627463" <> "00")
-
-    it "write the keys of a map in order, the type first, whatever the order they were added" $ do
-      let globals = Map.fromList [(Key 0x20 "", hexBytes "bb"), (Key 0x10 (hexBytes "01"), hexBytes "aa")]
-      encodePsbt (Psbt Version0 emptyTx globals [] [])
-        `shouldBe` hexBytes ("70736274ff" <> emptyTxEntry <> "02100101aa" <> "012001bb" <> "00")
-
-    it "write the unsigned transaction without the input scripts and the witness of a signed one" $ do
-      signed <- expectRight $ S.decode (bytesOf (extracted vectors))
-      psbt <- psbtOfVector (finalizer vectors)
-      (psbtOf signed).unsignedTx `shouldBe` psbt.unsignedTx
-
-    it "tell a PSBT from other bytes by its first five" $ do
-      isPsbt (bytesOf (creator vectors)) `shouldBe` True
-      isPsbt "{\"tx\": \"0200\"}" `shouldBe` False
-
-    it "accept the unsigned transaction after another key of the global map" $
-      decodePsbt (hexBytes ("70736274ff" <> "012001bb" <> emptyTxEntry <> "00"))
-        `shouldBe` Right (Psbt Version0 emptyTx (Map.fromList [(Key 0x20 "", hexBytes "bb")]) [] [])
-
-    it "refuse what is not a PSBT" $
-      decodePsbt "{\"tx\": \"0200\"}" `shouldBe` Left "Not a PSBT: the bytes do not start with the magic bytes of BIP 174"
-
-    it "refuse a key twice in a map, naming it" $
-      decodePsbt (hexBytes ("70736274ff" <> emptyTxEntry <> "012001aa" <> "012001bb" <> "00"))
-        `shouldBe` Left "The global map has the key 0x20 twice"
-
-    it "refuse bytes after the last map" $
-      decodePsbt (bytesOf (creator vectors) <> "\0") `shouldBe` Left "Bytes follow the last map"
-
-    -- Version 1 was never defined
-    it "refuse a PSBT of a version other than 0 and 2" $
-      decodePsbt (hexBytes ("70736274ff" <> emptyTxEntry <> "01fb0401000000" <> "00"))
-        `shouldBe` Left "The PSBT is of version 1: only versions 0 and 2 are supported"
-
-    -- The length of the first key, 1, written over three bytes
-    it "refuse a length that is not in its shortest form" $
-      decodePsbt (hexBytes ("70736274ff" <> "fd0100" <> "000a00000000000000000000" <> "00"))
-        `shouldBe` Left "A length in the global map is not in its shortest form"
-
-    -- The PSBT with 0 inputs and 2 outputs of the BIP, without the two
-    -- bytes that end its output maps
-    it "refuse bytes that end inside a map" $ do
-      let withoutOutputs = bytesOf (vectors.valid !! 9)
-      decodePsbt (B.take (B.length withoutOutputs - 2) withoutOutputs) `shouldBe` Left "The PSBT ends inside output 0"
-
-    it "refuse a key of the spec that carries data it should not, naming it" $
-      decodePsbt (bytesOf (vectors.invalid !! 15)) `shouldBe` Left "Input 0: the key 0x03 with the data 00 carries data"
-
-    it "refuse a derivation key that is not a public key" $
-      decodePsbt (bytesOf (vectors.invalid !! 10)) `shouldSatisfy` either ("is not a public key" `isSuffixOf`) (const False)
-
-    it "read the base64 text of a PSBT, with spaces and line breaks around it" $ do
-      let v = vectors.valid !! 0
-      (encodePsbt <$> decodePsbtBase64 (" " <> encodeUtf8 (fromMaybe "" v.vecBase64) <> "\n")) `shouldBe` Right (bytesOf v)
-
-    it "write the base64 text the BIP gives" $ do
-      let v = vectors.valid !! 0
-      psbt <- psbtOfVector v
-      Just (encodePsbtBase64 psbt) `shouldBe` (encodeUtf8 <$> v.vecBase64)
-
-    it "refuse text that is not base64" $
-      decodePsbtBase64 "not base64!" `shouldBe` Left "Not the base64 text of a PSBT"
-
-{- Fields -}
-
--- | The signature of the first signer of the BIP on the first input, as
--- Bitcoin Core decodes its PSBT
-firstSignature :: Text
-firstSignature = "3044022074018ad4180097b873323c0015720b3684cc8123891048e7dbcd9b55ad679c99022073d369b740e3eb53dcefa33823c8070514ca55a7dd9544f157c167913261118c01"
-
--- | The key of the first signer of the BIP, at m/0'/0'/0' of the master
--- key d90c6a4f
-firstKey :: Text
-firstKey = "029583bf39ae0a609747ad199addd634fa6108559d6c5cd39b4c2183f1ab96e07f"
-
--- The literal values below are those Bitcoin Core 25.0 shows for the
--- vectors with decodepsbt.
-fieldsSpec :: Vectors -> Spec
-fieldsSpec vectors =
-  describe "The fields of a PSBT" $ do
-    let publicKey text = forceRight (decodeSerial (hexBytes text)) :: PublicKey
-        shown :: [(PublicKey, Derivation)] -> [(Text, Derivation)]
-        shown records = [(encodeHex (encodeSerial key), derivation) | (key, derivation) <- records]
-
-    it "read the derivation records of an input: the public key, the fingerprint of the master key and the path" $ do
-      psbt <- psbtOfVector (updater vectors)
-      records <- expectRight $ inputDerivations (inputAt 0 psbt)
-      shown records
-        `shouldBe` [ (firstKey, Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/0'"),
-                     ("02dab61ff49a14db6a7d02b0cd1fbb78fc4b18312b5b4e54dae4dba2fbfef536d7", Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/1'")
-                   ]
-
-    it "read the derivation records of an output" $ do
-      psbt <- psbtOfVector (updater vectors)
-      records <- expectRight $ outputDerivations (outputAt 0 psbt)
-      shown records `shouldBe` [("03a9a4c37f5996d3aa25dbac6b570af0650394492942460b354753ed9eeca58771", Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/4'")]
-
-    -- The path is 0' (0x80000000) three times, each over four bytes,
-    -- little-endian
-    it "write a derivation record as the public key under the type, and the fingerprint then the path, four bytes an index" $ do
-      let key = publicKey firstKey
-      Map.toList (insertInputDerivation key (Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/0'") Map.empty)
-        `shouldBe` [(Key 0x06 (hexBytes firstKey), hexBytes ("d90c6a4f" <> "00000080" <> "00000080" <> "00000080"))]
-      Map.keys (insertOutputDerivation key (Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/4'") Map.empty)
-        `shouldBe` [Key 0x02 (hexBytes firstKey)]
-
-    it "read the sighash type of an input, when it has one" $ do
-      with <- psbtOfVector (updaterWithSigHash vectors)
-      without <- psbtOfVector (updater vectors)
-      mapM sigHashType with.inputs `shouldBe` Right [Just sigHashAll, Just sigHashAll]
-      mapM sigHashType without.inputs `shouldBe` Right [Nothing, Nothing]
-
-    -- SIGHASH_ALL with the FORKID flag of Bitcoin Cash, 0x41
-    it "write the sighash type over four bytes, little-endian, and drop it as a finalizer does" $ do
-      Map.toList (insertSigHashType (setForkIdFlag sigHashAll) Map.empty) `shouldBe` [(Key 0x03 "", hexBytes "41000000")]
-      Map.keys (deleteSigHashType (insertSigHashType sigHashAll (insertNonWitnessUtxo emptyTx Map.empty))) `shouldBe` [Key 0x00 ""]
-
-    it "read the whole previous transaction of an input" $ do
-      psbt <- psbtOfVector (vectors.valid !! 0)
-      parent <- expectRight $ nonWitnessUtxo (inputAt 0 psbt)
-      (txHashToHex . txHash <$> parent) `shouldBe` Just "f61b1742ca13176464adb3cb66050c00787bb3a4eead37e985f2df1e37718126"
-
-    it "write a previous transaction under the type 0x00" $ do
-      psbt <- psbtOfVector (vectors.valid !! 0)
-      parent <- expectRight $ nonWitnessUtxo (inputAt 0 psbt)
-      Map.toList (insertNonWitnessUtxo emptyTx Map.empty) `shouldBe` [(Key 0x00 "", hexBytes "00000000000000000000")]
-      nonWitnessUtxo (maybe Map.empty (`insertNonWitnessUtxo` Map.empty) parent) `shouldBe` Right parent
-
-    -- The second input of the vector spends 1 BTC at a P2SH address
-    it "read the output an input spends when the PSBT has it alone, and write it under the type 0x01" $ do
-      psbt <- psbtOfVector (vectors.valid !! 1)
-      let coin = TxOut 100000000 (hexBytes "a9143545e6e33b832c47050f24d3eeb93c9c03948bc787")
-      mapM witnessUtxo psbt.inputs `shouldBe` Right [Nothing, Just coin]
-      Map.toList (insertWitnessUtxo coin Map.empty) `shouldBe` [(Key 0x01 "", hexBytes "00e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787")]
-
-    it "tell an input with partial signatures from one without" $ do
-      partial <- psbtOfVector (vectors.valid !! 4)
-      unsigned <- psbtOfVector (vectors.valid !! 0)
-      hasPartialSignatures (inputAt 0 partial) `shouldBe` True
-      hasPartialSignatures (inputAt 0 unsigned) `shouldBe` False
-
-    -- The first signer of the BIP signs the first input with SIGHASH_ALL,
-    -- the last byte 01 of the signature
-    it "read the partial signatures of an input: the public key, and the signature with its sighash byte" $ do
-      psbt <- psbtOfVector (firstSigner vectors)
-      records <- expectRight (partialSignatures (inputAt 0 psbt))
-      [(encodeHex (encodeSerial key), encodeHex signature) | (key, signature) <- records] `shouldBe` [(firstKey, firstSignature)]
-
-    it "write a partial signature under the type 0x02 with the public key, and drop them all as a finalizer does" $ do
-      let m = insertPartialSignature (publicKey firstKey) (hexBytes firstSignature) (insertSigHashType sigHashAll Map.empty)
-      Map.toList m `shouldBe` [(Key 0x02 (hexBytes firstKey), hexBytes firstSignature), (Key 0x03 "", hexBytes "01000000")]
-      Map.toList (deletePartialSignatures m) `shouldBe` [(Key 0x03 "", hexBytes "01000000")]
-
-    -- The second input of the updater's PSBT spends a P2SH-P2WSH coin: a
-    -- 2-of-2 multisig behind a witness program
-    it "read the redeem script and the witness script of an input, and write them under the types 0x04 and 0x05" $ do
-      psbt <- psbtOfVector (updater vectors)
-      let redeem = Script [OP_0, opPushData (hexBytes "8c2353173743b595dfb4a07b72ba8e42e3797da74e87fe7d9d7497e3b2028903")]
-          witness = Script [OP_2, opPushData (hexBytes "03089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc"), opPushData (hexBytes "023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e73"), OP_2, OP_CHECKMULTISIG]
-      inputRedeemScript (inputAt 1 psbt) `shouldBe` Right (Just redeem)
-      inputWitnessScript (inputAt 1 psbt) `shouldBe` Right (Just witness)
-      inputRedeemScript (inputAt 0 psbt) `shouldSatisfy` (\found -> fmap (const ()) found == Right () && found /= Right Nothing)
-      Map.toList (insertInputRedeemScript redeem (insertInputWitnessScript witness Map.empty))
-        `shouldBe` [ (Key 0x04 "", hexBytes "00208c2353173743b595dfb4a07b72ba8e42e3797da74e87fe7d9d7497e3b2028903"),
-                     (Key 0x05 "", hexBytes "522103089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc21023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e7352ae")
-                   ]
-
-    it "read the redeem script and the witness script of an output, and write them under the types 0x00 and 0x01" $ do
-      let redeem = Script [OP_0, opPushData (hexBytes "8c2353173743b595dfb4a07b72ba8e42e3797da74e87fe7d9d7497e3b2028903")]
-          witness = Script [OP_1, OP_CHECKMULTISIG]
-          m = insertOutputRedeemScript redeem (insertOutputWitnessScript witness Map.empty)
-      Map.keys m `shouldBe` [Key 0x00 "", Key 0x01 ""]
-      outputRedeemScript m `shouldBe` Right (Just redeem)
-      outputWitnessScript m `shouldBe` Right (Just witness)
-      outputWitnessScript Map.empty `shouldBe` Right Nothing
-
-    it "read the final script and witness of a signed input" $ do
-      psbt <- psbtOfVector (finalizer vectors)
-      let first' = inputAt 0 psbt
-          second = inputAt 1 psbt
-      finalScriptSig first'
-        `shouldBe` Just (hexBytes "00473044022074018ad4180097b873323c0015720b3684cc8123891048e7dbcd9b55ad679c99022073d369b740e3eb53dcefa33823c8070514ca55a7dd9544f157c167913261118c01483045022100f61038b308dc1da865a34852746f015772934208c6d24454393cd99bdf2217770220056e675a675a6d0a02b85b14e5e29074d8a25a9b5760bea2816f661910a006ea01475221029583bf39ae0a609747ad199addd634fa6108559d6c5cd39b4c2183f1ab96e07f2102dab61ff49a14db6a7d02b0cd1fbb78fc4b18312b5b4e54dae4dba2fbfef536d752ae")
-      finalScriptWitness first' `shouldBe` Right Nothing
-      finalScriptSig second `shouldBe` Just (hexBytes "2200208c2353173743b595dfb4a07b72ba8e42e3797da74e87fe7d9d7497e3b2028903")
-      finalScriptWitness second
-        `shouldBe` Right
-          ( Just
-              [ "",
-                hexBytes "3044022062eb7a556107a7c73f45ac4ab5a1dddf6f7075fb1275969a7f383efff784bcb202200c05dbb7470dbf2f08557dd356c7325c1ed30913e996cd3840945db12228da5f01",
-                hexBytes "3044022065f45ba5998b59a27ffe1a7bed016af1f1f90d54b3aa8f7450aa5f56a25103bd02207f724703ad1edb96680b284b56d4ffcb88f7fb759eabbe08aa30f29b851383d201",
-                hexBytes "522103089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc21023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e7352ae"
-              ]
-          )
-
-    it "write a final script under the type 0x07, and a final witness as the number of its items then each after its length" $ do
-      Map.toList (insertFinalScriptSig (hexBytes "aabb") Map.empty) `shouldBe` [(Key 0x07 "", hexBytes "aabb")]
-      Map.toList (insertFinalScriptWitness [hexBytes "aabb", ""] Map.empty) `shouldBe` [(Key 0x08 "", hexBytes "0202aabb00")]
-
-    it "read the extended public keys of the global map, with their derivations, and write them under the type 0x01" $ do
-      psbt <- psbtOfVector (vectors.valid !! 7)
-      let xpub = fromJust $ xPubImport btc "xpub6CpGH79LXVkeiux2ZPWMpEubBrRfgcGCgy2HiagyN6NW3qdioJaqFYyD1fG6LDfxWEhMXJqcDuU5VneKt5UQYUGPa5Mfxdw2D2NArwX5TBm"
-          record = (xpub, Derivation (fingerprintOf "27569c50") "m/49'/0'/0'")
-      xpubRecords btc psbt.globals `shouldBe` Right [record]
-      let m = insertXpubRecord btc xpub (snd record) Map.empty
-      Map.keys m `shouldBe` [Key 0x01 (marshal btc xpub)]
-      xpubRecords btc m `shouldBe` Right [record]
-
-    -- The two keys of the vector are of the test network
-    it "leave aside the extended public keys of another network" $ do
-      psbt <- psbtOfVector (vectors.valid !! 5)
-      let tpub text = fromJust $ xPubImport btcTest text
-      xpubRecords btc psbt.globals `shouldBe` Right []
-      xpubRecords btcTest psbt.globals
-        `shouldBe` Right
-          [ (tpub "tpubDBkJeJo2X94Yq3RVz65DoUgyLUkaDrkfyrn2VcgyCRSKCRonvKvCF2FpYDGJWDkdRHBajXJGpc63GnumUt63ySvqCu2XaTRGVTKMYGuFk9H", Derivation (fingerprintOf "d90c6a4f") "m/174'/0'"),
-            (tpub "tpubDBkJeJo2X94YsvtBEU1eKoibEWiNv51nW5iHhs6VZp59jsE6nen8KZMFyGHuGbCvqjRqirgeMcfpVBkttpUUT6brm4duzSGoZeTbhqCNUu6", Derivation (fingerprintOf "d90c6a4f") "m/174'/1'")
-          ]
-
-    it "write a proprietary key as the type 0xfc, the identifier after its length, the subtype and the data" $ do
-      proprietaryKey (Proprietary "test" 1 (hexBytes "ab")) `shouldBe` Key 0xfc (hexBytes "047465737401ab")
-      proprietaryOf (Key 0xfc (hexBytes "047465737401ab")) `shouldBe` Right (Just (Proprietary "test" 1 (hexBytes "ab")))
-      proprietaryOf (Key 0x20 "") `shouldBe` Right Nothing
-      proprietaryOf (Key 0xfc "") `shouldBe` Left "the proprietary key 0xfc has no identifier and subtype"
-
-    it "look a proprietary field up by its identifier and subtype" $ do
-      let m = insertProprietary "test" 3 "Rent" Map.empty
-      lookupProprietary "test" 3 m `shouldBe` Just "Rent"
-      lookupProprietary "test" 2 m `shouldBe` Nothing
-      lookupProprietary "other" 3 m `shouldBe` Nothing
-
-{- Signing and finalizing -}
-
--- | A coin of 2 BTC at the script, spent whole by a transaction paying
--- two outputs, as a PSBT with the coin on its input: the whole previous
--- transaction, or the output alone for a Taproot coin, whose signature
--- commits to the output of every input (BIP 341)
-spendingPsbt :: ScriptOutput -> (Psbt, [(ScriptOutput, Word64, OutPoint)])
-spendingPsbt coinScript = (Psbt Version0 tx Map.empty [input] [Map.empty, Map.empty], [(coinScript, 200000000, outpoint)])
-  where
-    parent = Tx 1 [TxIn (OutPoint "e567952fb6cc33857f392efa3a46c995a28f69cca4bb1b37e0204dab1ec7a389" 1) "" 0xffffffff] [TxOut 200000000 (encodeSerial coinScript)] [] 0
-    outpoint = OutPoint (txHash parent) 0
-    tx =
-      Tx
-        2
-        [TxIn outpoint "" 0xfffffffe]
-        [ TxOut 99999699 (hexBytes "76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac"),
-          TxOut 100000000 (hexBytes "a9143545e6e33b832c47050f24d3eeb93c9c03948bc787")
-        ]
-        []
-        1257139
-    input = case coinScript of
-      PayWitness 1 _ -> insertWitnessUtxo (TxOut 200000000 (encodeSerial coinScript)) Map.empty
-      _ -> insertNonWitnessUtxo parent Map.empty
-
--- | A derivation record of a key, which a signer needs: the fingerprint
--- and the path are those of the BIP's first signer
-recordOf :: PublicKey -> PsbtMap -> PsbtMap
-recordOf public = insertInputDerivation public (Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/0'")
-
--- | A signer holding the keys
-keysSigner :: [PrivateKey] -> Signer
-keysSigner keys =
-  Signer
-    { keyOfRecord = \public derivation -> listToMaybe (mapMaybe (\key -> (keySigner key.key).keyOfRecord public derivation) keys),
-      keyOfHash = \h -> listToMaybe (mapMaybe (\key -> (keySigner key.key).keyOfHash h) keys),
-      acceptedSigHashes = defaultSigHashes,
-      requirePreviousTx = True
-    }
-
--- | Whether the transaction of the PSBT, once signed with the keys and
--- finalized, verifies against the coins it spends
-signsAndVerifies :: Network -> [PrivateKey] -> (Psbt, [(ScriptOutput, Word64, OutPoint)]) -> Either String Bool
-signsAndVerifies net keys (psbt, coins) = do
-  signed <- signPsbt net (keysSigner keys) psbt
-  final <- finalizePsbt net signed
-  tx <- psbtTransaction final
-  return (verifyStdTx net tx coins)
-
-signingSpec :: Spec
-signingSpec =
-  describe "Signing and finalizing" $ do
-    prop "a P2PKH coin, signed with the key of its address and finalized, verifies" $
-      forAll arbitraryKeyPair $ \(secret, public) ->
-        let (psbt, coins) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))
-            withRecord = withInputs (recordOf public <$> psbt.inputs) psbt
-         in signsAndVerifies btc [secret] (withRecord, coins) === Right True
-
-    -- The finalized input keeps its coin, its final script, and the
-    -- fields of version 2: the transaction it spends from, the output
-    -- index and the sequence
-    prop "a P2PKH coin of a PSBT of version 2, signed and finalized, verifies, and the PSBT stays of version 2 with the fields of its input" $
-      forAll arbitraryKeyPair $ \(secret, public) ->
-        let (psbt, coins) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))
-            version2 = withVersion Version2 (withInputs (recordOf public <$> psbt.inputs) psbt)
-            final = finalizePsbt btc =<< signPsbt btc (keysSigner [secret]) version2
-         in (signsAndVerifies btc [secret] (version2, coins), (.version) <$> final, Map.keys . inputAt 0 <$> final)
-              === (Right True, Right Version2, Right [Key 0x00 "", Key 0x07 "", Key 0x0e "", Key 0x0f "", Key 0x10 ""])
-
-    prop "a P2SH multisig coin, signed with enough of its keys and finalized, verifies" $
-      -- At most 7 keys: the redeem script of more uncompressed keys would be
-      -- over the 520 bytes a P2SH redeem script can have
-      forAll ((,) <$> arbitraryP2SHMSParam <*> arbitraryKeyPair) $ \((m, n), _) ->
-        forAll (vectorOf n arbitraryKeyPair) $ \pairs ->
-          let redeem = either error id $ encodeOutput (PayMulSig (snd <$> pairs) m)
-              (psbt, coins) = spendingPsbt (either error id (toP2SH redeem))
-              withFields = withInputs ((insertInputRedeemScript redeem . foldr (\(_, public) f -> recordOf public . f) id pairs) <$> psbt.inputs) psbt
-           in signsAndVerifies btc (fst <$> take m pairs) (withFields, coins) === Right True
-
-    -- The keys are compressed: a SegWit version 0 coin is not signed with
-    -- an uncompressed key, which 'signerScopeSpec' tests
-    prop "a P2WPKH coin, and a P2SH-P2WPKH one with its redeem script, signed and finalized, verify" $
-      forAll arbitraryKeyPairC $ \(secret, public) ->
-        let program = PayWitnessPKHash (addressHash (encodeSerial public))
-            (native, nativeCoins) = spendingPsbt program
-            redeem = either error id $ encodeOutput program
-            (nested, nestedCoins) = spendingPsbt (either error id (toP2SH redeem))
-            nativeWithRecord = withInputs (recordOf public <$> native.inputs) native
-            nestedWithFields = withInputs ((insertInputRedeemScript redeem . recordOf public) <$> nested.inputs) nested
-         in signsAndVerifies btc [secret] (nativeWithRecord, nativeCoins) === Right True
-              .&&. signsAndVerifies btc [secret] (nestedWithFields, nestedCoins) === Right True
-
-    prop "a P2WSH multisig coin with its witness script, nested in P2SH or not, signed and finalized, verifies" $
-      forAll arbitraryMSParam $ \(m, n) ->
-        forAll (vectorOf n arbitraryKeyPairC) $ \pairs ->
-          let witness = either error id $ encodeOutput (PayMulSig (snd <$> pairs) m)
-              program = either error id (toP2WSH witness)
-              records = foldr (\(_, public) f -> recordOf public . f) id pairs
-              (native, nativeCoins) = spendingPsbt program
-              (nested, nestedCoins) = spendingPsbt (either error id (toP2SH programScript))
-              nativeWithFields = withInputs ((insertInputWitnessScript witness . records) <$> native.inputs) native
-              nestedWithFields = withInputs ((insertInputRedeemScript programScript . insertInputWitnessScript witness . records) <$> nested.inputs) nested
-              programScript = either error id $ encodeOutput program
-           in signsAndVerifies btc (fst <$> take m pairs) (nativeWithFields, nativeCoins) === Right True
-                .&&. signsAndVerifies btc (fst <$> take m pairs) (nestedWithFields, nestedCoins) === Right True
-
-    it "signs with the sighash the input asks for when the signer accepts it, SIGHASH_ALL when it asks for none" $ do
-      let secret = PrivateKey secretOne True
-          public = derivePublicKey secret
-          (psbt, _) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))
-          asking sh = withInputs ((recordOf public . maybe id insertSigHashType sh) <$> psbt.inputs) psbt
-          sighashOf signed = map (B.last . snd) <$> partialSignatures (inputAt 0 signed)
-          acceptingNone = (keySigner secret.key) {acceptedSigHashes = sigHashNone : defaultSigHashes}
-      (sighashOf =<< signPsbt btc (keySigner secret.key) (asking Nothing)) `shouldBe` Right [0x01]
-      (sighashOf =<< signPsbt btc (keySigner secret.key) (asking (Just sigHashAll))) `shouldBe` Right [0x01]
-      -- SIGHASH_NONE leaves the outputs unsigned, so the signer must agree to it
-      signPsbt btc (keySigner secret.key) (asking (Just sigHashNone)) `shouldBe` Left "Input 0: the sighash type 2 is not one the signer accepts"
-      (sighashOf =<< signPsbt btc acceptingNone (asking (Just sigHashNone))) `shouldBe` Right [0x02]
-
-    it "leaves an input without its coin, or signed already, as it is" $ do
-      let secret = PrivateKey secretOne True
-          public = derivePublicKey secret
-          (psbt, _) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))
-          withoutCoin = withInputs [recordOf public Map.empty] psbt
-          final = withInputs ((insertFinalScriptSig "a script" . recordOf public) <$> psbt.inputs) psbt
-      signPsbt btc (keySigner secret.key) withoutCoin `shouldBe` Right withoutCoin
-      signPsbt btc (keySigner secret.key) final `shouldBe` Right final
-
-    it "refuses a previous transaction that is not the one the input spends" $ do
-      let public = compressedKey secretOne
-          (psbt, _) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))
-          wrong = withInputs [insertNonWitnessUtxo emptyTx Map.empty] psbt
-      signPsbt btc (Signer (\_ _ -> Nothing) (const Nothing) defaultSigHashes True) wrong `shouldBe` Left "Input 0: the previous transaction is not the one the input spends"
-
-    -- The derivation records name keys by the master key, b4a6ba67 with
-    -- the full path, or by the extended key given, with the path from it
-    it "finds the key an extended private key derives, by its own fingerprint or by the origin given" $ do
-      let root = makeXPrvKey "PSBT signer test"
-          rootFingerprint = xPubFP (deriveXPubKey root)
-          account = derivePath (Deriv :| 444 :: HardPath) root
-          accountFingerprint = xPubFP (deriveXPubKey account)
-          secretAt path = (derivePath (path :: DerivPath) root).key
-          publicOf secret = PublicKey (derivePubKey secret) True
-          signer = xPrvSigner account (Just (Derivation rootFingerprint "m/444'"))
-          unknownOrigin = xPrvSigner account Nothing
-      signer.keyOfRecord (publicOf (secretAt "m/444'/0")) (Derivation rootFingerprint "m/444'/0") `shouldBe` Just (secretAt "m/444'/0")
-      signer.keyOfRecord (publicOf (secretAt "m/444'/1")) (Derivation accountFingerprint "m/1") `shouldBe` Just (secretAt "m/444'/1")
-      signer.keyOfRecord (publicOf (secretAt "m/444'/1")) (Derivation rootFingerprint "m/445'/1") `shouldBe` Nothing
-      signer.keyOfRecord (publicOf (secretAt "m/444'/1")) (Derivation accountFingerprint "m/2") `shouldBe` Nothing
-      unknownOrigin.keyOfRecord (publicOf (secretAt "m/444'/0")) (Derivation rootFingerprint "m/444'/0") `shouldBe` Nothing
-      unknownOrigin.keyOfRecord (publicOf (secretAt "m/444'/0")) (Derivation accountFingerprint "m/0") `shouldBe` Just (secretAt "m/444'/0")
-      -- An extended key cannot know which path a hash is at
-      signer.keyOfHash (addressHash (encodeSerial (publicOf (secretAt "m/444'/0")))) `shouldBe` Nothing
-
-{- A PSBT of every kind of coin -}
-
--- | The PSBTs of a file that scripts/create_complex_psbt_data.sh wrote: a
--- transaction of nine coins of every kind, signed by twelve wallets of
--- Bitcoin Core one at a time, their combination, its finalization and the
--- transaction it gives
-data Complex = Complex
-  { initialPsbt :: Psbt,
-    signedPsbts :: [Psbt],
-    combinedPsbt :: Psbt,
-    completePsbt :: Psbt,
-    finalTx :: Tx
-  }
-
-instance Json.FromJSON Complex where
-  parseJSON = Json.withObject "complex" $ \o ->
-    Complex
-      <$> psbtAt o "initial_psbt"
-      <*> mapM (psbtAt o) ["miner_psbt", "p2pkh_psbt", "p2sh_ms_1_psbt", "p2sh_ms_2_psbt", "p2sh_pk_psbt", "p2sh_wsh_pk_psbt", "p2sh_wsh_ms_1_psbt", "p2sh_wsh_ms_2_psbt", "p2wpkh_psbt", "p2wsh_pk_psbt", "p2wsh_ms_1_psbt", "p2wsh_ms_2_psbt"]
-      <*> psbtAt o "combined_psbt"
-      <*> psbtAt o "complete_psbt"
-      <*> (either fail return . S.decode . hexBytes =<< o .: "final_tx")
-    where
-      psbtAt o name = either fail return . decodePsbtBase64 . encodeUtf8 =<< o .: name
-
-complexSpec :: Spec
-complexSpec = do
-  -- data/complex_psbt.json is the file of an older Bitcoin Core, in
-  -- version 0. Each wallet finalized the coins it could complete alone.
-  describe "The PSBT of nine coins of every kind, which twelve wallets of Bitcoin Core signed one at a time" $ do
-    complex <- runIO (readTestFile "complex_psbt.json" :: IO Complex)
-    complexChecks complex
-
-  -- data/psbt_complex_core32.json is the file of Bitcoin Core 32.1, in
-  -- version 2. The wallets signed with finalize=false, so that the
-  -- combination holds partial signatures only.
-  describe "The PSBT of nine coins of every kind, which twelve wallets of Bitcoin Core 32.1 signed without finalizing" $ do
-    complex <- runIO (readTestFile "psbt_complex_core32.json" :: IO Complex)
-    it "is a version 2 PSBT whose combination has no final input" $ do
-      complex.combinedPsbt.version `shouldBe` Version2
-      length complex.combinedPsbt.inputs `shouldBe` 9
-      -- Types 0x07 and 0x08 are the final script and the final witness
-      length [key | input <- complex.combinedPsbt.inputs, key <- Map.keys input, key.keyType `elem` [0x07, 0x08]] `shouldBe` 0
-    complexChecks complex
-
--- | What holds for both files: the library combines, finalizes and
--- extracts what Bitcoin Core combined, finalized and extracted
-complexChecks :: Complex -> Spec
-complexChecks complex = do
-  -- The PSBT Core created has no entry that a signed one lacks
-  it "adds nothing to a signed PSBT when the PSBT Core created is combined with it" $
-    mapM (combinePsbt complex.initialPsbt) complex.signedPsbts `shouldBe` Right complex.signedPsbts
-
-  it "combines into the PSBT Core combined" $
-    case complex.signedPsbts of
-      first' : rest -> foldM combinePsbt first' rest `shouldBe` Right complex.combinedPsbt
-      [] -> expectationFailure "No signed PSBT"
-
-  it "finalizes into the PSBT Core finalized" $
-    finalizePsbt btc complex.combinedPsbt `shouldBe` Right complex.completePsbt
-
-  it "gives the transaction Core extracted" $
-    psbtTransaction complex.completePsbt `shouldBe` Right complex.finalTx
-
-{- The files of Bitcoin Core 32.1 -}
-
--- The files live in data/psbt_core32.json: the PSBT of a payment as
--- walletcreatefundedpsbt gives it in version 0 and in version 2, the
--- version 2 one signed by walletprocesspsbt without finalizing, then
--- finalized, and the transaction finalizepsbt extracts
-data Core32 = Core32
-  { preparedV0 :: Psbt,
-    preparedV2 :: Psbt,
-    signedV2 :: Psbt,
-    finalizedV2 :: Psbt,
-    extractedTx :: Tx
-  }
-
-instance Json.FromJSON Core32 where
-  parseJSON = Json.withObject "core32" $ \o ->
-    Core32
-      <$> psbtAt o "prepared_v0"
-      <*> psbtAt o "prepared_v2"
-      <*> psbtAt o "signed_v2"
-      <*> psbtAt o "finalized_v2"
-      <*> (either fail return . S.decode . hexBytes =<< o .: "final_tx")
-    where
-      psbtAt o name = either fail return . decodePsbtBase64 . encodeUtf8 =<< o .: name
-
-core32Spec :: Spec
-core32Spec =
-  describe "The files of Bitcoin Core 32.1, which writes version 2 unless asked for version 0" $ do
-    core <- runIO (readTestFile "psbt_core32.json" :: IO Core32)
-    it "are the same payment in both versions: the version 2 file is the version 0 file converted, and back" $ do
-      core.preparedV2.version `shouldBe` Version2
-      core.preparedV2.unsignedTx `shouldBe` core.preparedV0.unsignedTx
-      withVersion Version2 core.preparedV0 `shouldBe` core.preparedV2
-      withVersion Version0 core.preparedV2 `shouldBe` core.preparedV0
-
-    it "finalize into the PSBT Core finalized" $
-      finalizePsbt btc core.signedV2 `shouldBe` Right core.finalizedV2
-
-    it "give the transaction Core extracted" $
-      psbtTransaction core.finalizedV2 `shouldBe` Right core.extractedTx
-
-    -- The records name the key of the coin by the fingerprint bc560f95 of
-    -- a seed and the path m/44'/0'/0'/0/0: the account key at m/44'/0'/0'
-    -- of that seed signs. The coin is 50 BTC at the P2PKH script of that
-    -- key.
-    it "are signed with the account key the records name, into a transaction that verifies" $ do
-      let account = fromJust (xPrvImport btc "xprv9yHxeaLAZvxXb9VtJNesqk8avfN8misGAW9DUW9eacZJNqsfZxqKLmK5jfmvFideQqGesviJeagzSQYCuQySjgvt7TdfowKja5aJqbgyuNh")
-          signer = xPrvSigner account (Just (Derivation (fingerprintOf "bc560f95") "m/44'/0'/0'"))
-      coin <- expectRight (decodeSerial (hexBytes "76a914c80d55223e2f1061363add2a7b0363c285bf298d88ac"))
-      final <- expectRight (finalizePsbt btc =<< signPsbt btc signer core.preparedV2)
-      tx <- expectRight (psbtTransaction final)
-      final.version `shouldBe` Version2
-      verifyStdTx btc tx [(coin, 5000000000, OutPoint "fede72ccadbf9f16f826e3078578b0660526a37b48d4f894ab26f4cf5a95e89c" 0)] `shouldBe` True
-
-{- The checks of the signer and the finalizer -}
-
-signerChecksSpec :: Spec
-signerChecksSpec =
-  describe "The checks of the signer and the finalizer" $ do
-    let secret = PrivateKey secretOne True
-        public = derivePublicKey secret
-        otherPublic = compressedKey secretTwo
-        (psbt, coins) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))
-        parent = fromJust (either (const Nothing) id (nonWitnessUtxo (inputAt 0 psbt)))
-        coin = head parent.outputs
-        withInput m = withInputs [m] psbt
-        signer = keySigner secret.key
-        signed m = signPsbt btc signer (withInput (recordOf public m))
-        signatureCount s = fmap length (partialSignatures (inputAt 0 s))
-
-    it "refuses to sign a legacy coin known from its witness output only, which only a witness signature may use" $
-      signed (insertWitnessUtxo coin Map.empty)
-        `shouldBe` Left "Input 0: the coin is given as a witness output only, which may not be signed with a non-witness signature"
-
-    it "takes the coin from the previous transaction first, and refuses a witness output that is not that output" $ do
-      (signatureCount =<< signed (insertWitnessUtxo coin (insertNonWitnessUtxo parent Map.empty))) `shouldBe` Right 1
-      signed (insertWitnessUtxo (TxOut 1 coin.script) (insertNonWitnessUtxo parent Map.empty))
-        `shouldBe` Left "Input 0: the witness output of the input is not the output of its previous transaction"
-
-    it "refuses a sighash type no node accepts, and one whose fork id flag does not fit the network" $ do
-      signed (insertSigHashType 0 (insertNonWitnessUtxo parent Map.empty)) `shouldBe` Left "Input 0: the sighash type 0 is not one a node accepts"
-      signed (insertSigHashType 0x21 (insertNonWitnessUtxo parent Map.empty)) `shouldBe` Left "Input 0: the sighash type 33 is not one a node accepts"
-      signed (insertSigHashType (setForkIdFlag sigHashAll) (insertNonWitnessUtxo parent Map.empty)) `shouldBe` Left "Input 0: the sighash type has a fork id flag the network does not use"
-      signPsbt bch signer (withInput (recordOf public (insertSigHashType sigHashAll (insertNonWitnessUtxo parent Map.empty))))
-        `shouldBe` Left "Input 0: the sighash type lacks the fork id flag the network requires"
-      -- With the flag, the Bitcoin Cash digest signs
-      (signatureCount =<< signPsbt bch signer (withInput (recordOf public (insertSigHashType (setForkIdFlag sigHashAll) (insertNonWitnessUtxo parent Map.empty))))) `shouldBe` Right 1
-
-    it "refuses a sighash type the signer does not accept, and signs with it once the signer lists it" $ do
-      let acceptingSingle = signer {acceptedSigHashes = [sigHashSingle]}
-          askingSingle = insertSigHashType sigHashSingle (insertNonWitnessUtxo parent Map.empty)
-      signed askingSingle `shouldBe` Left "Input 0: the sighash type 3 is not one the signer accepts"
-      (signatureCount =<< signPsbt btc acceptingSingle (withInput (recordOf public askingSingle))) `shouldBe` Right 1
-      -- ANYONECANPAY makes another type: 0x81 is not 0x01
-      signed (insertSigHashType (setAnyoneCanPay sigHashAll) (insertNonWitnessUtxo parent Map.empty)) `shouldBe` Left "Input 0: the sighash type 129 is not one the signer accepts"
-
-    -- Two coins of the same script, spent by one transaction with one
-    -- output: input 1 has no output at its index
-    it "refuses SIGHASH_SINGLE on a legacy coin whose input has no output at its index, and signs it on a SegWit coin" $ do
-      let witnessCoin = TxOut 200000000 (encodeSerial (PayWitnessPKHash (addressHash (encodeSerial public))))
-          parentOf c = Tx 1 [TxIn (OutPoint "e567952fb6cc33857f392efa3a46c995a28f69cca4bb1b37e0204dab1ec7a389" 1) "" 0xffffffff] [c, c] [] 0
-          spendingBoth p = Tx 2 [TxIn (OutPoint (txHash p) 0) "" 0xfffffffe, TxIn (OutPoint (txHash p) 1) "" 0xfffffffe] [TxOut 399999000 (hexBytes "76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac")] [] 0
-          askingSingle p = recordOf public (insertSigHashType sigHashSingle (insertNonWitnessUtxo p Map.empty))
-          psbtOf p = Psbt Version0 (spendingBoth p) Map.empty [askingSingle p, askingSingle p] [Map.empty]
-          acceptingSingle = signer {acceptedSigHashes = [sigHashSingle]}
-      signPsbt btc acceptingSingle (psbtOf (parentOf coin)) `shouldBe` Left "Input 1: makeSignature: SIGHASH_SINGLE without an output at the input index"
-      -- The BIP 143 digest commits to the coin, so the SegWit signature is fine
-      (signatureCount =<< signPsbt btc acceptingSingle (psbtOf (parentOf witnessCoin))) `shouldBe` Right 1
-      (fmap length . partialSignatures . inputAt 1 =<< signPsbt btc acceptingSingle (psbtOf (parentOf witnessCoin))) `shouldBe` Right 1
-
-    it "refuses a redeem script that does not hash to the coin, and one on a coin that is not pay-to-script-hash" $ do
-      let ms = PayMulSig [public, otherPublic] 1
-          msScript = either error id (encodeOutput ms)
-          wrongScript = either error id (encodeOutput (PayMulSig [otherPublic, public] 1))
-          (p2sh, _) = spendingPsbt (either error id (toP2SH msScript))
-          p2shParent = fromJust (either (const Nothing) id (nonWitnessUtxo (inputAt 0 p2sh)))
-          p2shInput m = withInputs [recordOf public (insertNonWitnessUtxo p2shParent m)] p2sh
-      (signatureCount =<< signPsbt btc signer (p2shInput (insertInputRedeemScript msScript Map.empty))) `shouldBe` Right 1
-      signPsbt btc signer (p2shInput (insertInputRedeemScript wrongScript Map.empty))
-        `shouldBe` Left "Input 0: the redeem script of the input does not hash to its coin"
-      signed (insertInputRedeemScript msScript (insertNonWitnessUtxo parent Map.empty))
-        `shouldBe` Left "Input 0: the input has a redeem script, but its coin is not pay-to-script-hash"
-
-    it "refuses a witness script that does not hash to the witness program" $ do
-      let ms = PayMulSig [public, otherPublic] 1
-          msScript = either error id (encodeOutput ms)
-          wrongScript = either error id (encodeOutput (PayMulSig [otherPublic, public] 1))
-          (p2wsh, _) = spendingPsbt (either error id (toP2WSH msScript))
-          p2wshInput m = withInputs [recordOf public (Map.union m (inputAt 0 p2wsh))] p2wsh
-      (signatureCount =<< signPsbt btc signer (p2wshInput (insertInputWitnessScript msScript Map.empty))) `shouldBe` Right 1
-      signPsbt btc signer (p2wshInput (insertInputWitnessScript wrongScript Map.empty))
-        `shouldBe` Left "Input 0: the witness script of the input does not hash to its witness program"
-      signed (insertInputWitnessScript msScript (insertNonWitnessUtxo parent Map.empty))
-        `shouldBe` Left "Input 0: the input has a witness script, but its coin is not pay-to-witness-script-hash"
-
-    it "leaves an input whose coin script is not standard as it is, and signs the others" $ do
-      let weird = TxOut 1000 (runPutS (serialize (Script [OP_1])))
-          parent2 = Tx 1 parent.inputs [coin, weird] [] 0
-          op0 = OutPoint (txHash parent2) 0
-          op1 = OutPoint (txHash parent2) 1
-          tx = Tx 2 [TxIn op0 "" 0xfffffffe, TxIn op1 "" 0xfffffffe] psbt.unsignedTx.outputs [] 0
-          both = Psbt Version0 tx Map.empty [recordOf public (insertNonWitnessUtxo parent2 Map.empty), insertNonWitnessUtxo parent2 Map.empty] [Map.empty, Map.empty]
-      s <- expectRight (signPsbt btc signer both)
-      map hasPartialSignatures s.inputs `shouldBe` [True, False]
-      f <- expectRight (finalizePsbt btc s)
-      map (isJust . finalScriptSig) f.inputs `shouldBe` [True, False]
-
-    it "signs a coin whose key it holds without a derivation record, by the hash of the key" $ do
-      (signatureCount =<< signPsbt btc signer (withInput (insertNonWitnessUtxo parent Map.empty))) `shouldBe` Right 1
-      -- A multisig coin names its keys
-      let ms = PayMulSig [public, otherPublic] 1
-          msScript = either error id (encodeOutput ms)
-          (p2sh, p2shCoins) = spendingPsbt (either error id (toP2SH msScript))
-          p2shParent = fromJust (either (const Nothing) id (nonWitnessUtxo (inputAt 0 p2sh)))
-          p2shFields = withInputs [insertInputRedeemScript msScript (insertNonWitnessUtxo p2shParent Map.empty)] p2sh
-      s <- expectRight (signPsbt btc signer p2shFields)
-      signatureCount s `shouldBe` Right 1
-      signsAndVerifies btc [secret] (p2shFields, p2shCoins) `shouldBe` Right True
-      -- The other key is not held
-      (signatureCount =<< signPsbt btc (keySigner secret.key) (fst (spendingPsbt (PayPKHash (addressHash (encodeSerial otherPublic)))))) `shouldBe` Right 0
-      coins `seq` return ()
-
-    it "the finalizer refuses a signature that is not a signature, one with another sighash type than the input asks, and one that does not verify" $ do
-      s <- expectRight (signed (insertNonWitnessUtxo parent Map.empty))
-      signature <- case either error id (partialSignatures (inputAt 0 s)) of
-        [(_, sig)] -> return sig
-        _ -> fail "one signature"
-      let withSig sig m = withInput (insertPartialSignature public sig m)
-          keyHex = show (encodeHex (encodeSerial public))
-      finalizePsbt btc (withSig "3045aa" (insertNonWitnessUtxo parent Map.empty))
-        `shouldBe` Left ("Input 0: the signature of the key " <> keyHex <> " is not a valid signature")
-      finalizePsbt btc (withSig signature (insertSigHashType sigHashNone (insertNonWitnessUtxo parent Map.empty)))
-        `shouldBe` Left ("Input 0: the signature of the key " <> keyHex <> " does not use the sighash type of the input")
-      -- The signature of the same key on another transaction
-      let sameKeyOther = withInputs [recordOf public (insertNonWitnessUtxo parent Map.empty)] (Psbt Version0 (Tx 2 psbt.unsignedTx.inputs [] [] 0) Map.empty psbt.inputs [])
-      elsewhere <- expectRight (signPsbt btc signer sameKeyOther)
-      foreignSig <- case either error id (partialSignatures (inputAt 0 elsewhere)) of
-        [(_, sig)] -> return sig
-        _ -> fail "one signature"
-      finalizePsbt btc (withSig foreignSig (insertNonWitnessUtxo parent Map.empty))
-        `shouldBe` Left ("Input 0: the signature of the key " <> keyHex <> " does not verify")
-      -- The right signature finalizes
-      f <- expectRight (finalizePsbt btc (withSig signature (insertNonWitnessUtxo parent Map.empty)))
-      isJust (finalScriptSig (inputAt 0 f)) `shouldBe` True
-
-{- Taproot -}
-
-data Vectors371 = Vectors371
-  { refused371 :: [Vector],
-    accepted371 :: [Vector]
-  }
-
-instance Json.FromJSON Vectors371 where
-  parseJSON = Json.withObject "vectors" $ \o -> Vectors371 <$> o .: "invalid" <*> o .: "valid"
-
--- | Why each invalid PSBT of BIP 371 is refused, as the end of the reason
-refusals371 :: [String]
-refusals371 =
-  [ "Input 0: the value of the key 0x17 is not an x-only public key",
-    "Input 0: the value of the key 0x13 is not a Taproot signature: decodeTaprootSig: a signature is 64 or 65 bytes, not 63",
-    "Input 0: the value of the key 0x13 is not a Taproot signature: decodeTaprootSig: a signature is 64 or 65 bytes, not 66",
-    "is not an x-only public key",
-    "Output 1: the value of the key 0x05 is not an x-only public key",
-    "is not an x-only public key",
-    "is not an x-only public key and a leaf hash",
-    "is not a Taproot signature: decodeTaprootSig: a signature is 64 or 65 bytes, not 66",
-    "is not a Taproot signature: decodeTaprootSig: a signature is 64 or 65 bytes, not 63",
-    "is not a control block",
-    "is not a control block"
-  ]
-
-taprootSpec :: Vectors371 -> Spec
-taprootSpec vectors =
-  describe "The Taproot fields of BIP 371" $ do
-    describe "the invalid PSBTs are refused, each for its reason" $
-      forM_ (zip vectors.refused371 refusals371) $ \(v, reason) ->
-        it v.vecCase $ decodePsbt (bytesOf v) `shouldSatisfy` either (reason `isSuffixOf`) (const False)
-
-    describe "the valid PSBTs are read, and written back byte for byte" $
-      forM_ vectors.accepted371 $ \v ->
-        it v.vecCase $ (encodePsbt <$> decodePsbt (bytesOf v)) `shouldBe` Right (bytesOf v)
-
-    let vectorAt i = psbtOfVector (vectors.accepted371 !! i)
-        xOnly text = fromJust (importXOnlyPubKey (hexBytes text))
-        digest text = fromJust (digestFromByteString (hexBytes text)) :: Digest SHA256
-        keyScript text = Script [opPushData (hexBytes text), OP_CHECKSIG]
-
-    it "read the internal key and the derivation of a key path input" $ do
-      psbt <- vectorAt 0
-      inputTapInternalKey (inputAt 0 psbt) `shouldBe` Right (Just (xOnly "fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa232"))
-      inputTapDerivations (inputAt 0 psbt) `shouldBe` Right [(xOnly "fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa232", TapDerivation [] (Derivation (fingerprintOf "772b2da7") "m/86'/1'/0'/1/0"))]
-      inputTapMerkleRoot (inputAt 0 psbt) `shouldBe` Right Nothing
-      tapKeySig (inputAt 0 psbt) `shouldBe` Right Nothing
-
-    it "read the key path signature of a signed input, and finalize it into a witness of that signature" $ do
-      psbt <- vectorAt 1
-      let sigHex = "bb53ec917bad9d906af1ba87181c48b86ace5aae2b53605a725ca74625631476fc6f5baedaf4f2ee0f477f36f58f3970d5b8273b7e497b97af2e3f125c97af34"
-          sig = fromJust (schnorrSig (hexBytes sigHex))
-      tapKeySig (inputAt 0 psbt) `shouldBe` (Just <$> taprootSignature sig sigHashDefault)
-      final <- expectRight (finalizePsbt btc psbt)
-      finalScriptWitness (inputAt 0 final) `shouldBe` Right (Just [hexBytes sigHex])
-      Map.keys (inputAt 0 final) `shouldBe` [Key 0x01 "", Key 0x08 ""]
-      tx <- expectRight (psbtTransaction final)
-      let coin = TxOut 5000000000 (hexBytes "51205a2c2cf5b52cf31f83ad2e8da63ff03183ecd8f609c7510ae8a48e03910a0757")
-      verifyStdTx btc tx [(either error id (decodeSerial coin.script), coin.value, (head tx.inputs).outpoint)] `shouldBe` True
-
-    it "read the internal key and the derivation of a key path output" $ do
-      psbt <- vectorAt 2
-      outputTapInternalKey (outputAt 0 psbt) `shouldBe` Right (Just (xOnly "1124da7aec92ccd06c954562647f437b138b95721a84be2bf2276bbddab3e671"))
-      outputTapDerivations (outputAt 0 psbt) `shouldBe` Right [(xOnly "1124da7aec92ccd06c954562647f437b138b95721a84be2bf2276bbddab3e671", TapDerivation [] (Derivation (fingerprintOf "772b2da7") "m/86'/1'/0'/0/5"))]
-      outputTapTree (outputAt 0 psbt) `shouldBe` Right Nothing
-
-    it "read the leaf scripts, the derivations with their leaves, the internal key and the Merkle root of a script path input" $ do
-      psbt <- vectorAt 3
-      leaves <- expectRight (tapLeafScripts (inputAt 0 psbt))
-      map (.script) leaves
-        `shouldBe` [ keyScript "2cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2",
-                     keyScript "4320b0bf16f011b53ea7be615924aa7f27e5d29ad20ea1155d848676c3bad1b2",
-                     keyScript "fa0f7a3cef3b1d0c0a6ce7d26e17ada0b2e5c92d19efad48b41859cb8a451ca9"
-                   ]
-      map (.leafVersion) leaves `shouldBe` [0xc0, 0xc0, 0xc0]
-      map (B.length . (.controlBlock)) leaves `shouldBe` [97, 65, 97]
-      inputTapInternalKey (inputAt 0 psbt) `shouldBe` Right (Just (xOnly "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0"))
-      inputTapMerkleRoot (inputAt 0 psbt) `shouldBe` Right (Just (digest "f0362e2f75a6f420a5bde3eb221d96ae6720cf25f81890c95b1d775acb515e65"))
-      records <- expectRight (inputTapDerivations (inputAt 0 psbt))
-      lookup (xOnly "2cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2") records
-        `shouldBe` Just (TapDerivation [digest "cd970e15f53fc0c82f950fd560ffa919b76172be017368a89913af074f400b09"] (Derivation (fingerprintOf "772b2da7") "m/86'/1'/2'/0/0"))
-      lookup (xOnly "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0") records
-        `shouldBe` Just (TapDerivation [] (Derivation (fingerprintOf "7c461e5d") "m"))
-      -- The leaf hash of the record is the hash of the leaf script
-      leafHash 0xc0 (keyScript "2cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2") `shouldBe` digest "cd970e15f53fc0c82f950fd560ffa919b76172be017368a89913af074f400b09"
-      -- The control blocks commit the leaves to the output key, with the Merkle root
-      let outKey = fromJust (importXOnlyPubKey (hexBytes "c2247efbfd92ac47f6f40b8d42d169175a19fa9fa10e4a25d7f35eb4dd85b692"))
-      forM_ leaves $ \leaf -> do
-        (v, internal, proof) <- expectRight (decodeControlBlock leaf.controlBlock)
-        verifyScriptPathData outKey (ScriptPathData Nothing [] leaf.script (odd v) 0xc0 internal proof Nothing) `shouldBe` True
-
-    it "read the script tree of a script path output, whose leaves build the tree of its output key" $ do
-      psbt <- vectorAt 4
-      let leaves =
-            [ TapLeaf 2 0xc0 (keyScript "736e572900fe1252589a2143c8f3c79f71a0412d2353af755e9701c782694a02"),
-              TapLeaf 2 0xc0 (keyScript "631c5f3b5832b8fbdebfb19704ceeb323c21f40f7a24f43d68ef0cc26b125969"),
-              TapLeaf 1 0xc0 (keyScript "44faa49a0338de488c8dfffecdfb6f329f380bd566ef20c8df6d813eab1c4273")
-            ]
-      outputTapTree (outputAt 0 psbt) `shouldBe` Right (Just leaves)
-      outputTapInternalKey (outputAt 0 psbt) `shouldBe` Right (Just (xOnly "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0"))
-      let tree = fromJust (tapTreeFromLeaves leaves)
-          output = TaprootOutput (xOnly "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0") (Just tree)
-      encodeSerial (taprootScriptOutput output) `shouldBe` (head psbt.unsignedTx.outputs).script
-      Map.lookup (Key 0x06 "") (insertOutputTapTree leaves Map.empty) `shouldBe` Map.lookup (Key 0x06 "") (outputAt 0 psbt)
-      records <- expectRight (outputTapDerivations (outputAt 0 psbt))
-      length records `shouldBe` 4
-
-    it "read the script path signatures of a signed input, and finalize it with the first leaf that has one" $ do
-      psbt <- vectorAt 5
-      sigs <- expectRight (tapScriptSigs (inputAt 0 psbt))
-      map (\((k, h), s) -> (exportXOnlyPubKey k, h, B.length (encodeTaprootSig s))) sigs
-        `shouldBe` [ (hexBytes "2cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2", digest "cd970e15f53fc0c82f950fd560ffa919b76172be017368a89913af074f400b09", 64),
-                     (hexBytes "4320b0bf16f011b53ea7be615924aa7f27e5d29ad20ea1155d848676c3bad1b2", digest "115f2e490af7cc45c4f78511f36057ce5c5a5c56325a29fb44dfc203f356e1f8", 64),
-                     (hexBytes "fa0f7a3cef3b1d0c0a6ce7d26e17ada0b2e5c92d19efad48b41859cb8a451ca9", digest "6f7d62059e9497a1a4a267569d9876da60101aff38e3529b9b939ce7f91ae970", 64)
-                   ]
-      final <- expectRight (finalizePsbt btc psbt)
-      witness <- expectRight (finalScriptWitness (inputAt 0 final))
-      fmap (map B.length) witness `shouldBe` Just [64, 34, 97]
-      tx <- expectRight (psbtTransaction final)
-      let coin = TxOut 5000000000 (hexBytes "5120c2247efbfd92ac47f6f40b8d42d169175a19fa9fa10e4a25d7f35eb4dd85b692")
-      verifyStdTx btc tx [(either error id (decodeSerial coin.script), coin.value, (head tx.inputs).outpoint)] `shouldBe` True
-
-    it "write the fields back as they were read" $
-      forM_ [0 .. 5] $ \i -> do
-        psbt <- vectorAt i
-        forM_ psbt.inputs $ \m -> do
-          key <- expectRight (inputTapInternalKey m)
-          forM_ key $ \k -> Map.lookup (Key 0x17 "") (insertInputTapInternalKey k Map.empty) `shouldBe` Map.lookup (Key 0x17 "") m
-          root <- expectRight (inputTapMerkleRoot m)
-          forM_ root $ \r -> Map.lookup (Key 0x18 "") (insertInputTapMerkleRoot r Map.empty) `shouldBe` Map.lookup (Key 0x18 "") m
-          sig <- expectRight (tapKeySig m)
-          forM_ sig $ \s -> Map.lookup (Key 0x13 "") (insertTapKeySig s Map.empty) `shouldBe` Map.lookup (Key 0x13 "") m
-          leaves <- expectRight (tapLeafScripts m)
-          Map.toList (foldr insertTapLeafScript Map.empty leaves) `shouldBe` [(k, v) | (k, v) <- Map.toList m, k.keyType == 0x15]
-          records <- expectRight (inputTapDerivations m)
-          Map.toList (foldr (uncurry insertInputTapDerivation) Map.empty records) `shouldBe` [(k, v) | (k, v) <- Map.toList m, k.keyType == 0x16]
-          sigs <- expectRight (tapScriptSigs m)
-          Map.toList (foldr (\((k, h), s) -> insertTapScriptSig k h s) Map.empty sigs) `shouldBe` [(k, v) | (k, v) <- Map.toList m, k.keyType == 0x14]
-        forM_ psbt.outputs $ \m -> do
-          key <- expectRight (outputTapInternalKey m)
-          forM_ key $ \k -> Map.lookup (Key 0x05 "") (insertOutputTapInternalKey k Map.empty) `shouldBe` Map.lookup (Key 0x05 "") m
-          records <- expectRight (outputTapDerivations m)
-          Map.toList (foldr (uncurry insertOutputTapDerivation) Map.empty records) `shouldBe` [(k, v) | (k, v) <- Map.toList m, k.keyType == 0x07]
-
-    prop "a Taproot coin without script tree, signed by its key path with the internal key and finalized, verifies" $
-      forAll arbitraryKeyPair $ \(secret, public) ->
-        let coinScript = taprootScriptOutput (TaprootOutput public.point Nothing)
-            (psbt, coins) = spendingPsbt coinScript
-            fields = insertInputTapInternalKey public.point . insertInputTapDerivation public.point (TapDerivation [] (Derivation (fingerprintOf "d90c6a4f") "m/86'/0'/0'/0/0"))
-            withFields = withInputs (fields <$> psbt.inputs) psbt
-            signed = signPsbt btc (keySigner secret.key) withFields
-         in (signsAndVerifies btc [secret] (withFields, coins), fmap (fmap (fmap (.hash)) . tapKeySig . inputAt 0) signed) === (Right True, Right (Right (Just sigHashDefault)))
-
-    prop "a Taproot coin with a leaf that checks one key, signed by that leaf and finalized, verifies" $
-      forAll ((,) <$> arbitraryKeyPair <*> arbitraryKeyPair) $ \((secret, public), (_, internal)) ->
-        let leaf = Script [opPushData (exportXOnlyPubKey public.point), OP_CHECKSIG]
-            tree = MASTBranch (MASTLeaf 0xc0 leaf) (MASTLeaf 0xc0 (Script [OP_RETURN]))
-            output = TaprootOutput internal.point (Just tree)
-            coinScript = taprootScriptOutput output
-            (psbt, coins) = spendingPsbt coinScript
-            proof = case getMerkleProofs tree of
-              (_, _, p) : _ -> p
-              [] -> []
-            control = encodeControlBlock (0xc0 + keyParity (taprootOutputKey output)) internal.point proof
-            fields =
-              insertInputTapInternalKey internal.point
-                . insertInputTapMerkleRoot (mastCommitment tree)
-                . insertTapLeafScript (TapLeafScript control leaf 0xc0)
-                . insertInputTapDerivation public.point (TapDerivation [leafHash 0xc0 leaf] (Derivation (fingerprintOf "d90c6a4f") "m/86'/0'/0'/0/1"))
-            withFields = withInputs (fields <$> psbt.inputs) psbt
-         in signsAndVerifies btc [secret] (withFields, coins) === Right True
-
-    it "the signer refuses a sighash type a Taproot signature may not use, and an internal key that does not give the coin" $ do
-      let secret = PrivateKey secretOne True
-          public = derivePublicKey secret
-          other = compressedKey secretTwo
-          coinScript = taprootScriptOutput (TaprootOutput public.point Nothing)
-          (psbt, _) = spendingPsbt coinScript
-          withFields m = withInputs [m (insertInputTapInternalKey public.point (inputAt 0 psbt))] psbt
-      signPsbt btc (keySigner secret.key) (withFields (insertSigHashType (setForkIdFlag sigHashAll))) `shouldBe` Left "Input 0: the sighash type 65 is not one a Taproot signature may use"
-      signPsbt btc (keySigner secret.key) (withInputs [insertInputTapInternalKey other.point (inputAt 0 psbt)] psbt) `shouldBe` Left "Input 0: the internal key and the Merkle root do not give the output key of the coin"
-      -- Without the internal key, the input is left alone
-      signPsbt btc (keySigner secret.key) psbt `shouldBe` Right psbt
-
-{- Properties -}
-
-propertiesSpec :: Spec
-propertiesSpec =
-  describe "Any PSBT" $ do
-    prop "is read back as it was written" $
-      forAll (arbitraryPsbt btc) $
-        \psbt -> decodePsbt (encodePsbt psbt) == Right psbt
-
-    prop "is read back from its base64 text" $
-      forAll (arbitraryPsbt btc) $
-        \psbt -> decodePsbtBase64 (encodePsbtBase64 psbt) == Right psbt
-
-    prop "combined with itself is itself" $
-      forAll (arbitraryPsbt btc) $
-        \psbt -> combinePsbt psbt psbt == Right psbt
-
-    -- The combiner of BIP 174 keeps every entry that either PSBT has. The
-    -- key type 0x7e is one no map knows.
-    prop "combined with a copy that has one more entry in every map, in either order, is that copy" $
-      forAll (arbitraryPsbt btc) $ \psbt ->
-        let oneMore = Map.insert (Key 0x7e "combiner test") "one more entry"
-            copy = Psbt psbt.version psbt.unsignedTx (oneMore psbt.globals) (oneMore <$> psbt.inputs) (oneMore <$> psbt.outputs)
-         in combinePsbt psbt copy == Right copy && combinePsbt copy psbt == Right copy
-
-{- What the decoder refuses -}
-
--- | The unsigned transaction of 'tinyPsbt': version 2, one input that
--- spends output 0 of the transaction whose id bytes are 00 01 … 1f, one
--- output of 1,000 satoshi, lock time 0. It is 82 bytes long.
-tinyTx :: Text
-tinyTx = "0200000001000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f0000000000ffffffff01e803000000000000160014111111111111111111111111111111111111111100000000"
-
--- | A PSBT of version 0 over 'tinyTx', with the entries given, in hex, in
--- its global map, in the map of its input and in the map of its output.
--- An entry is a key after its length, then a value after its length. The
--- first entry is the transaction: 0x52 is its 82 bytes.
-tinyPsbt :: Text -> Text -> Text -> ByteString
-tinyPsbt globalEntries inputEntries outputEntries =
-  hexBytes ("70736274ff" <> "010052" <> tinyTx <> globalEntries <> "00" <> inputEntries <> "00" <> outputEntries <> "00")
-
--- | The same payment as 'tinyPsbt' in version 2, with the entries given in
--- the map of its input: the transaction version 2, one input, one output
--- and the PSBT version 2 in the global map, the transaction id and the
--- output index 0 in the input, the amount and the script in the output.
-tinyPsbt2 :: Text -> ByteString
-tinyPsbt2 inputEntries =
-  hexBytes $
-    "70736274ff"
-      <> ("01020402000000" <> "01040101" <> "01050101" <> "01fb0402000000" <> "00")
-      <> (inputEntries <> "010e20000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" <> "010f0400000000" <> "00")
-      <> ("010308e803000000000000" <> "01041600141111111111111111111111111111111111111111" <> "00")
-
--- | 33 bytes that start like a compressed public key and are no point of
--- the curve: the x coordinate ff…ff is above the field size
-notAPoint :: Text
-notAPoint = "02" <> T.replicate 32 "ff"
-
--- | A public key of the BIP 174 vectors
-aPoint :: Text
-aPoint = "029583bf39ae0a609747ad199addd634fa6108559d6c5cd39b4c2183f1ab96e07f"
-
--- | A transaction of 61 bytes that the input of 'tinyTx' does not spend:
--- one input, one output of 5,000 satoshi with the script OP_1
-anotherTx :: Text
-anotherTx = "0100000001" <> T.replicate 32 "00" <> "ffffffff" <> "00" <> "ffffffff" <> "01" <> "8813000000000000" <> "0151" <> "00000000"
-
--- | A leaf of a script tree as PSBT_OUT_TAP_TREE lists it: its depth, its
--- leaf version, and after its length of 34 bytes the script
--- @<32 bytes of 0x22> OP_CHECKSIG@. It is 37 bytes long.
-treeLeaf :: Text -> Text -> Text
-treeLeaf depth version = depth <> version <> "22" <> "20" <> T.replicate 32 "22" <> "ac"
-
-decoderChecksSpec :: Spec
-decoderChecksSpec =
-  describe "What the decoder refuses, as Bitcoin Core 32.1 does" $ do
-    it "reads the small PSBT that the cases below add one entry to, in both versions" $ do
-      (encodePsbt <$> decodePsbt (tinyPsbt "" "" "")) `shouldBe` Right (tinyPsbt "" "" "")
-      (encodePsbt <$> decodePsbt (tinyPsbt2 "")) `shouldBe` Right (tinyPsbt2 "")
-
-    -- The type of a key is a compact size integer. fd0000 is 0, and fd0200
-    -- is 2, over three bytes where one is enough.
-    it "refuses a key whose type is not in its shortest form" $ do
-      decodePsbt (tinyPsbt "03fd000001aa" "" "") `shouldBe` Left "The global map has a key whose type is not in its shortest form"
-      decodePsbt (tinyPsbt "" "03fd020001aa" "") `shouldBe` Left "Input 0 has a key whose type is not in its shortest form"
-      decodePsbt (tinyPsbt "" "" "09ff010000000000000001aa") `shouldBe` Left "Output 0 has a key whose type is not in its shortest form"
-
-    -- fe announces a type of four more bytes, and the key has one more
-    it "refuses a key that ends inside its type" $
-      decodePsbt (tinyPsbt "" "02fe0101aa" "") `shouldBe` Left "Input 0 has a key that ends inside its type"
-
-    -- Bitcoin Core reads no compact size above 0x02000000. fe00000003 is
-    -- 0x03000000, and ff0000000001000000 is 2^32.
-    it "refuses a key whose type is above the largest compact size Bitcoin Core reads" $ do
-      decodePsbt (tinyPsbt "" "05fe0000000301aa" "") `shouldBe` Left "Input 0 has a key whose type is beyond any type"
-      decodePsbt (tinyPsbt "" "09ff000000000100000001aa" "") `shouldBe` Left "Input 0 has a key whose type is beyond any type"
-
-    -- fdfd00 is the type 253 and fe00000002 the type 0x02000000, both in
-    -- their shortest form
-    it "reads a key whose type takes three or five bytes, and writes it back" $ do
-      (encodePsbt <$> decodePsbt (tinyPsbt "" "03fdfd0001aa" "")) `shouldBe` Right (tinyPsbt "" "03fdfd0001aa" "")
-      (encodePsbt <$> decodePsbt (tinyPsbt "" "05fe0000000201aa" "")) `shouldBe` Right (tinyPsbt "" "05fe0000000201aa" "")
-
-    -- The key is the type 0x02 and 33 bytes, 34 in all (0x22). The value is
-    -- a signature of nine bytes, the smallest BIP 66 allows, with SIGHASH_ALL.
-    it "refuses a partial signature under a key that is not a point of the curve" $
-      decodePsbt (tinyPsbt "" ("2202" <> notAPoint <> "09300602010102010101") "")
-        `shouldBe` Left ("Input 0: the key 0x02 with the data " <> T.unpack notAPoint <> " is not a public key")
-
-    it "reads a partial signature that is in the encoding of BIP 66 with a defined sighash byte" $
-      (encodePsbt <$> decodePsbt (tinyPsbt "" ("2202" <> aPoint <> "09300602010102010101") ""))
-        `shouldBe` Right (tinyPsbt "" ("2202" <> aPoint <> "09300602010102010101") "")
-
-    -- "garbage" in ASCII, then no value at all, then the signature above
-    -- with the sighash byte 0x04, which no node accepts
-    it "refuses a partial signature that is not in the encoding of BIP 66, or whose sighash byte is not defined" $ do
-      let refusal = Left ("Input 0: the value of the key 0x02 with the data " <> T.unpack aPoint <> " is not a signature in the encoding of BIP 66 with a defined sighash byte")
-      decodePsbt (tinyPsbt "" ("2202" <> aPoint <> "0767617262616765") "") `shouldBe` refusal
-      decodePsbt (tinyPsbt "" ("2202" <> aPoint <> "00") "") `shouldBe` refusal
-      decodePsbt (tinyPsbt "" ("2202" <> aPoint <> "09300602010102010104") "") `shouldBe` refusal
-
-    -- Each value ends with the sighash byte 0x01, which is defined, and
-    -- breaks one rule of BIP 66: bytes that are no DER at all, a length
-    -- byte that does not cover the signature (0x07 for 6 bytes), an R that
-    -- is negative (0x80), and an R with a zero byte it does not need (0001)
-    it "refuses a partial signature with a defined sighash byte that breaks a rule of BIP 66" $ do
-      let refusal = Left ("Input 0: the value of the key 0x02 with the data " <> T.unpack aPoint <> " is not a signature in the encoding of BIP 66 with a defined sighash byte")
-      decodePsbt (tinyPsbt "" ("2202" <> aPoint <> "0aaabbccddeeff00112201") "") `shouldBe` refusal
-      decodePsbt (tinyPsbt "" ("2202" <> aPoint <> "09300702010102010101") "") `shouldBe` refusal
-      decodePsbt (tinyPsbt "" ("2202" <> aPoint <> "09300602018002010101") "") `shouldBe` refusal
-      decodePsbt (tinyPsbt "" ("2202" <> aPoint <> "0a30070202000102010101") "") `shouldBe` refusal
-
-    -- The value is the fingerprint d90c6a4f and the path m/0'
-    it "refuses a derivation record under a key that is not a point of the curve, on an input and on an output" $ do
-      decodePsbt (tinyPsbt "" ("2206" <> notAPoint <> "08d90c6a4f00000080") "")
-        `shouldBe` Left ("Input 0: the key 0x06 with the data " <> T.unpack notAPoint <> " is not a public key")
-      decodePsbt (tinyPsbt "" "" ("2202" <> notAPoint <> "08d90c6a4f00000080"))
-        `shouldBe` Left ("Output 0: the key 0x02 with the data " <> T.unpack notAPoint <> " is not a public key")
-
-    -- The key is the type 0x01 and the 78 bytes of an extended key, 79 in
-    -- all (0x4f): the version 0488b21e, depth 0, no parent, index 0, a chain
-    -- code of zeros, and the public key
-    it "refuses an extended public key whose key is not a point of the curve" $ do
-      let xpubWith key = "4f01" <> "0488b21e" <> "00" <> "00000000" <> "00000000" <> T.replicate 32 "00" <> key <> "04d90c6a4f"
-      (encodePsbt <$> decodePsbt (tinyPsbt (xpubWith aPoint) "" "")) `shouldBe` Right (tinyPsbt (xpubWith aPoint) "" "")
-      decodePsbt (tinyPsbt (xpubWith notAPoint) "" "") `shouldSatisfy` either ("is not an extended public key" `isSuffixOf`) (const False)
-
-    -- 0x3d is the 61 bytes of the transaction
-    it "refuses a previous transaction that is not the one the input spends, in both versions" $ do
-      decodePsbt (tinyPsbt "" ("01003d" <> anotherTx) "") `shouldBe` Left "Input 0: the previous transaction is not the one the input spends"
-      decodePsbt (tinyPsbt2 ("01003d" <> anotherTx)) `shouldBe` Left "Input 0: the previous transaction is not the one the input spends"
-
-    -- An empty tree, then a leaf of the leaf version 0xc1, a leaf at depth
-    -- 129 (0x81), one leaf alone at depth 1, and three leaves at depth 1.
-    -- 0x25 is the 37 bytes of a leaf, 0x6f the 111 bytes of three.
-    it "refuses a script tree that is empty, has an odd leaf version, a leaf deeper than 128, or leaves that make no tree" $ do
-      decodePsbt (tinyPsbt "" "" "010600") `shouldBe` Left "Output 0: the value of the key 0x06 is an empty script tree"
-      decodePsbt (tinyPsbt "" "" ("010625" <> treeLeaf "00" "c1")) `shouldBe` Left "Output 0: the value of the key 0x06 has a leaf with an odd leaf version"
-      decodePsbt (tinyPsbt "" "" ("010625" <> treeLeaf "81" "c0")) `shouldBe` Left "Output 0: the value of the key 0x06 has a leaf deeper than 128"
-      decodePsbt (tinyPsbt "" "" ("010625" <> treeLeaf "01" "c0")) `shouldBe` Left "Output 0: the value of the key 0x06 is not a whole script tree"
-      decodePsbt (tinyPsbt "" "" ("01066f" <> treeLeaf "01" "c0" <> treeLeaf "01" "c0" <> treeLeaf "01" "c0")) `shouldBe` Left "Output 0: the value of the key 0x06 is not a whole script tree"
-
-    it "reads a script tree of one leaf at depth 0, and one of two leaves at depth 1" $ do
-      (encodePsbt <$> decodePsbt (tinyPsbt "" "" ("010625" <> treeLeaf "00" "c0"))) `shouldBe` Right (tinyPsbt "" "" ("010625" <> treeLeaf "00" "c0"))
-      (encodePsbt <$> decodePsbt (tinyPsbt "" "" ("01064a" <> treeLeaf "01" "c0" <> treeLeaf "01" "c0"))) `shouldBe` Right (tinyPsbt "" "" ("01064a" <> treeLeaf "01" "c0" <> treeLeaf "01" "c0"))
-
-    -- The length 1 of the value "aa", over five bytes and over nine
-    it "refuses a length written over five or nine bytes that is not in its shortest form" $ do
-      decodePsbt (hexBytes ("70736274ff" <> emptyTxEntry <> "0120" <> "fe01000000" <> "aa" <> "00")) `shouldBe` Left "A length in the global map is not in its shortest form"
-      decodePsbt (hexBytes ("70736274ff" <> emptyTxEntry <> "0120" <> "ff0100000000000000" <> "aa" <> "00")) `shouldBe` Left "A length in the global map is not in its shortest form"
-
-    -- The key is the type 0x15 and a control block of 33 bytes plus 32 per
-    -- node. 128 nodes make 4,130 bytes with the type (fd2210), and 129 make
-    -- 4,162 (fd4210). The value is a script of 34 bytes and the leaf version.
-    it "refuses a control block of 129 nodes, and reads one of 128" $ do
-      let leafEntry nodes len = len <> "15" <> "c0" <> T.replicate 32 "22" <> T.replicate (32 * nodes) "33" <> "23" <> "20" <> T.replicate 32 "22" <> "ac" <> "c0"
-      (B.length . encodePsbt <$> decodePsbt (tinyPsbt "" (leafEntry 128 "fd2210") "")) `shouldBe` Right (B.length (tinyPsbt "" (leafEntry 128 "fd2210") ""))
-      decodePsbt (tinyPsbt "" (leafEntry 129 "fd4210") "") `shouldSatisfy` either ("is not a control block" `isSuffixOf`) (const False)
-
-    -- An extended key of depth 0 has no path. The value is the fingerprint
-    -- and the one index 0'.
-    it "refuses an extended public key of depth 0 with a path of one index" $ do
-      let xpub = "4f01" <> "0488b21e" <> "00" <> "00000000" <> "00000000" <> T.replicate 32 "00" <> aPoint <> "08d90c6a4f00000080"
-      decodePsbt (tinyPsbt xpub "" "") `shouldSatisfy` either ("has a path that is not as deep as the key" `isSuffixOf`) (const False)
-
-    -- Two entries with the same key: the type 0x20 and 1,000 bytes of 0xab,
-    -- 1,001 in all (fde903)
-    it "names at most 40 bytes of the data of a key in a refusal, then its length" $ do
-      let entry = "fde903" <> "20" <> T.replicate 1000 "ab" <> "00"
-      decodePsbt (tinyPsbt (entry <> entry) "" "")
-        `shouldBe` Left ("The global map has the key 0x20 with the data " <> concat (replicate 40 "ab") <> "… (1000 bytes) twice")
-
-{- What the signer and the finalizer sign, and what they leave alone -}
-
--- | A transaction that spends the two outputs of a previous transaction
--- paying the two scripts, as a PSBT with that previous transaction on both
--- inputs. Each output holds 2 BTC.
-spendingTwo :: ByteString -> ByteString -> Psbt
-spendingTwo scriptA scriptB = Psbt Version0 tx Map.empty [input, input] [Map.empty]
-  where
-    parent = Tx 1 [TxIn (OutPoint "e567952fb6cc33857f392efa3a46c995a28f69cca4bb1b37e0204dab1ec7a389" 1) "" 0xffffffff] [TxOut 200000000 scriptA, TxOut 200000000 scriptB] [] 0
-    tx = Tx 2 [TxIn (OutPoint (txHash parent) 0) "" 0xfffffffe, TxIn (OutPoint (txHash parent) 1) "" 0xfffffffe] [TxOut 399990000 (hexBytes "76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac")] [] 0
-    input = insertNonWitnessUtxo parent Map.empty
-
-signerScopeSpec :: Spec
-signerScopeSpec =
-  describe "What the signer and the finalizer sign, and what they leave alone" $ do
-    let secret = PrivateKey secretOne True
-        public = derivePublicKey secret
-        otherPublic = compressedKey secretTwo
-        signer = keySigner secretOne
-        ownScript = encodeSerial (PayPKHash (addressHash (encodeSerial public)))
-        otherScript = encodeSerial (PayPKHash (addressHash (encodeSerial otherPublic)))
-        (psbt, _) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))
-        parent = fromJust (either (const Nothing) id (nonWitnessUtxo (inputAt 0 psbt)))
-        coin = head parent.outputs
-        signatureCounts = mapM (fmap length . partialSignatures) . (.inputs)
-        keyHex = show (encodeHex (encodeSerial public))
-
-    -- BIP 32 gives a key a depth of one byte, so no key is 256 steps below
-    -- another
-    it "a signer built from an extended key holds no key for a record whose path has 256 steps" $ do
-      let master = makeXPrvKey "PSBT signer test"
-          tooDeep = Derivation (xPubFP (deriveXPubKey master)) (listToPath (replicate 256 0))
-      (xPrvSigner master Nothing).keyOfRecord public tooDeep `shouldBe` Nothing
-
-    it "signing leaves unsigned an input whose record names the signer's key with a path of 256 steps" $ do
-      let master = makeXPrvKey "PSBT signer test"
-          tooDeep = Derivation (xPubFP (deriveXPubKey master)) (listToPath (replicate 256 0))
-          withRecord = withInputs (insertInputDerivation public tooDeep <$> psbt.inputs) psbt
-      (signatureCounts =<< signPsbt btc (xPrvSigner master Nothing) withRecord) `shouldBe` Right [0]
-
-    -- The second record names a key the coin does not pay. A signer that
-    -- derives a key for every record can be made to work without end.
-    it "asks the signer for the key of a record only when the script of the coin names that key" $ do
-      let onlyOwn = signer {keyOfRecord = \asked _ -> if asked == public then Just secretOne else error "asked for the key of a record the coin does not name"}
-          withRecords = withInputs ((recordOf public . recordOf otherPublic) <$> psbt.inputs) psbt
-      (signatureCounts =<< signPsbt btc onlyOwn withRecords) `shouldBe` Right [1]
-
-    -- The coin pays the hash of key 2, and the record names key 1, which
-    -- the signer holds. BIP 174: "If a Signer cannot sign a transaction, it
-    -- must not add a Partial Signature."
-    it "adds no signature for a key the script of the coin does not name, even when a derivation record names it" $ do
-      let (other, _) = spendingPsbt (PayPKHash (addressHash (encodeSerial otherPublic)))
-      (signatureCounts =<< signPsbt btc signer (withInputs (recordOf public <$> other.inputs) other)) `shouldBe` Right [0]
-
-    it "adds no signature to a P2WSH coin whose witness script is missing, nor to a P2SH coin whose redeem script is missing" $ do
-      let multisig = forceRight (encodeOutput (PayMulSig [public, otherPublic] 2))
-          (p2wsh, _) = spendingPsbt (forceRight (toP2WSH multisig))
-          (p2sh, _) = spendingPsbt (forceRight (toP2SH multisig))
-      (signatureCounts =<< signPsbt btc signer (withInputs (recordOf public <$> p2wsh.inputs) p2wsh)) `shouldBe` Right [0]
-      (signatureCounts =<< signPsbt btc signer (withInputs (recordOf public <$> p2sh.inputs) p2sh)) `shouldBe` Right [0]
-
-    it "signs a P2SH-P2WPKH coin with its redeem script by the hash of its key, without a derivation record" $ do
-      let redeem = forceRight (encodeOutput (PayWitnessPKHash (addressHash (encodeSerial public))))
-          (nested, _) = spendingPsbt (forceRight (toP2SH redeem))
-      (signatureCounts =<< signPsbt btc signer (withInputs (insertInputRedeemScript redeem <$> nested.inputs) nested)) `shouldBe` Right [1]
-
-    -- 0x41 is SIGHASH_ALL (0x01) with SIGHASH_FORKID (0x40)
-    it "on the Bitcoin Cash networks, signs an input that asks for no sighash type with SIGHASH_ALL and the fork id flag" $
-      forM_ [bch, bchTest, bchTest4, bchRegTest] $ \net ->
-        (map (B.last . snd) <$> (partialSignatures . inputAt 0 =<< signPsbt net signer psbt)) `shouldBe` Right [0x41]
-
-    -- Input 0 is a coin of key 1. Input 1 is a P2WSH coin of someone else,
-    -- whose witness script is <key 2> OP_CHECKSIGVERIFY <144>
-    -- OP_CHECKSEQUENCEVERIFY, which is no template the library knows.
-    it "signs and finalizes its own input, and leaves alone an input whose witness script is not a standard template" $ do
-      let timelocked = Script [opPushData (encodeSerial otherPublic), OP_CHECKSIGVERIFY, opPushData "\x90\x00", OP_CHECKSEQUENCEVERIFY]
-          both = spendingTwo ownScript (encodeSerial (forceRight (toP2WSH timelocked)))
-          withScript = withInputs [inputAt 0 both, insertInputWitnessScript timelocked (inputAt 1 both)] both
-      signed <- expectRight (signPsbt btc signer withScript)
-      signatureCounts signed `shouldBe` Right [1, 0]
-      inputAt 1 signed `shouldBe` inputAt 1 withScript
-      final <- expectRight (finalizePsbt btc signed)
-      map (isJust . finalScriptSig) final.inputs `shouldBe` [True, False]
-      inputAt 1 final `shouldBe` inputAt 1 withScript
-
-    -- Input 1 is a P2PKH coin of key 2, known from its output alone. The
-    -- signer could not sign it anyway. Bitcoin Core leaves such an input
-    -- unsigned and signs the others.
-    it "leaves alone a legacy coin known from its witness output only when it holds no key for it, and signs its own input" $ do
-      let both = spendingTwo ownScript otherScript
-          witnessOnly = withInputs [inputAt 0 both, insertWitnessUtxo (TxOut 200000000 otherScript) Map.empty] both
-      (signatureCounts =<< signPsbt btc signer witnessOnly) `shouldBe` Right [1, 0]
-
-    -- Bitcoin Core refuses the whole PSBT too: a sighash type that the
-    -- caller did not ask for is a mismatch on any input that has its coin
-    it "refuses a PSBT in which another party's input asks for a sighash type the signer does not accept" $ do
-      let both = spendingTwo ownScript otherScript
-          asking = withInputs [inputAt 0 both, insertSigHashType (setAnyoneCanPay sigHashSingle) (inputAt 1 both)] both
-      signPsbt btc signer asking `shouldBe` Left "Input 1: the sighash type 131 is not one the signer accepts"
-
-    it "refuses to sign a SegWit version 0 coin with an uncompressed key" $ do
-      let uncompressed = PublicKey public.point False
-          (p2wpkh, _) = spendingPsbt (PayWitnessPKHash (addressHash (encodeSerial uncompressed)))
-      signPsbt btc signer p2wpkh `shouldBe` Left "Input 0: a SegWit version 0 coin may not be signed with an uncompressed key"
-
-    -- The signature is a real one of key 1, on another coin. The finalizer
-    -- must refuse it for the form of the key, whatever it signs.
-    it "the finalizer refuses a signature of an uncompressed key on a SegWit version 0 coin" $ do
-      let uncompressed = PublicKey public.point False
-          (p2wpkh, _) = spendingPsbt (PayWitnessPKHash (addressHash (encodeSerial uncompressed)))
-      signed <- expectRight (signPsbt btc signer psbt)
-      signature <- case partialSignatures (inputAt 0 signed) of
-        Right [(_, sig)] -> return sig
-        _ -> fail "one signature"
-      finalizePsbt btc (withInputs (insertPartialSignature uncompressed signature <$> p2wpkh.inputs) p2wpkh)
-        `shouldBe` Left ("Input 0: the signature of the key " <> show (encodeHex (encodeSerial uncompressed)) <> " is of an uncompressed key, which a SegWit version 0 coin may not be spent with")
-
-    -- The second signature is the one of key 1, filed under key 2: it does
-    -- not verify for key 2. The coin does not name key 2, so the finalizer
-    -- has no reason to look at it.
-    it "the finalizer does not look at a partial signature of a key the script of the coin does not name" $ do
-      signed <- expectRight (signPsbt btc signer psbt)
-      signature <- case partialSignatures (inputAt 0 signed) of
-        Right [(_, sig)] -> return sig
-        _ -> fail "one signature"
-      let withStray = withInputs (insertPartialSignature otherPublic signature <$> signed.inputs) signed
-      (finalScriptSig . inputAt 0 <$> finalizePsbt btc withStray) `shouldBe` (finalScriptSig . inputAt 0 <$> finalizePsbt btc signed)
-      (isJust . finalScriptSig . inputAt 0 <$> finalizePsbt btc withStray) `shouldBe` Right True
-
-    -- Bitcoin Core takes SIGHASH_ALL for an input that names no sighash
-    -- type, and gives no final script when a signature uses another
-    it "the finalizer refuses a SIGHASH_NONE signature on an input that names no sighash type" $ do
-      let acceptingNone = signer {acceptedSigHashes = [sigHashNone]}
-      signed <- expectRight (signPsbt btc acceptingNone (withInputs (insertSigHashType sigHashNone <$> psbt.inputs) psbt))
-      finalizePsbt btc (withInputs (deleteSigHashType <$> signed.inputs) signed)
-        `shouldBe` Left ("Input 0: the signature of the key " <> keyHex <> " does not use SIGHASH_ALL, and the input names no sighash type")
-
-    it "the finalizer leaves alone a signed legacy coin that is known from its witness output only" $ do
-      signed <- expectRight (signPsbt btc signer psbt)
-      let witnessOnly = withInputs [insertWitnessUtxo coin (Map.delete (Key 0x00 "") (inputAt 0 signed))] signed
-      finalizePsbt btc witnessOnly `shouldBe` Right witnessOnly
-
-    -- A signer written by a caller may answer with a key that is not the
-    -- one asked for. Its signature would be of no use to anyone.
-    it "signs with a key the signer gives only when it is the key the coin names" $ do
-      let wrongByRecord = signer {keyOfRecord = \_ _ -> Just secretTwo, keyOfHash = const Nothing}
-          wrongByHash = signer {keyOfRecord = \_ _ -> Nothing, keyOfHash = const (Just (PrivateKey secretTwo True))}
-          withRecord = withInputs (recordOf public <$> psbt.inputs) psbt
-      (signatureCounts =<< signPsbt btc wrongByRecord withRecord) `shouldBe` Right [0]
-      (signatureCounts =<< signPsbt btc wrongByHash psbt) `shouldBe` Right [0]
-
-    it "a signer of one key holds no key for the record of another key" $ do
-      let record = Derivation (fingerprintOf "00000000") "m/0"
-      (keySigner secretOne).keyOfRecord otherPublic record `shouldBe` Nothing
-      (keySigner secretOne).keyOfRecord public record `shouldBe` Just secretOne
-
-    -- The time lock 100 is below 500,000,000, so it would be read as a height
-    it "a constructor refuses an input whose map breaks the spec, such as a required time lock below 500000000" $ do
-      let modifiable = withFlags (Modifiable True True False 0) (withVersion Version2 (psbtOf (Tx 2 [] [] [] 0)))
-      addInput coinInput (Map.singleton (Key 0x11 "") (hexBytes "64000000")) modifiable
-        `shouldBe` Left "Input 0: the value of the key 0x11 is a time lock below 500000000"
-      addOutput paidOutput (Map.singleton (Key 0x06 "") "") modifiable
-        `shouldBe` Left "Output 0: the value of the key 0x06 is an empty script tree"
-      -- The previous transaction has one output, and the input spends its second
-      let previous = Tx 1 [coinInput] [paidOutput] [] 0
-      addInput (TxIn (OutPoint (txHash previous) 1) "" 0xffffffff) (insertNonWitnessUtxo previous Map.empty) modifiable
-        `shouldBe` Left "Input 0: the input spends an output its previous transaction does not have"
-      addInput (TxIn (OutPoint (txHash previous) 0) "" 0xffffffff) (insertNonWitnessUtxo emptyTx Map.empty) modifiable
-        `shouldBe` Left "Input 0: the previous transaction is not the one the input spends"
-
-    -- 0065cd1d is 500,000,000, the first lock time that is a time, and
-    -- ff64cd1d is 499,999,999
-    it "a required time lock of 500000000 is the lock time of the transaction, and one of 499999999 is refused" $ do
-      ((.unsignedTx.locktime) <$> decodePsbt (tinyPsbt2 "0111040065cd1d")) `shouldBe` Right 500000000
-      decodePsbt (tinyPsbt2 "011104ff64cd1d") `shouldBe` Left "Input 0: the value of the key 0x11 is a time lock below 500000000"
-
-{- The checks on Taproot signatures -}
-
--- | The PSBT with each of its input maps changed
-onInputs :: (PsbtMap -> PsbtMap) -> Psbt -> Psbt
-onInputs f psbt = withInputs (f <$> psbt.inputs) psbt
-
--- | The map with the entries of one key type changed
-onKeyType :: Word8 -> (Key -> ByteString -> (Key, ByteString)) -> PsbtMap -> PsbtMap
-onKeyType t f m = Map.fromList [if key.keyType == t then f key value else (key, value) | (key, value) <- Map.toList m]
-
--- | Bytes with their last bit flipped
-flipLastBit :: ByteString -> ByteString
-flipLastBit bytes = B.init bytes <> B.singleton (B.last bytes `xor` 1)
-
--- | An entry with the last bit of its value flipped, and one with the last
--- bit of the data of its key flipped
-flipValue, flipKeyData :: Key -> ByteString -> (Key, ByteString)
-flipValue key value = (key, flipLastBit value)
-flipKeyData key value = (Key key.keyType (flipLastBit key.keyData), value)
-
-taprootChecksSpec :: Vectors371 -> Spec
-taprootChecksSpec vectors =
-  describe "The checks on Taproot signatures" $ do
-    let vectorAt i = psbtOfVector (vectors.accepted371 !! i)
-        internal = derivePubKey secretOne
-        leafKey = derivePubKey secretTwo
-        leaf = Script [opPushData (exportXOnlyPubKey leafKey), OP_CHECKSIG]
-        tree = MASTBranch (MASTLeaf 0xc0 leaf) (MASTLeaf 0xc0 (Script [OP_RETURN]))
-        output = TaprootOutput internal (Just tree)
-        control = encodeControlBlock (0xc0 + keyParity (taprootOutputKey output)) internal [leafHash 0xc0 (Script [OP_RETURN])]
-        (withTree, _) = spendingPsbt (taprootScriptOutput output)
-        treeFields = insertInputTapInternalKey internal . insertInputTapMerkleRoot (mastCommitment tree) . insertTapLeafScript (TapLeafScript control leaf 0xc0)
-        derivation = Derivation (fingerprintOf "d90c6a4f") "m/86'/0'/0'/0/0"
-        -- A signer that finds its keys by derivation record only, as one
-        -- built from an extended key does
-        byRecord secret = (keySigner secret) {keyOfHash = const Nothing}
-
-    it "the finalizer refuses a key path signature that does not verify" $ do
-      psbt <- vectorAt 1
-      finalizePsbt btc (onInputs (onKeyType 0x13 flipValue) psbt)
-        `shouldBe` Left "Input 0: the key path signature does not verify"
-
-    it "the finalizer refuses a script path signature that does not verify" $ do
-      psbt <- vectorAt 5
-      finalizePsbt btc (onInputs (onKeyType 0x14 flipValue) psbt)
-        `shouldBe` Left "Input 0: the script path signature does not verify"
-
-    it "the finalizer refuses a leaf whose control block does not commit it to the output key" $ do
-      psbt <- vectorAt 5
-      finalizePsbt btc (onInputs (onKeyType 0x15 flipKeyData) psbt)
-        `shouldBe` Left "Input 0: the control block of the leaf does not commit it to the output key"
-
-    -- The signatures of both vectors are 64 bytes, which is SIGHASH_DEFAULT
-    it "the finalizer refuses a Taproot signature that does not use the sighash type the input names" $ do
-      keyPath <- vectorAt 1
-      scriptPath <- vectorAt 5
-      finalizePsbt btc (onInputs (insertSigHashType sigHashAll) keyPath) `shouldBe` Left "Input 0: a Taproot signature does not use the sighash type of the input"
-      finalizePsbt btc (onInputs (insertSigHashType sigHashAll) scriptPath) `shouldBe` Left "Input 0: a Taproot signature does not use the sighash type of the input"
-
-    -- Bitcoin Core takes SIGHASH_DEFAULT for a Taproot input that names no
-    -- sighash type, and then wants every signature to be 64 bytes
-    it "the finalizer refuses a SIGHASH_ALL key path signature on an input that names no sighash type" $ do
-      let (keyOnly, _) = spendingPsbt (taprootScriptOutput (TaprootOutput internal Nothing))
-          asking = onInputs (insertSigHashType sigHashAll . insertInputTapInternalKey internal) keyOnly
-      signed <- expectRight (signPsbt btc (keySigner secretOne) asking)
-      (fmap (fmap (.hash)) . tapKeySig . inputAt 0) signed `shouldBe` Right (Just sigHashAll)
-      finalizePsbt btc (onInputs deleteSigHashType signed)
-        `shouldBe` Left "Input 0: a Taproot signature does not use SIGHASH_DEFAULT, and the input names no sighash type"
-
-    it "the signer refuses a Taproot coin that asks for a sighash type the signer does not accept" $ do
-      let (keyOnly, _) = spendingPsbt (taprootScriptOutput (TaprootOutput internal Nothing))
-      signPsbt btc (keySigner secretOne) (onInputs (insertSigHashType sigHashSingle . insertInputTapInternalKey internal) keyOnly)
-        `shouldBe` Left "Input 0: the sighash type 3 is not one the signer accepts"
-
-    -- BIP 371: the leaf hashes of a record "are of the leaves which involve
-    -- this public key". A key that is the internal key and also a leaf key
-    -- has a record with a leaf hash, and Bitcoin Core writes it that way.
-    it "signs the key path of a Taproot coin when the record of its internal key lists a leaf" $ do
-      let record = insertInputTapDerivation internal (TapDerivation [leafHash 0xc0 leaf] derivation)
-      signed <- expectRight (signPsbt btc (byRecord secretOne) (onInputs (record . treeFields) withTree))
-      (fmap isJust . tapKeySig . inputAt 0) signed `shouldBe` Right True
-
-    it "signs a leaf with the key of a record that lists that leaf, and not with one that lists another leaf" $ do
-      let listing hashes = insertInputTapDerivation leafKey (TapDerivation hashes derivation)
-          signatures f = fmap length . tapScriptSigs . inputAt 0 =<< signPsbt btc (byRecord secretTwo) (onInputs (f . treeFields) withTree)
-      signatures (listing [leafHash 0xc0 leaf]) `shouldBe` Right 1
-      signatures (listing [leafHash 0xc0 (Script [OP_RETURN])]) `shouldBe` Right 0
-
-    -- The leaf is in no tree of the coin: its control block names another
-    -- internal key
-    it "signs no leaf whose control block does not commit it to the coin" $ do
-      let stray = encodeControlBlock 0xc0 leafKey [leafHash 0xc0 (Script [OP_RETURN])]
-          fields = insertInputTapInternalKey internal . insertInputTapMerkleRoot (mastCommitment tree) . insertTapLeafScript (TapLeafScript stray leaf 0xc0)
-      signed <- expectRight (signPsbt btc (keySigner secretTwo) (onInputs fields withTree))
-      (fmap length . tapScriptSigs . inputAt 0) signed `shouldBe` Right 0
-
-    it "signs a Taproot coin of a PSBT of version 2 by its key path, and the PSBT stays of version 2" $ do
-      let (keyOnly, coins) = spendingPsbt (taprootScriptOutput (TaprootOutput internal Nothing))
-          version2 = withVersion Version2 (onInputs (insertInputTapInternalKey internal) keyOnly)
-      final <- expectRight (finalizePsbt btc =<< signPsbt btc (keySigner secretOne) version2)
-      final.version `shouldBe` Version2
-      tx <- expectRight (psbtTransaction final)
-      verifyStdTx btc tx coins `shouldBe` True
-
-{- The coins of a PSBT, and the previous transaction a signer may require -}
-
-coinsSpec :: Spec
-coinsSpec =
-  describe "The coins of a PSBT" $ do
-    let public = compressedKey secretOne
-        signer = keySigner secretOne
-        program = PayWitnessPKHash (addressHash (encodeSerial public))
-        (psbt, _) = spendingPsbt program
-        parent = fromJust (either (const Nothing) id (nonWitnessUtxo (inputAt 0 psbt)))
-        output = head parent.outputs
-        witnessOnly = withInputs [insertWitnessUtxo output Map.empty] psbt
-        signatureCounts = mapM (fmap length . partialSignatures) . (.inputs)
-
-    it "tells the coin of each input, and whether it comes from the previous transaction of the input" $ do
-      inputCoins psbt `shouldBe` Right [Just (InputCoin output True)]
-      inputCoins witnessOnly `shouldBe` Right [Just (InputCoin output False)]
-      inputCoins (withInputs [Map.empty] psbt) `shouldBe` Right [Nothing]
-
-    -- The coin holds 200,000,000 satoshi and the outputs pay 99,999,699 and
-    -- 100,000,000: 200,000,000 − 199,999,699 = 301
-    it "gives the fee when every coin comes from its previous transaction" $
-      psbtFee psbt `shouldBe` Right 301
-
-    it "gives no fee when the amount of a coin is only a claim, when a coin is missing, or when the outputs pay more than the coins hold" $ do
-      psbtFee witnessOnly `shouldBe` Left "Input 0: the coin is given as a witness output only, so its amount is not checked"
-      psbtFee (withInputs [Map.empty] psbt) `shouldBe` Left "Input 0 has no coin"
-      -- The same transaction with one more output of 302 satoshi
-      let tx = psbt.unsignedTx
-          paysMore = Psbt Version0 (Tx tx.version tx.inputs (tx.outputs <> [TxOut 302 ""]) [] tx.locktime) Map.empty psbt.inputs [Map.empty, Map.empty, Map.empty]
-      psbtFee paysMore `shouldBe` Left "The outputs pay more than the coins hold"
-
-    -- BIP 174: "The Signer may choose to fail to sign a segwit input if a
-    -- non-witness UTXO is not provided."
-    it "a signer refuses a SegWit version 0 coin known from its witness output only, and signs it with its previous transaction" $ do
-      signPsbt btc signer witnessOnly
-        `shouldBe` Left "Input 0: the coin is given as a witness output only, and the signer requires the previous transaction of a SegWit version 0 coin"
-      (signatureCounts =<< signPsbt btc signer psbt) `shouldBe` Right [1]
-      (signatureCounts =<< signPsbt btc signer (withInputs [insertWitnessUtxo output (inputAt 0 psbt)] psbt)) `shouldBe` Right [1]
-
-    it "a signer told to trust witness outputs signs a SegWit version 0 coin known from its witness output only" $
-      (signatureCounts =<< signPsbt btc (signer {requirePreviousTx = False}) witnessOnly) `shouldBe` Right [1]
-
-    -- CVE-2020-14199. The signer holds two coins of 15 and 20 BTC. The
-    -- writer of the PSBT understates the first as 5 BTC and overstates the
-    -- second. A signature of each input commits to the amount of that input
-    -- alone, so the signature of the second input would be valid in a
-    -- transaction that burns the 10 BTC of difference as fee.
-    it "a signer refuses a PSBT that states the amounts of its SegWit version 0 coins without their previous transactions" $ do
-      let both = spendingTwo (encodeSerial program) (encodeSerial program)
-          claimed = withInputs [insertWitnessUtxo (TxOut 500000000 (encodeSerial program)) Map.empty, insertWitnessUtxo (TxOut 2000000000 (encodeSerial program)) Map.empty] both
-      signPsbt btc signer claimed
-        `shouldBe` Left "Input 0: the coin is given as a witness output only, and the signer requires the previous transaction of a SegWit version 0 coin"
-
-    -- A Taproot signature commits to the amount of every coin (BIP 341)
-    it "a signer signs a Taproot coin known from its witness output only" $ do
-      let internal = derivePubKey secretOne
-          (taproot, _) = spendingPsbt (taprootScriptOutput (TaprootOutput internal Nothing))
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE TupleSections #-}
+{-# OPTIONS_GHC -Wno-deprecations #-}
+
+-- | The PSBT format of BIP 174, and its version 2 of BIP 370: the vectors
+-- of both BIPs, the bytes of a PSBT and the refusals of what breaks the
+-- spec, the fields of the spec, the roles: combining, signing, finalizing
+-- and extracting, and the inputs and outputs a PSBT of version 2 takes.
+module Haskoin.Transaction.PsbtSpec (spec) where
+
+import BitcoinCore
+import Control.Exception (evaluate)
+import Control.Monad (foldM, forM, forM_)
+import Crypto.Hash (Digest, SHA256, digestFromByteString)
+import Data.Aeson ((.:), (.:?), (.=))
+import Data.Aeson qualified as Json
+import Data.Aeson.Key qualified as Key
+import Data.Bits (xor)
+import Data.ByteArray (convert)
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as B
+import Data.ByteString.Lazy qualified as BL
+import Data.Bytes.Put (runPutS)
+import Data.Bytes.Serial (serialize)
+import Data.List (isPrefixOf, isSuffixOf)
+import Data.Map.Strict qualified as Map
+import Data.Maybe (fromJust, fromMaybe, isJust, listToMaybe, mapMaybe)
+import Data.Serialize qualified as S
+import Data.String (fromString)
+import Data.Text (Text)
+import Data.Text qualified as T
+import Data.Text.Encoding (decodeUtf8, encodeUtf8)
+import Data.Word (Word32, Word64, Word8)
+import Haskoin.Address
+import Haskoin.Crypto
+import Haskoin.Network.Constants
+import Haskoin.Network.Data
+import Haskoin.Script
+import Haskoin.Transaction
+import Haskoin.Util
+import Haskoin.Util.Arbitrary
+import Numeric (showHex)
+import System.Environment (lookupEnv)
+import System.Timeout (timeout)
+import Test.Hspec
+import Test.Hspec.QuickCheck (prop)
+import Test.QuickCheck
+
+{- The vectors of the BIP -}
+
+-- The vectors live in data/psbt_bip174.json, copied from the BIP. Each has
+-- the case the BIP gives, its hex, and its base64 when the BIP gives it.
+data Vector = Vector
+  { vecCase :: String,
+    vecHex :: Text,
+    vecBase64 :: Maybe Text
+  }
+
+instance Json.FromJSON Vector where
+  parseJSON = Json.withObject "vector" $ \o -> Vector <$> o .: "case" <*> o .: "hex" <*> o .:? "base64"
+
+-- | The invalid PSBTs, the valid ones, the PSBTs of the walk-through of the
+-- roles, in the order of the BIP, and the transaction its extractor gives
+data Vectors = Vectors
+  { invalid :: [Vector],
+    valid :: [Vector],
+    roles :: [Vector],
+    extracted :: Vector
+  }
+
+instance Json.FromJSON Vectors where
+  parseJSON = Json.withObject "vectors" $ \o -> Vectors <$> o .: "invalid" <*> o .: "valid" <*> o .: "roles" <*> o .: "extracted"
+
+-- The PSBTs of the walk-through, by their place in it
+creator, updater, updaterWithSigHash, firstSigner, secondSigner, combiner, finalizer, unknownA, unknownB, unknownCombined, toCombineA, toCombineB, combined :: Vectors -> Vector
+creator v = roles v !! 0
+updater v = roles v !! 1
+updaterWithSigHash v = roles v !! 2
+firstSigner v = roles v !! 3
+secondSigner v = roles v !! 4
+combiner v = roles v !! 5
+finalizer v = roles v !! 6
+unknownA v = roles v !! 7
+unknownB v = roles v !! 8
+unknownCombined v = roles v !! 9
+toCombineA v = roles v !! 10
+toCombineB v = roles v !! 11
+combined v = roles v !! 12
+
+hexBytes :: Text -> ByteString
+hexBytes = fromJust . decodeHex
+
+bytesOf :: Vector -> ByteString
+bytesOf = hexBytes . vecHex
+
+expectRight :: Either String a -> IO a
+expectRight = either fail return
+
+forceRight :: Either String a -> a
+forceRight = either error id
+
+fingerprintOf :: Text -> Fingerprint
+fingerprintOf = forceRight . textToFingerprint
+
+-- | The PSBT of a vector, which must decode
+psbtOfVector :: Vector -> IO Psbt
+psbtOfVector v = expectRight (decodePsbt (bytesOf v))
+
+-- | The secret keys 1, 2 and 3 of the signer tests. Their public keys are
+-- the points G, 2G and 3G of the curve.
+secretOne, secretTwo, secretThree :: SecKey
+secretOne = "0000000000000000000000000000000000000000000000000000000000000001"
+secretTwo = "0000000000000000000000000000000000000000000000000000000000000002"
+secretThree = "0000000000000000000000000000000000000000000000000000000000000003"
+
+-- | The compressed public key of a secret key
+compressedKey :: SecKey -> PublicKey
+compressedKey secret = PublicKey (derivePubKey secret) True
+
+-- | The map of the input, or of the output, at the index
+inputAt, outputAt :: Int -> Psbt -> PsbtMap
+inputAt i psbt = psbt.inputs !! i
+outputAt i psbt = psbt.outputs !! i
+
+-- | A PSBT with the maps of its inputs replaced
+withInputs :: [PsbtMap] -> Psbt -> Psbt
+withInputs inputs psbt = Psbt psbt.version psbt.unsignedTx psbt.globals inputs psbt.outputs
+
+-- | The PSBT with the flags given in its global map
+withFlags :: Modifiable -> Psbt -> Psbt
+withFlags flags psbt = Psbt psbt.version psbt.unsignedTx (insertTxModifiable flags psbt.globals) psbt.inputs psbt.outputs
+
+spec :: Spec
+spec = do
+  vectors <- runIO (readTestFile "psbt_bip174.json" :: IO Vectors)
+  vectors370 <- runIO (readTestFile "psbt_bip370.json" :: IO Vectors370)
+  vectors371 <- runIO (readTestFile "psbt_bip371.json" :: IO Vectors371)
+  vectors373 <- runIO (readTestFile "psbt_bip373.json" :: IO Vectors371)
+  do
+    vectorsSpec vectors
+    vectors370Spec vectors370
+    rolesSpec vectors
+    version2Spec
+    bytesSpec vectors
+    fieldsSpec vectors
+    signingSpec
+    signerChecksSpec
+    signerScopeSpec
+    inputByInputSpec
+    coinsSpec
+    version2FieldsSpec
+    taprootChecksSpec vectors371
+    taprootCostSpec
+    decoderChecksSpec
+    taprootSpec vectors371
+    musig2Spec vectors373
+    complexSpec
+    core32Spec
+    coreSigningSpec
+    coreComplexSpec
+    propertiesSpec
+
+{- The vectors of BIP 370 -}
+
+-- The vectors of BIP 370 live in data/psbt_bip370.json: the invalid
+-- PSBTs, the valid ones, and the PSBTs of its lock time cases, each with
+-- the lock time the BIP computes, none when it cannot be computed
+data LockTimeVector = LockTimeVector
+  { ltCase :: String,
+    ltHex :: Text,
+    ltLockTime :: Maybe Word32
+  }
+
+instance Json.FromJSON LockTimeVector where
+  parseJSON = Json.withObject "vector" $ \o -> LockTimeVector <$> o .: "case" <*> o .: "hex" <*> o .:? "locktime"
+
+data Vectors370 = Vectors370
+  { refused :: [Vector],
+    accepted :: [Vector],
+    lockTimes :: [LockTimeVector]
+  }
+
+instance Json.FromJSON Vectors370 where
+  parseJSON = Json.withObject "vectors" $ \o -> Vectors370 <$> o .: "invalid" <*> o .: "valid" <*> o .: "locktime"
+
+-- | Why each invalid PSBT of BIP 370 is refused, in the order of the BIP:
+-- a field of the other version, a field version 2 requires missing, a
+-- lock time out of its range
+refusals370 :: [String]
+refusals370 =
+  [ "The global map: the key 0x00 is not of PSBT version 2",
+    "The global map: the key 0x02 is not of PSBT version 0",
+    "The global map: the key 0x03 is not of PSBT version 0",
+    "The global map: the key 0x04 is not of PSBT version 0",
+    "The global map: the key 0x05 is not of PSBT version 0",
+    "The global map: the key 0x06 is not of PSBT version 0",
+    "Input 0: the key 0x0e is not of PSBT version 0",
+    "Input 0: the key 0x0f is not of PSBT version 0",
+    "Input 0: the key 0x10 is not of PSBT version 0",
+    "Input 0: the key 0x11 is not of PSBT version 0",
+    "Input 0: the key 0x12 is not of PSBT version 0",
+    "Output 0: the key 0x03 is not of PSBT version 0",
+    "Output 0: the key 0x04 is not of PSBT version 0",
+    "The global map: the key 0x00 is not of PSBT version 2",
+    "The global map has no input count",
+    "The global map has no output count",
+    "The global map has no transaction version",
+    "Input 0 has no previous transaction id",
+    "Input 0 has no output index",
+    "Output 0 has no amount",
+    "Output 0 has no script",
+    "Input 0: the value of the key 0x11 is a time lock below 500000000",
+    "Input 0: the value of the key 0x12 is not a height between 1 and 499999999",
+    "Input 0: the value of the key 0x12 is not a height between 1 and 499999999"
+  ]
+
+vectors370Spec :: Vectors370 -> Spec
+vectors370Spec vectors = do
+  describe "The invalid PSBTs of BIP 370 are refused, each for its reason" $
+    forM_ (zip vectors.refused refusals370) $ \(v, reason) ->
+      it v.vecCase $ decodePsbt (bytesOf v) `shouldBe` Left reason
+
+  describe "The valid PSBTs of BIP 370 are read as version 2, and written back byte for byte" $
+    forM_ vectors.accepted $ \v ->
+      it v.vecCase $ do
+        psbt <- psbtOfVector v
+        psbt.version `shouldBe` Version2
+        encodePsbt psbt `shouldBe` bytesOf v
+
+  describe "The transaction of a PSBT of version 2 is the one its fields describe" $
+    -- The first valid PSBT of the BIP: one input, two outputs, nothing
+    -- else. Its input has no sequence field, so its sequence is final,
+    -- and no input requires a lock time, nor is a fallback given: lock
+    -- time 0.
+    it "for the first valid PSBT of the BIP, with a sequence and a lock time that no field gives" $ do
+      psbt <- psbtOfVector (vectors.accepted !! 0)
+      psbt.unsignedTx
+        `shouldBe` Tx
+          2
+          [TxIn (OutPoint "c85f81844094f9f0eec1e41f8d63e0a99e9f73dc725d7319871c9c4121d90a0b" 0) "" 0xffffffff]
+          [ TxOut 800000000 (hexBytes "0014c430f64c4756da310dbd1a085572ef299926272c"),
+            TxOut 199998859 (hexBytes "00144dd193ac964a56ac1b9e1cca8454fe2f474f8513")
+          ]
+          []
+          0
+
+  describe "The lock time of a PSBT of version 2 is the one BIP 370 determines" $
+    forM_ vectors.lockTimes $ \v ->
+      it v.ltCase $
+        ((.unsignedTx.locktime) <$> decodePsbt (hexBytes v.ltHex))
+          `shouldBe` maybe (Left "No lock time fits every input: some require a height, others a time") Right v.ltLockTime
+
+{- The vectors -}
+
+-- | Why each invalid PSBT of BIP 174 is refused, in the order of the BIP,
+-- as the start of the reason. The cases are: no magic bytes, a map
+-- missing, a script in the unsigned transaction, no unsigned transaction,
+-- a key twice, twelve keys whose data is not what their type takes, and
+-- an unsigned transaction that is not in the serialization without witness
+-- or not whole.
+refusals174 :: [String]
+refusals174 =
+  [ "Not a PSBT: the bytes do not start with the magic bytes of BIP 174",
+    "The PSBT ends inside output 0",
+    "The unsigned transaction has an input with a script",
+    "The global map has no unsigned transaction",
+    "Input 0 has the key 0x00 twice",
+    "The global map: the key 0x00 with the data 01 carries data",
+    "Input 0: the key 0x01 with the data 00 carries data",
+    "Input 0: the key 0x02 with the data 03b1341ccba7683b6af4f1238cd6e97e7167d569fac47f1e48d47541844355bd is not a public key",
+    "Input 0: the key 0x04 with the data 00 carries data",
+    "Input 0: the key 0x05 with the data 00 carries data",
+    "Input 0: the key 0x06 with the data 03b1341ccba7683b6af4f1238cd6e97e7167d569fac47f1e48d47541844355bd is not a public key",
+    "Input 0: the key 0x00 with the data 00 carries data",
+    "Input 0: the key 0x07 with the data 00 carries data",
+    "Input 1: the key 0x08 with the data 00 carries data",
+    "Output 0: the key 0x02 with the data 03a9a4c37f5996d3aa25dbac6b570af0650394492942460b354753ed9eeca587 is not a public key",
+    "Input 0: the key 0x03 with the data 00 carries data",
+    "Output 0: the key 0x00 with the data 00 carries data",
+    "Output 1: the key 0x01 with the data 0025512103b7ce23a01c5b4bf00a642537cdfabb315b668332867478ef51309d",
+    "The unsigned transaction does not decode",
+    "The unsigned transaction does not decode"
+  ]
+
+vectorsSpec :: Vectors -> Spec
+vectorsSpec vectors = do
+  describe "The invalid PSBTs of BIP 174 are refused, each for its reason" $
+    forM_ (zip vectors.invalid refusals174) $ \(v, reason) ->
+      it v.vecCase $ decodePsbt (bytesOf v) `shouldSatisfy` either (reason `isPrefixOf`) (const False)
+
+  describe "The valid PSBTs of BIP 174 are read, and written back byte for byte" $
+    forM_ vectors.valid $ \v ->
+      it v.vecCase $ (encodePsbt <$> decodePsbt (bytesOf v)) `shouldBe` Right (bytesOf v)
+
+  describe "The valid PSBTs of BIP 174 read the same from their base64 text" $
+    forM_ [(v, text) | v <- vectors.valid, Just text <- [v.vecBase64]] $ \(v, text) ->
+      it v.vecCase $ (encodePsbt <$> decodePsbtBase64 (encodeUtf8 text)) `shouldBe` Right (bytesOf v)
+
+  -- The combiner's PSBT of the two signed ones lists the signatures of
+  -- its second input out of order: see 'rolesSpec'
+  describe "The PSBTs of the roles of BIP 174 are read, and written back byte for byte" $
+    forM_ [v | v <- vectors.roles, v.vecCase /= (combiner vectors).vecCase] $ \v ->
+      it v.vecCase $ (encodePsbt <$> decodePsbt (bytesOf v)) `shouldBe` Right (bytesOf v)
+
+rolesSpec :: Vectors -> Spec
+rolesSpec vectors =
+  describe "The roles of BIP 174" $ do
+    it "the creator's PSBT is the unsigned transaction with empty maps" $ do
+      psbt <- psbtOfVector (creator vectors)
+      psbtOf psbt.unsignedTx `shouldBe` psbt
+
+    it "the transaction extractor gives the transaction of the finalizer's PSBT" $ do
+      psbt <- psbtOfVector (finalizer vectors)
+      (S.encode <$> psbtTransaction psbt) `shouldBe` Right (bytesOf (extracted vectors))
+
+    -- BIP 174: the extractor "checks whether all inputs have complete
+    -- scriptSigs and scriptWitnesses", and otherwise "must not modify the
+    -- PSBT". Bitcoin Core gives no transaction then (FinalizeAndExtractPSBT).
+    it "the transaction extractor refuses a PSBT with an input that is not final" $ do
+      psbt <- psbtOfVector (creator vectors)
+      psbtTransaction psbt `shouldBe` Left "Input 0 is not final"
+
+    it "the transaction of a PSBT that is still being signed has the final scripts of the inputs that have them" $ do
+      unsigned <- psbtOfVector (creator vectors)
+      psbtPartialTransaction unsigned `shouldBe` Right unsigned.unsignedTx
+      final <- psbtOfVector (finalizer vectors)
+      -- The second input loses its final script and witness
+      let halfFinal = withInputs [inputAt 0 final, Map.delete (Key 0x07 "") (Map.delete (Key 0x08 "") (inputAt 1 final))] final
+      psbtTransaction halfFinal `shouldBe` Left "Input 1 is not final"
+      (map (B.null . (.script)) . (.inputs) <$> psbtPartialTransaction halfFinal) `shouldBe` Right [False, True]
+      ((.witness) <$> psbtPartialTransaction halfFinal) `shouldBe` Right []
+
+    -- The updater's PSBT gives the coin of its second input, a P2SH-P2WSH
+    -- one, as a witness output only, as BIP 174 did before CVE-2020-14199
+    -- was known.
+    it "a signer that trusts witness outputs makes the first signer's PSBT of the BIP from the updater's, and the second signer's" $ do
+      psbt <- psbtOfVector (updaterWithSigHash vectors)
+      let master = fromJust (xPrvImport btcTest "tprv8ZgxMBicQKsPd9TeAdPADNnSyH9SSUUbTVeFszDE23Ki6TBB5nCefAdHkK8Fm3qMQR6sHwA56zqRmKmxnHk37JkiFzvncDqoKmPWubu7hDF")
+          trusting = (xPrvSigner master Nothing) {requirePreviousTx = False}
+          holding paths = trusting {keyOfRecord = \public derivation -> if derivation.path `elem` paths then trusting.keyOfRecord public derivation else Nothing}
+      (encodePsbt <$> signPsbt btcTest (holding ["m/0'/0'/0'", "m/0'/0'/2'"]) psbt) `shouldBe` Right (bytesOf (firstSigner vectors))
+      (encodePsbt <$> signPsbt btcTest (holding ["m/0'/0'/1'", "m/0'/0'/3'"]) psbt) `shouldBe` Right (bytesOf (secondSigner vectors))
+
+    -- The master key of the BIP holds the two keys of each input. Input 0
+    -- has its previous transaction. Input 1 is the P2SH-P2WSH coin known
+    -- from its witness output only.
+    it
+      "a signer that wants previous transactions signs the input \
+      \of the updater's PSBT that has one, and leaves the other"
+      $ do
+        psbt <- psbtOfVector (updaterWithSigHash vectors)
+        let master = fromJust (xPrvImport btcTest "tprv8ZgxMBicQKsPd9TeAdPADNnSyH9SSUUbTVeFszDE23Ki6TBB5nCefAdHkK8Fm3qMQR6sHwA56zqRmKmxnHk37JkiFzvncDqoKmPWubu7hDF")
+        signed <- expectRight (signPsbt btcTest (xPrvSigner master Nothing) psbt)
+        mapM (fmap length . partialSignatures) signed.inputs `shouldBe` Right [2, 0]
+        inputAt 1 signed `shouldBe` inputAt 1 psbt
+
+    -- The four cases the BIP lists under "Fails Signer checks", signed
+    -- with the master key of the BIP. The input at fault never gains a
+    -- signature. The numbers are the partial signatures of each input.
+    describe "a signer adds no signature to the input at fault of the PSBTs that fail the signer checks of the BIP" $ do
+      let master = fromJust (xPrvImport btcTest "tprv8ZgxMBicQKsPd9TeAdPADNnSyH9SSUUbTVeFszDE23Ki6TBB5nCefAdHkK8Fm3qMQR6sHwA56zqRmKmxnHk37JkiFzvncDqoKmPWubu7hDF")
+          trusting = (xPrvSigner master Nothing) {requirePreviousTx = False}
+          counts = mapM (fmap length . partialSignatures) . (.inputs)
+          failing i = psbtOfVector (vectors.valid !! i)
+      -- No record names a key, so the signer holds none: nothing is signed
+      it "a witness output for a legacy coin" $ do
+        psbt <- failing 10
+        counts psbt `shouldBe` Right [0, 0]
+        (counts =<< signPsbt btcTest trusting psbt) `shouldBe` Right [0, 0]
+      -- The redeem script of input 0 is no standard script, and does not
+      -- hash to the coin. Input 1 is sound and is signed.
+      it "a redeem script that does not match the coin, with the previous transaction" $ do
+        psbt <- failing 11
+        counts psbt `shouldBe` Right [1, 1]
+        (counts =<< signPsbt btcTest trusting psbt) `shouldBe` Right [1, 2]
+      -- The redeem script of input 1 does not hash to the coin. Input 0
+      -- is sound and is signed.
+      it "a redeem script that does not match the coin, with the witness output" $ do
+        psbt <- failing 12
+        counts psbt `shouldBe` Right [1, 1]
+        (counts =<< signPsbt btcTest trusting psbt) `shouldBe` Right [2, 1]
+      -- The witness script of input 1 is no standard script. Input 0 is
+      -- sound and is signed.
+      it "a witness script that does not match the redeem script" $ do
+        psbt <- failing 13
+        counts psbt `shouldBe` Right [1, 1]
+        (counts =<< signPsbt btcTest trusting psbt) `shouldBe` Right [2, 1]
+
+    -- The spec does not say in which order a combiner writes the keys of a
+    -- map. The BIP's combiner lists the two signatures of the second input
+    -- out of order; the keys of a map are written in order here, as
+    -- Bitcoin Core writes them. The PSBTs are the same, byte for byte once
+    -- the BIP's is written back.
+    it "the combiner's PSBT is that of the two signers combined, whatever the order of its inputs" $ do
+      a <- psbtOfVector (firstSigner vectors)
+      b <- psbtOfVector (secondSigner vectors)
+      both <- psbtOfVector (combiner vectors)
+      combinePsbt a b `shouldBe` Right both
+      combinePsbt b a `shouldBe` Right both
+      encodePsbt both `shouldNotBe` bytesOf (combiner vectors)
+      decodePsbt (encodePsbt both) `shouldBe` Right both
+
+    it "the two PSBTs with unknown keys combine as the combiner of the BIP that orders keys lexicographically does" $ do
+      a <- psbtOfVector (unknownA vectors)
+      b <- psbtOfVector (unknownB vectors)
+      (encodePsbt <$> combinePsbt a b) `shouldBe` Right (bytesOf (unknownCombined vectors))
+      (encodePsbt <$> combinePsbt b a) `shouldBe` Right (bytesOf (unknownCombined vectors))
+
+    it "the two PSBTs to combine give the combiner's PSBT" $ do
+      a <- psbtOfVector (toCombineA vectors)
+      b <- psbtOfVector (toCombineB vectors)
+      (encodePsbt <$> combinePsbt a b) `shouldBe` Right (bytesOf (combined vectors))
+
+    it "PSBTs of different transactions are not combined" $ do
+      a <- psbtOfVector (creator vectors)
+      combinePsbt a (psbtOf emptyTx) `shouldBe` Left "The PSBTs are not of the same transaction"
+
+    it "the updater's PSBT with SIGHASH_ALL is the updater's PSBT with the sighash type on every input" $ do
+      psbt <- psbtOfVector (updater vectors)
+      encodePsbt (withInputs (insertSigHashType sigHashAll <$> psbt.inputs) psbt) `shouldBe` bytesOf (updaterWithSigHash vectors)
+
+    it "the finalizer's PSBT is the combiner's PSBT finalized" $ do
+      psbt <- psbtOfVector (combiner vectors)
+      (encodePsbt <$> finalizePsbt btc psbt) `shouldBe` Right (bytesOf (finalizer vectors))
+
+    it "the finalizer leaves an input without enough signatures as it is" $ do
+      psbt <- psbtOfVector (firstSigner vectors)
+      finalizePsbt btc psbt `shouldBe` Right psbt
+
+{- The roles of version 2 -}
+
+-- | The input and output of the PSBTs below: the coin and the first output
+-- of the first valid PSBT of BIP 370, and another output of the same
+-- transaction as the coin
+coinInput, otherInput :: TxIn
+coinInput = TxIn (OutPoint "c85f81844094f9f0eec1e41f8d63e0a99e9f73dc725d7319871c9c4121d90a0b" 0) "" 0xfffffffd
+otherInput = TxIn (OutPoint "c85f81844094f9f0eec1e41f8d63e0a99e9f73dc725d7319871c9c4121d90a0b" 1) "" 0xfffffffd
+
+paidOutput :: TxOut
+paidOutput = TxOut 800000000 (hexBytes "0014c430f64c4756da310dbd1a085572ef299926272c")
+
+version2Spec :: Spec
+version2Spec =
+  describe "A PSBT of version 2" $ do
+    -- A creator of BIP 370 starts with no input and no output. The
+    -- created one, with its flags set so that inputs and outputs can be
+    -- added, and with the input and the output added.
+    let created = withVersion Version2 (psbtOf (Tx 2 [] [] [] 0))
+        modifiable = withFlags (Modifiable True True False 0) created
+        built = forceRight (addOutput paidOutput Map.empty =<< addInput coinInput Map.empty modifiable)
+        -- The same without its flags, as a constructor leaves it once
+        -- nothing is to be added
+        unflagged = Psbt Version2 built.unsignedTx (deleteTxModifiable built.globals) built.inputs built.outputs
+        requiring field value = addInput otherInput (field value Map.empty)
+
+    -- The fields of the global map: the transaction version 2, the
+    -- fallback lock time 0, the two counts of 0, and the PSBT version 2
+    it "is created with no input and no output, and the fields that describe its transaction" $
+      encodeHex (encodePsbt created) `shouldBe` "70736274ff0102040200000001030400000000010401000105010001fb040200000000"
+
+    it "takes no input or output unless its flags allow it" $ do
+      addInput coinInput Map.empty created `shouldBe` Left "The inputs of the PSBT may not be modified"
+      addOutput paidOutput Map.empty created `shouldBe` Left "The outputs of the PSBT may not be modified"
+
+    -- The input is described by the id of the transaction it spends from,
+    -- in the byte order of a transaction, the index of the output and its
+    -- sequence; the output by its amount and its script
+    it "takes an input and an output at the end, counted, described in their maps, and in its transaction" $ do
+      built.unsignedTx `shouldBe` Tx 2 [coinInput] [paidOutput] [] 0
+      Map.lookup (Key 0x04 "") built.globals `shouldBe` Just "\x01"
+      Map.lookup (Key 0x05 "") built.globals `shouldBe` Just "\x01"
+      inputAt 0 built
+        `shouldBe` Map.fromList
+          [ (Key 0x0e "", hexBytes "0b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8"),
+            (Key 0x0f "", hexBytes "00000000"),
+            (Key 0x10 "", hexBytes "fdffffff")
+          ]
+      outputAt 0 built `shouldBe` Map.fromList [(Key 0x03 "", hexBytes "0008af2f00000000"), (Key 0x04 "", hexBytes "0014c430f64c4756da310dbd1a085572ef299926272c")]
+
+    it "refuses an input that spends an output it spends already" $
+      addInput coinInput Map.empty built `shouldBe` Left "An input of the PSBT spends that output already"
+
+    it "is not of version 0, which takes no input or output" $
+      addInput coinInput Map.empty (psbtOf emptyTx) `shouldBe` Left "A PSBT of version 0 takes no input or output: its transaction is fixed"
+
+    it "takes the lock time its inputs require: the greatest height when every one that requires a lock time takes a height" $ do
+      withHeight <- expectRight (addInput coinInput (insertRequiredHeightLockTime 10000 Map.empty) modifiable)
+      withHeight.unsignedTx.locktime `shouldBe` 10000
+      ((.unsignedTx.locktime) <$> requiring insertRequiredHeightLockTime 9000 withHeight) `shouldBe` Right 10000
+      requiring insertRequiredTimeLockTime 1657048460 withHeight `shouldBe` Left "No lock time fits every input: some require a height, others a time"
+
+    -- The input of the PSBT has its final script
+    it "refuses an input that changes the lock time once an input is signed, and takes one that keeps it" $ do
+      let signed = withInputs [insertFinalScriptSig "\x00" (inputAt 0 built)] built
+      requiring insertRequiredHeightLockTime 10000 signed `shouldBe` Left "An input is signed already: the lock time may not change"
+      ((.unsignedTx.locktime) <$> addInput otherInput Map.empty signed) `shouldBe` Right 0
+
+    it "takes a sequence for an input, in its transaction and in its map, as an updater sets one" $ do
+      updated <- expectRight (setInputSequence 0 1 built)
+      map (.sequence) updated.unsignedTx.inputs `shouldBe` [1]
+      Map.lookup (Key 0x10 "") (inputAt 0 updated) `shouldBe` Just (hexBytes "01000000")
+      setInputSequence 1 1 built `shouldBe` Left "The PSBT has no input 1"
+      setInputSequence 0 1 (psbtOf emptyTx) `shouldBe` Left "The sequences of a PSBT of version 0 are in its unsigned transaction, which is fixed"
+      -- A signature commits to the sequence of its input
+      setInputSequence 0 1 (withInputs [insertFinalScriptSig "\x00" (inputAt 0 built)] built) `shouldBe` Left "Input 0 is signed already: its sequence may not change"
+
+    -- The id of its transaction with the sequence of its input at 0: the
+    -- same whatever the sequence. A PSBT of version 0 is identified by
+    -- its transaction as it is, with the sequence 0xfffffffd here.
+    it "is identified by its transaction with every sequence at 0" $ do
+      psbtId built `shouldBe` "79dd9a151a6cfc0dc3b7779a697817a80544e2c9dc0cfb399ecc7fa3b4da8f2c"
+      (psbtId <$> setInputSequence 0 1 built) `shouldBe` Right "79dd9a151a6cfc0dc3b7779a697817a80544e2c9dc0cfb399ecc7fa3b4da8f2c"
+      psbtId (withVersion Version0 built) `shouldBe` "7ca9f2c2ff60a7a3f7efdaa703bfb23b9415639e07b71e194bafb4d592e2c405"
+
+    it "combines with the same PSBT whose sequence an updater changed, and keeps the sequence of the first" $ do
+      updated <- expectRight (setInputSequence 0 1 built)
+      (map (.sequence) . (.unsignedTx.inputs) <$> combinePsbt built updated) `shouldBe` Right [0xfffffffd]
+      (map (.sequence) . (.unsignedTx.inputs) <$> combinePsbt updated built) `shouldBe` Right [1]
+
+    it "does not combine with a PSBT of version 0" $
+      combinePsbt built (withVersion Version0 built) `shouldBe` Left "The PSBTs are not of the same version"
+
+    -- The first lets inputs be added and has a SIGHASH_SINGLE signature;
+    -- the second lets inputs and outputs be added, with the undefined
+    -- bit 3 set
+    it "combines its flags as Bitcoin Core does: modifiable only when both say so, with a SIGHASH_SINGLE signature of either" $ do
+      (txModifiable . (.globals) <$> combinePsbt (withFlags (Modifiable True False True 0) built) (withFlags (Modifiable True True False 8) built))
+        `shouldBe` Right (Right (Just (Modifiable True False True 0)))
+      (txModifiable . (.globals) <$> combinePsbt unflagged (withFlags (Modifiable True False True 0) built))
+        `shouldBe` Right (Right (Just (Modifiable False False True 0)))
+
+    it "once signed, takes no more inputs unless the sighash has ANYONECANPAY, no more outputs unless it is NONE, and tells a SIGHASH_SINGLE signature" $ do
+      let open = withFlags (Modifiable True True False 0) built
+          flagsAfter sighash psbt = txModifiable (afterSignature sighash psbt).globals
+      flagsAfter sigHashAll open `shouldBe` Right (Just (Modifiable False False False 0))
+      flagsAfter (setAnyoneCanPay sigHashNone) open `shouldBe` Right (Just (Modifiable True True False 0))
+      flagsAfter sigHashSingle open `shouldBe` Right (Just (Modifiable False False True 0))
+      flagsAfter sigHashAll unflagged `shouldBe` Right Nothing
+      flagsAfter sigHashSingle unflagged `shouldBe` Right (Just (Modifiable False False True 0))
+
+    it "converted to version 0 is the PSBT of its transaction" $
+      withVersion Version0 built `shouldBe` psbtOf (Tx 2 [coinInput] [paidOutput] [] 0)
+
+{- Bytes -}
+
+-- | A transaction with nothing in it: version 0, no input, no output, lock
+-- time 0, which is "0000000000000000000000" over ten bytes
+emptyTx :: Tx
+emptyTx = Tx 0 [] [] [] 0
+
+-- | The global map of the PSBT of 'emptyTx': the key of the unsigned
+-- transaction, one byte of type 0x00, and the ten bytes of the transaction
+emptyTxEntry :: Text
+emptyTxEntry = "01000a00000000000000000000"
+
+bytesSpec :: Vectors -> Spec
+bytesSpec vectors =
+  describe "The bytes of a PSBT" $ do
+    -- The vector of the BIP for a transaction without inputs or outputs
+    it "are the magic bytes, the unsigned transaction, and a map for each input and output" $
+      encodePsbt (psbtOf emptyTx) `shouldBe` hexBytes ("70736274ff" <> emptyTxEntry <> "00")
+
+    -- The key is 7 bytes: the type 0xfc, the identifier "test" after its
+    -- length 4, and the subtype 0. The value is the 3 bytes of "btc".
+    it "write a key as its length, its type and its data, and its value after its length" $
+      encodePsbt (Psbt Version0 emptyTx (insertProprietary "test" 0 "btc" Map.empty) [] [])
+        `shouldBe` hexBytes ("70736274ff" <> emptyTxEntry <> "07fc047465737400" <> "03627463" <> "00")
+
+    it "write the keys of a map in order, the type first, whatever the order they were added" $ do
+      let globals = Map.fromList [(Key 0x20 "", hexBytes "bb"), (Key 0x10 (hexBytes "01"), hexBytes "aa")]
+      encodePsbt (Psbt Version0 emptyTx globals [] [])
+        `shouldBe` hexBytes ("70736274ff" <> emptyTxEntry <> "02100101aa" <> "012001bb" <> "00")
+
+    it "write the unsigned transaction without the input scripts and the witness of a signed one" $ do
+      signed <- expectRight $ S.decode (bytesOf (extracted vectors))
+      psbt <- psbtOfVector (finalizer vectors)
+      (psbtOf signed).unsignedTx `shouldBe` psbt.unsignedTx
+
+    it "tell a PSBT from other bytes by its first five" $ do
+      isPsbt (bytesOf (creator vectors)) `shouldBe` True
+      isPsbt "{\"tx\": \"0200\"}" `shouldBe` False
+
+    it "accept the unsigned transaction after another key of the global map" $
+      decodePsbt (hexBytes ("70736274ff" <> "012001bb" <> emptyTxEntry <> "00"))
+        `shouldBe` Right (Psbt Version0 emptyTx (Map.fromList [(Key 0x20 "", hexBytes "bb")]) [] [])
+
+    it "refuse what is not a PSBT" $
+      decodePsbt "{\"tx\": \"0200\"}" `shouldBe` Left "Not a PSBT: the bytes do not start with the magic bytes of BIP 174"
+
+    it "refuse a key twice in a map, naming it" $
+      decodePsbt (hexBytes ("70736274ff" <> emptyTxEntry <> "012001aa" <> "012001bb" <> "00"))
+        `shouldBe` Left "The global map has the key 0x20 twice"
+
+    it "refuse bytes after the last map" $
+      decodePsbt (bytesOf (creator vectors) <> "\0") `shouldBe` Left "Bytes follow the last map"
+
+    -- Version 1 was never defined
+    it "refuse a PSBT of a version other than 0 and 2" $
+      decodePsbt (hexBytes ("70736274ff" <> emptyTxEntry <> "01fb0401000000" <> "00"))
+        `shouldBe` Left "The PSBT is of version 1: only versions 0 and 2 are supported"
+
+    -- The length of the first key, 1, written over three bytes
+    it "refuse a length that is not in its shortest form" $
+      decodePsbt (hexBytes ("70736274ff" <> "fd0100" <> "000a00000000000000000000" <> "00"))
+        `shouldBe` Left "A length in the global map is not in its shortest form"
+
+    -- The PSBT with 0 inputs and 2 outputs of the BIP, without the two
+    -- bytes that end its output maps
+    it "refuse bytes that end inside a map" $ do
+      let withoutOutputs = bytesOf (vectors.valid !! 9)
+      decodePsbt (B.take (B.length withoutOutputs - 2) withoutOutputs) `shouldBe` Left "The PSBT ends inside output 0"
+
+    it "refuse a key of the spec that carries data it should not, naming it" $
+      decodePsbt (bytesOf (vectors.invalid !! 15)) `shouldBe` Left "Input 0: the key 0x03 with the data 00 carries data"
+
+    it "refuse a derivation key that is not a public key" $
+      decodePsbt (bytesOf (vectors.invalid !! 10)) `shouldSatisfy` either ("is not a public key" `isSuffixOf`) (const False)
+
+    it "read the base64 text of a PSBT, with spaces and line breaks around it" $ do
+      let v = vectors.valid !! 0
+      (encodePsbt <$> decodePsbtBase64 (" " <> encodeUtf8 (fromMaybe "" v.vecBase64) <> "\n")) `shouldBe` Right (bytesOf v)
+
+    it "write the base64 text the BIP gives" $ do
+      let v = vectors.valid !! 0
+      psbt <- psbtOfVector v
+      Just (encodePsbtBase64 psbt) `shouldBe` (encodeUtf8 <$> v.vecBase64)
+
+    it "refuse text that is not base64" $
+      decodePsbtBase64 "not base64!" `shouldBe` Left "Not the base64 text of a PSBT"
+
+{- Fields -}
+
+-- | The signature of the first signer of the BIP on the first input, as
+-- Bitcoin Core decodes its PSBT
+firstSignature :: Text
+firstSignature = "3044022074018ad4180097b873323c0015720b3684cc8123891048e7dbcd9b55ad679c99022073d369b740e3eb53dcefa33823c8070514ca55a7dd9544f157c167913261118c01"
+
+-- | The key of the first signer of the BIP, at m/0'/0'/0' of the master
+-- key d90c6a4f
+firstKey :: Text
+firstKey = "029583bf39ae0a609747ad199addd634fa6108559d6c5cd39b4c2183f1ab96e07f"
+
+-- The literal values below are those Bitcoin Core 25.0 shows for the
+-- vectors with decodepsbt.
+fieldsSpec :: Vectors -> Spec
+fieldsSpec vectors =
+  describe "The fields of a PSBT" $ do
+    let publicKey text = forceRight (decodeSerial (hexBytes text)) :: PublicKey
+        shown :: [(PublicKey, Derivation)] -> [(Text, Derivation)]
+        shown records = [(encodeHex (encodeSerial key), derivation) | (key, derivation) <- records]
+
+    it "read the derivation records of an input: the public key, the fingerprint of the master key and the path" $ do
+      psbt <- psbtOfVector (updater vectors)
+      records <- expectRight $ inputDerivations (inputAt 0 psbt)
+      shown records
+        `shouldBe` [ (firstKey, Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/0'"),
+                     ("02dab61ff49a14db6a7d02b0cd1fbb78fc4b18312b5b4e54dae4dba2fbfef536d7", Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/1'")
+                   ]
+
+    it "read the derivation records of an output" $ do
+      psbt <- psbtOfVector (updater vectors)
+      records <- expectRight $ outputDerivations (outputAt 0 psbt)
+      shown records `shouldBe` [("03a9a4c37f5996d3aa25dbac6b570af0650394492942460b354753ed9eeca58771", Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/4'")]
+
+    -- The path is 0' (0x80000000) three times, each over four bytes,
+    -- little-endian
+    it "write a derivation record as the public key under the type, and the fingerprint then the path, four bytes an index" $ do
+      let key = publicKey firstKey
+      Map.toList (insertInputDerivation key (Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/0'") Map.empty)
+        `shouldBe` [(Key 0x06 (hexBytes firstKey), hexBytes ("d90c6a4f" <> "00000080" <> "00000080" <> "00000080"))]
+      Map.keys (insertOutputDerivation key (Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/4'") Map.empty)
+        `shouldBe` [Key 0x02 (hexBytes firstKey)]
+
+    it "read the sighash type of an input, when it has one" $ do
+      with <- psbtOfVector (updaterWithSigHash vectors)
+      without <- psbtOfVector (updater vectors)
+      mapM sigHashType with.inputs `shouldBe` Right [Just sigHashAll, Just sigHashAll]
+      mapM sigHashType without.inputs `shouldBe` Right [Nothing, Nothing]
+
+    -- SIGHASH_ALL with the FORKID flag of Bitcoin Cash, 0x41
+    it "write the sighash type over four bytes, little-endian, and drop it as a finalizer does" $ do
+      Map.toList (insertSigHashType (setForkIdFlag sigHashAll) Map.empty) `shouldBe` [(Key 0x03 "", hexBytes "41000000")]
+      Map.keys (deleteSigHashType (insertSigHashType sigHashAll (insertNonWitnessUtxo emptyTx Map.empty))) `shouldBe` [Key 0x00 ""]
+
+    it "read the whole previous transaction of an input" $ do
+      psbt <- psbtOfVector (vectors.valid !! 0)
+      parent <- expectRight $ nonWitnessUtxo (inputAt 0 psbt)
+      (txHashToHex . txHash <$> parent) `shouldBe` Just "f61b1742ca13176464adb3cb66050c00787bb3a4eead37e985f2df1e37718126"
+
+    it "write a previous transaction under the type 0x00" $ do
+      psbt <- psbtOfVector (vectors.valid !! 0)
+      parent <- expectRight $ nonWitnessUtxo (inputAt 0 psbt)
+      Map.toList (insertNonWitnessUtxo emptyTx Map.empty) `shouldBe` [(Key 0x00 "", hexBytes "00000000000000000000")]
+      nonWitnessUtxo (maybe Map.empty (`insertNonWitnessUtxo` Map.empty) parent) `shouldBe` Right parent
+
+    -- The second input of the vector spends 1 BTC at a P2SH address
+    it "read the output an input spends when the PSBT has it alone, and write it under the type 0x01" $ do
+      psbt <- psbtOfVector (vectors.valid !! 1)
+      let coin = TxOut 100000000 (hexBytes "a9143545e6e33b832c47050f24d3eeb93c9c03948bc787")
+      mapM witnessUtxo psbt.inputs `shouldBe` Right [Nothing, Just coin]
+      Map.toList (insertWitnessUtxo coin Map.empty) `shouldBe` [(Key 0x01 "", hexBytes "00e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787")]
+
+    it "tell an input with partial signatures from one without" $ do
+      partial <- psbtOfVector (vectors.valid !! 4)
+      unsigned <- psbtOfVector (vectors.valid !! 0)
+      hasPartialSignatures (inputAt 0 partial) `shouldBe` True
+      hasPartialSignatures (inputAt 0 unsigned) `shouldBe` False
+
+    -- The first signer of the BIP signs the first input with SIGHASH_ALL,
+    -- the last byte 01 of the signature
+    it "read the partial signatures of an input: the public key, and the signature with its sighash byte" $ do
+      psbt <- psbtOfVector (firstSigner vectors)
+      records <- expectRight (partialSignatures (inputAt 0 psbt))
+      [(encodeHex (encodeSerial key), encodeHex signature) | (key, signature) <- records] `shouldBe` [(firstKey, firstSignature)]
+
+    it "write a partial signature under the type 0x02 with the public key, and drop them all as a finalizer does" $ do
+      let m = insertPartialSignature (publicKey firstKey) (hexBytes firstSignature) (insertSigHashType sigHashAll Map.empty)
+      Map.toList m `shouldBe` [(Key 0x02 (hexBytes firstKey), hexBytes firstSignature), (Key 0x03 "", hexBytes "01000000")]
+      Map.toList (deletePartialSignatures m) `shouldBe` [(Key 0x03 "", hexBytes "01000000")]
+
+    -- The second input of the updater's PSBT spends a P2SH-P2WSH coin: a
+    -- 2-of-2 multisig behind a witness program
+    it "read the redeem script and the witness script of an input, and write them under the types 0x04 and 0x05" $ do
+      psbt <- psbtOfVector (updater vectors)
+      let redeem = Script [OP_0, opPushData (hexBytes "8c2353173743b595dfb4a07b72ba8e42e3797da74e87fe7d9d7497e3b2028903")]
+          witness = Script [OP_2, opPushData (hexBytes "03089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc"), opPushData (hexBytes "023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e73"), OP_2, OP_CHECKMULTISIG]
+      inputRedeemScript (inputAt 1 psbt) `shouldBe` Right (Just redeem)
+      inputWitnessScript (inputAt 1 psbt) `shouldBe` Right (Just witness)
+      inputRedeemScript (inputAt 0 psbt) `shouldSatisfy` (\found -> fmap (const ()) found == Right () && found /= Right Nothing)
+      Map.toList (insertInputRedeemScript redeem (insertInputWitnessScript witness Map.empty))
+        `shouldBe` [ (Key 0x04 "", hexBytes "00208c2353173743b595dfb4a07b72ba8e42e3797da74e87fe7d9d7497e3b2028903"),
+                     (Key 0x05 "", hexBytes "522103089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc21023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e7352ae")
+                   ]
+
+    it "read the redeem script and the witness script of an output, and write them under the types 0x00 and 0x01" $ do
+      let redeem = Script [OP_0, opPushData (hexBytes "8c2353173743b595dfb4a07b72ba8e42e3797da74e87fe7d9d7497e3b2028903")]
+          witness = Script [OP_1, OP_CHECKMULTISIG]
+          m = insertOutputRedeemScript redeem (insertOutputWitnessScript witness Map.empty)
+      Map.keys m `shouldBe` [Key 0x00 "", Key 0x01 ""]
+      outputRedeemScript m `shouldBe` Right (Just redeem)
+      outputWitnessScript m `shouldBe` Right (Just witness)
+      outputWitnessScript Map.empty `shouldBe` Right Nothing
+
+    it "read the final script and witness of a signed input" $ do
+      psbt <- psbtOfVector (finalizer vectors)
+      let first' = inputAt 0 psbt
+          second = inputAt 1 psbt
+      finalScriptSig first'
+        `shouldBe` Just (hexBytes "00473044022074018ad4180097b873323c0015720b3684cc8123891048e7dbcd9b55ad679c99022073d369b740e3eb53dcefa33823c8070514ca55a7dd9544f157c167913261118c01483045022100f61038b308dc1da865a34852746f015772934208c6d24454393cd99bdf2217770220056e675a675a6d0a02b85b14e5e29074d8a25a9b5760bea2816f661910a006ea01475221029583bf39ae0a609747ad199addd634fa6108559d6c5cd39b4c2183f1ab96e07f2102dab61ff49a14db6a7d02b0cd1fbb78fc4b18312b5b4e54dae4dba2fbfef536d752ae")
+      finalScriptWitness first' `shouldBe` Right Nothing
+      finalScriptSig second `shouldBe` Just (hexBytes "2200208c2353173743b595dfb4a07b72ba8e42e3797da74e87fe7d9d7497e3b2028903")
+      finalScriptWitness second
+        `shouldBe` Right
+          ( Just
+              [ "",
+                hexBytes "3044022062eb7a556107a7c73f45ac4ab5a1dddf6f7075fb1275969a7f383efff784bcb202200c05dbb7470dbf2f08557dd356c7325c1ed30913e996cd3840945db12228da5f01",
+                hexBytes "3044022065f45ba5998b59a27ffe1a7bed016af1f1f90d54b3aa8f7450aa5f56a25103bd02207f724703ad1edb96680b284b56d4ffcb88f7fb759eabbe08aa30f29b851383d201",
+                hexBytes "522103089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc21023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e7352ae"
+              ]
+          )
+
+    it "write a final script under the type 0x07, and a final witness as the number of its items then each after its length" $ do
+      Map.toList (insertFinalScriptSig (hexBytes "aabb") Map.empty) `shouldBe` [(Key 0x07 "", hexBytes "aabb")]
+      Map.toList (insertFinalScriptWitness [hexBytes "aabb", ""] Map.empty) `shouldBe` [(Key 0x08 "", hexBytes "0202aabb00")]
+
+    it "read the extended public keys of the global map, with their derivations, and write them under the type 0x01" $ do
+      psbt <- psbtOfVector (vectors.valid !! 7)
+      let xpub = fromJust $ xPubImport btc "xpub6CpGH79LXVkeiux2ZPWMpEubBrRfgcGCgy2HiagyN6NW3qdioJaqFYyD1fG6LDfxWEhMXJqcDuU5VneKt5UQYUGPa5Mfxdw2D2NArwX5TBm"
+          record = (xpub, Derivation (fingerprintOf "27569c50") "m/49'/0'/0'")
+      xpubRecords btc psbt.globals `shouldBe` Right [record]
+      let m = insertXpubRecord btc xpub (snd record) Map.empty
+      Map.keys m `shouldBe` [Key 0x01 (marshal btc xpub)]
+      xpubRecords btc m `shouldBe` Right [record]
+
+    -- The two keys of the vector are of the test network
+    it "leave aside the extended public keys of another network" $ do
+      psbt <- psbtOfVector (vectors.valid !! 5)
+      let tpub text = fromJust $ xPubImport btcTest text
+      xpubRecords btc psbt.globals `shouldBe` Right []
+      xpubRecords btcTest psbt.globals
+        `shouldBe` Right
+          [ (tpub "tpubDBkJeJo2X94Yq3RVz65DoUgyLUkaDrkfyrn2VcgyCRSKCRonvKvCF2FpYDGJWDkdRHBajXJGpc63GnumUt63ySvqCu2XaTRGVTKMYGuFk9H", Derivation (fingerprintOf "d90c6a4f") "m/174'/0'"),
+            (tpub "tpubDBkJeJo2X94YsvtBEU1eKoibEWiNv51nW5iHhs6VZp59jsE6nen8KZMFyGHuGbCvqjRqirgeMcfpVBkttpUUT6brm4duzSGoZeTbhqCNUu6", Derivation (fingerprintOf "d90c6a4f") "m/174'/1'")
+          ]
+
+    it "write a proprietary key as the type 0xfc, the identifier after its length, the subtype and the data" $ do
+      proprietaryKey (Proprietary "test" 1 (hexBytes "ab")) `shouldBe` Key 0xfc (hexBytes "047465737401ab")
+      proprietaryOf (Key 0xfc (hexBytes "047465737401ab")) `shouldBe` Right (Just (Proprietary "test" 1 (hexBytes "ab")))
+      proprietaryOf (Key 0x20 "") `shouldBe` Right Nothing
+      proprietaryOf (Key 0xfc "") `shouldBe` Left "the proprietary key 0xfc has no identifier and subtype"
+
+    it "look a proprietary field up by its identifier and subtype" $ do
+      let m = insertProprietary "test" 3 "Rent" Map.empty
+      lookupProprietary "test" 3 m `shouldBe` Just "Rent"
+      lookupProprietary "test" 2 m `shouldBe` Nothing
+      lookupProprietary "other" 3 m `shouldBe` Nothing
+
+{- Signing and finalizing -}
+
+-- | A coin of 2 BTC at the script, spent whole by a transaction paying
+-- two outputs, as a PSBT with the coin on its input: the whole previous
+-- transaction, or the output alone for a Taproot coin, whose signature
+-- commits to the output of every input (BIP 341)
+spendingPsbt :: ScriptOutput -> (Psbt, [(ScriptOutput, Word64, OutPoint)])
+spendingPsbt coinScript = (Psbt Version0 tx Map.empty [input] [Map.empty, Map.empty], [(coinScript, 200000000, outpoint)])
+  where
+    parent = Tx 1 [TxIn (OutPoint "e567952fb6cc33857f392efa3a46c995a28f69cca4bb1b37e0204dab1ec7a389" 1) "" 0xffffffff] [TxOut 200000000 (encodeSerial coinScript)] [] 0
+    outpoint = OutPoint (txHash parent) 0
+    tx =
+      Tx
+        2
+        [TxIn outpoint "" 0xfffffffe]
+        [ TxOut 99999699 (hexBytes "76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac"),
+          TxOut 100000000 (hexBytes "a9143545e6e33b832c47050f24d3eeb93c9c03948bc787")
+        ]
+        []
+        1257139
+    input = case coinScript of
+      PayWitness 1 _ -> insertWitnessUtxo (TxOut 200000000 (encodeSerial coinScript)) Map.empty
+      _ -> insertNonWitnessUtxo parent Map.empty
+
+-- | A derivation record of a key, which a signer needs: the fingerprint
+-- and the path are those of the BIP's first signer
+recordOf :: PublicKey -> PsbtMap -> PsbtMap
+recordOf public = insertInputDerivation public (Derivation (fingerprintOf "d90c6a4f") "m/0'/0'/0'")
+
+-- | A signer holding the keys
+keysSigner :: [PrivateKey] -> Signer
+keysSigner keys =
+  Signer
+    { keyOfRecord = \public derivation -> listToMaybe (mapMaybe (\key -> (keySigner key.key).keyOfRecord public derivation) keys),
+      keyOfHash = \h -> listToMaybe (mapMaybe (\key -> (keySigner key.key).keyOfHash h) keys),
+      acceptedSigHashes = defaultSigHashes,
+      requirePreviousTx = True
+    }
+
+-- | Whether the transaction of the PSBT, once signed with the keys and
+-- finalized, verifies against the coins it spends
+signsAndVerifies :: Network -> [PrivateKey] -> (Psbt, [(ScriptOutput, Word64, OutPoint)]) -> Either String Bool
+signsAndVerifies net keys (psbt, coins) = do
+  signed <- signPsbt net (keysSigner keys) psbt
+  final <- finalizePsbt net signed
+  tx <- psbtTransaction final
+  return (verifyStdTx net tx coins)
+
+signingSpec :: Spec
+signingSpec =
+  describe "Signing and finalizing" $ do
+    prop "a P2PKH coin, signed with the key of its address and finalized, verifies" $
+      forAll arbitraryKeyPair $ \(secret, public) ->
+        let (psbt, coins) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))
+            withRecord = withInputs (recordOf public <$> psbt.inputs) psbt
+         in signsAndVerifies btc [secret] (withRecord, coins) === Right True
+
+    -- The finalized input keeps its coin, its final script, and the
+    -- fields of version 2: the transaction it spends from, the output
+    -- index and the sequence
+    prop "a P2PKH coin of a PSBT of version 2, signed and finalized, verifies, and the PSBT stays of version 2 with the fields of its input" $
+      forAll arbitraryKeyPair $ \(secret, public) ->
+        let (psbt, coins) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))
+            version2 = withVersion Version2 (withInputs (recordOf public <$> psbt.inputs) psbt)
+            final = finalizePsbt btc =<< signPsbt btc (keysSigner [secret]) version2
+         in (signsAndVerifies btc [secret] (version2, coins), (.version) <$> final, Map.keys . inputAt 0 <$> final)
+              === (Right True, Right Version2, Right [Key 0x00 "", Key 0x07 "", Key 0x0e "", Key 0x0f "", Key 0x10 ""])
+
+    prop "a P2SH multisig coin, signed with enough of its keys and finalized, verifies" $
+      -- At most 7 keys: the redeem script of more uncompressed keys would be
+      -- over the 520 bytes a P2SH redeem script can have
+      forAll ((,) <$> arbitraryP2SHMSParam <*> arbitraryKeyPair) $ \((m, n), _) ->
+        forAll (vectorOf n arbitraryKeyPair) $ \pairs ->
+          let redeem = either error id $ encodeOutput (PayMulSig (snd <$> pairs) m)
+              (psbt, coins) = spendingPsbt (either error id (toP2SH redeem))
+              withFields = withInputs ((insertInputRedeemScript redeem . foldr (\(_, public) f -> recordOf public . f) id pairs) <$> psbt.inputs) psbt
+           in signsAndVerifies btc (fst <$> take m pairs) (withFields, coins) === Right True
+
+    -- The keys are compressed: a SegWit version 0 coin is not signed with
+    -- an uncompressed key, which 'signerScopeSpec' tests
+    prop "a P2WPKH coin, and a P2SH-P2WPKH one with its redeem script, signed and finalized, verify" $
+      forAll arbitraryKeyPairC $ \(secret, public) ->
+        let program = PayWitnessPKHash (addressHash (encodeSerial public))
+            (native, nativeCoins) = spendingPsbt program
+            redeem = either error id $ encodeOutput program
+            (nested, nestedCoins) = spendingPsbt (either error id (toP2SH redeem))
+            nativeWithRecord = withInputs (recordOf public <$> native.inputs) native
+            nestedWithFields = withInputs ((insertInputRedeemScript redeem . recordOf public) <$> nested.inputs) nested
+         in signsAndVerifies btc [secret] (nativeWithRecord, nativeCoins) === Right True
+              .&&. signsAndVerifies btc [secret] (nestedWithFields, nestedCoins) === Right True
+
+    prop "a P2WSH multisig coin with its witness script, nested in P2SH or not, signed and finalized, verifies" $
+      forAll arbitraryMSParam $ \(m, n) ->
+        forAll (vectorOf n arbitraryKeyPairC) $ \pairs ->
+          let witness = either error id $ encodeOutput (PayMulSig (snd <$> pairs) m)
+              program = either error id (toP2WSH witness)
+              records = foldr (\(_, public) f -> recordOf public . f) id pairs
+              (native, nativeCoins) = spendingPsbt program
+              (nested, nestedCoins) = spendingPsbt (either error id (toP2SH programScript))
+              nativeWithFields = withInputs ((insertInputWitnessScript witness . records) <$> native.inputs) native
+              nestedWithFields = withInputs ((insertInputRedeemScript programScript . insertInputWitnessScript witness . records) <$> nested.inputs) nested
+              programScript = either error id $ encodeOutput program
+           in signsAndVerifies btc (fst <$> take m pairs) (nativeWithFields, nativeCoins) === Right True
+                .&&. signsAndVerifies btc (fst <$> take m pairs) (nestedWithFields, nestedCoins) === Right True
+
+    it "signs with the sighash the input asks for when the signer accepts it, SIGHASH_ALL when it asks for none" $ do
+      let secret = PrivateKey secretOne True
+          public = derivePublicKey secret
+          (psbt, _) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))
+          asking sh = withInputs ((recordOf public . maybe id insertSigHashType sh) <$> psbt.inputs) psbt
+          sighashOf signed = map (B.last . snd) <$> partialSignatures (inputAt 0 signed)
+          acceptingNone = (keySigner secret.key) {acceptedSigHashes = sigHashNone : defaultSigHashes}
+      (sighashOf =<< signPsbt btc (keySigner secret.key) (asking Nothing)) `shouldBe` Right [0x01]
+      (sighashOf =<< signPsbt btc (keySigner secret.key) (asking (Just sigHashAll))) `shouldBe` Right [0x01]
+      -- SIGHASH_NONE leaves the outputs unsigned, so the signer must agree to it
+      signPsbt btc (keySigner secret.key) (asking (Just sigHashNone)) `shouldBe` Left "Input 0: the sighash type 2 is not one the signer accepts"
+      (sighashOf =<< signPsbt btc acceptingNone (asking (Just sigHashNone))) `shouldBe` Right [0x02]
+
+    it "leaves an input without its coin, or signed already, as it is" $ do
+      let secret = PrivateKey secretOne True
+          public = derivePublicKey secret
+          (psbt, _) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))
+          withoutCoin = withInputs [recordOf public Map.empty] psbt
+          final = withInputs ((insertFinalScriptSig "a script" . recordOf public) <$> psbt.inputs) psbt
+      signPsbt btc (keySigner secret.key) withoutCoin `shouldBe` Right withoutCoin
+      signPsbt btc (keySigner secret.key) final `shouldBe` Right final
+
+    it "refuses a previous transaction that is not the one the input spends" $ do
+      let public = compressedKey secretOne
+          (psbt, _) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))
+          wrong = withInputs [insertNonWitnessUtxo emptyTx Map.empty] psbt
+      signPsbt btc (Signer (\_ _ -> Nothing) (const Nothing) defaultSigHashes True) wrong `shouldBe` Left "Input 0: the previous transaction is not the one the input spends"
+
+    -- The derivation records name keys by the master key, b4a6ba67 with
+    -- the full path, or by the extended key given, with the path from it
+    it "finds the key an extended private key derives, by its own fingerprint or by the origin given" $ do
+      let root = makeXPrvKey "PSBT signer test"
+          rootFingerprint = xPubFP (deriveXPubKey root)
+          account = derivePath (Deriv :| 444 :: HardPath) root
+          accountFingerprint = xPubFP (deriveXPubKey account)
+          secretAt path = (derivePath (path :: DerivPath) root).key
+          publicOf secret = PublicKey (derivePubKey secret) True
+          signer = xPrvSigner account (Just (Derivation rootFingerprint "m/444'"))
+          unknownOrigin = xPrvSigner account Nothing
+      signer.keyOfRecord (publicOf (secretAt "m/444'/0")) (Derivation rootFingerprint "m/444'/0") `shouldBe` Just (secretAt "m/444'/0")
+      signer.keyOfRecord (publicOf (secretAt "m/444'/1")) (Derivation accountFingerprint "m/1") `shouldBe` Just (secretAt "m/444'/1")
+      signer.keyOfRecord (publicOf (secretAt "m/444'/1")) (Derivation rootFingerprint "m/445'/1") `shouldBe` Nothing
+      signer.keyOfRecord (publicOf (secretAt "m/444'/1")) (Derivation accountFingerprint "m/2") `shouldBe` Nothing
+      unknownOrigin.keyOfRecord (publicOf (secretAt "m/444'/0")) (Derivation rootFingerprint "m/444'/0") `shouldBe` Nothing
+      unknownOrigin.keyOfRecord (publicOf (secretAt "m/444'/0")) (Derivation accountFingerprint "m/0") `shouldBe` Just (secretAt "m/444'/0")
+      -- An extended key cannot know which path a hash is at
+      signer.keyOfHash (addressHash (encodeSerial (publicOf (secretAt "m/444'/0")))) `shouldBe` Nothing
+
+{- A PSBT of every kind of coin -}
+
+-- | The PSBTs of a transaction of nine coins of every kind, signed by
+-- twelve wallets of Bitcoin Core one at a time, their combination, its
+-- finalization and the transaction it gives: read from a file of the
+-- repository, or made by a node of Bitcoin Core as the tests run
+-- ('coreComplexSpec')
+data Complex = Complex
+  { initialPsbt :: Psbt,
+    signedPsbts :: [Psbt],
+    combinedPsbt :: Psbt,
+    completePsbt :: Psbt,
+    finalTx :: Tx
+  }
+
+instance Json.FromJSON Complex where
+  parseJSON = Json.withObject "complex" $ \o ->
+    Complex
+      <$> psbtAt o "initial_psbt"
+      <*> mapM (psbtAt o) ["miner_psbt", "p2pkh_psbt", "p2sh_ms_1_psbt", "p2sh_ms_2_psbt", "p2sh_pk_psbt", "p2sh_wsh_pk_psbt", "p2sh_wsh_ms_1_psbt", "p2sh_wsh_ms_2_psbt", "p2wpkh_psbt", "p2wsh_pk_psbt", "p2wsh_ms_1_psbt", "p2wsh_ms_2_psbt"]
+      <*> psbtAt o "combined_psbt"
+      <*> psbtAt o "complete_psbt"
+      <*> (either fail return . S.decode . hexBytes =<< o .: "final_tx")
+    where
+      psbtAt o name = either fail return . decodePsbtBase64 . encodeUtf8 =<< o .: name
+
+complexSpec :: Spec
+complexSpec = do
+  -- data/complex_psbt.json is the file of an older Bitcoin Core, in
+  -- version 0. Each wallet finalized the coins it could complete alone.
+  describe "The PSBT of nine coins of every kind, which twelve wallets of Bitcoin Core signed one at a time" $ do
+    complex <- runIO (readTestFile "complex_psbt.json" :: IO Complex)
+    before (return complex) complexChecks
+
+  -- data/psbt_complex_core32.json is the file of Bitcoin Core 32.1, in
+  -- version 2. The wallets signed with finalize=false, so that the
+  -- combination holds partial signatures only.
+  describe "The PSBT of nine coins of every kind, which twelve wallets of Bitcoin Core 32.1 signed without finalizing" $ do
+    complex <- runIO (readTestFile "psbt_complex_core32.json" :: IO Complex)
+    before (return complex) $ do
+      version2Combination
+      complexChecks
+
+-- | The combination of PSBTs that Bitcoin Core 32.1 signed without
+-- finalizing them
+version2Combination :: SpecWith Complex
+version2Combination =
+  it "is a version 2 PSBT whose combination has no final input" $ \complex -> do
+    complex.combinedPsbt.version `shouldBe` Version2
+    length complex.combinedPsbt.inputs `shouldBe` 9
+    -- Types 0x07 and 0x08 are the final script and the final witness
+    length [key | input <- complex.combinedPsbt.inputs, key <- Map.keys input, key.keyType `elem` [0x07, 0x08]]
+      `shouldBe` 0
+
+-- | What holds for both files, and for what a node makes as the tests run:
+-- the library combines, finalizes and extracts what Bitcoin Core combined,
+-- finalized and extracted
+complexChecks :: SpecWith Complex
+complexChecks = do
+  -- The PSBT Core created has no entry that a signed one lacks
+  it "adds nothing to a signed PSBT when the PSBT Core created is combined with it" $ \complex ->
+    mapM (combinePsbt complex.initialPsbt) complex.signedPsbts `shouldBe` Right complex.signedPsbts
+
+  it "combines into the PSBT Core combined" $ \complex ->
+    case complex.signedPsbts of
+      first' : rest -> foldM combinePsbt first' rest `shouldBe` Right complex.combinedPsbt
+      [] -> expectationFailure "No signed PSBT"
+
+  it "finalizes into the PSBT Core finalized" $ \complex ->
+    finalizePsbt btc complex.combinedPsbt `shouldBe` Right complex.completePsbt
+
+  it "gives the transaction Core extracted" $ \complex ->
+    psbtTransaction complex.completePsbt `shouldBe` Right complex.finalTx
+
+{- Against a node of Bitcoin Core -}
+
+-- | A key of the tests against Bitcoin Core, made from a label, with its
+-- public key in hexadecimal and its private key in the wallet import format
+-- of regtest, as descriptors write them
+data TestKey = TestKey
+  { private :: PrivateKey,
+    publicHex :: Text,
+    wif :: Text
+  }
+
+testKey :: ByteString -> TestKey
+testKey label =
+  TestKey
+    { private = private,
+      publicHex = encodeHex (encodeSerial (derivePublicKey private)),
+      wif = toWif btcRegTest private
+    }
+  where
+    -- A seed has 16 bytes at least
+    private = wrapSecKey True (makeXPrvKey ("Key of the tests against Bitcoin Core: " <> label)).key
+
+-- | The library signs the PSBTs that Bitcoin Core makes for coins of every
+-- kind that both sign, and Bitcoin Core finalizes them and accepts their
+-- transactions into its mempool. The library finalizes each into the same
+-- transaction. Two of the three keys of a multisig coin sign apart, and
+-- Bitcoin Core combines what they signed.
+coreSigningSpec :: Spec
+coreSigningSpec =
+  describe ("Bitcoin Core " <> coreVersion <> " accepts the transactions of its PSBTs that the library signs") $
+    aroundNode withMiner $
+      forM_ kinds $ \(name, descriptor, signers) ->
+        it ("for a coin of " <> T.unpack name) $ \node -> signedByLibrary node name descriptor signers
+  where
+    k1 = testKey "PSBT key 1"
+    k2 = testKey "PSBT key 2"
+    k3 = testKey "PSBT key 3"
+    single = k1.publicHex
+    multi = "sortedmulti(2," <> T.intercalate "," [k1.publicHex, k2.publicHex, k3.publicHex] <> ")"
+    kinds =
+      [ ("p2pkh", "pkh(" <> single <> ")", [k1]),
+        ("p2sh-pk", "sh(pk(" <> single <> "))", [k1]),
+        ("p2sh-ms", "sh(" <> multi <> ")", [k1, k2]),
+        ("p2sh-wpkh", "sh(wpkh(" <> single <> "))", [k1]),
+        ("p2sh-wsh-ms", "sh(wsh(" <> multi <> "))", [k1, k2]),
+        ("p2wpkh", "wpkh(" <> single <> ")", [k1]),
+        ("p2wsh-ms", "wsh(" <> multi <> ")", [k1, k2])
+      ]
+    -- The miner has the coinbases of a hundred blocks to spend
+    withMiner node = do
+      _ <- rpc node "createwallet" [Json.String "miner"]
+      mine node 200
+      return node
+
+-- | The miner pays a coin to a descriptor. A wallet that watches the
+-- descriptor, without its keys, makes a PSBT that spends the coin. The
+-- library signs it with each key, and Bitcoin Core combines and finalizes
+-- the result, and accepts its transaction.
+signedByLibrary :: Node -> Text -> Text -> [TestKey] -> Expectation
+signedByLibrary node name descriptor keys = do
+  -- walletcreatefundedpsbt takes the lock time before the options
+  let lockTime = Json.toJSON (0 :: Int)
+  public <- textAt "descriptor" =<< rpc node "getdescriptorinfo" [Json.String descriptor]
+  address <- firstText =<< rpc node "deriveaddresses" [Json.String public]
+  -- The coin is output 0 of the funding transaction
+  funding <-
+    textAt "psbt"
+      =<< walletRpc
+        node
+        "miner"
+        "walletcreatefundedpsbt"
+        [ emptyArray,
+          Json.object [Key.fromText address .= (1 :: Int)],
+          lockTime,
+          Json.object ["changePosition" .= (1 :: Int)]
+        ]
+  fundingSigned <- textAt "psbt" =<< walletRpc node "miner" "walletprocesspsbt" [Json.String funding]
+  fundingTx <- textAt "hex" =<< rpc node "finalizepsbt" [Json.String fundingSigned]
+  fundingTxid <- rpc node "sendrawtransaction" [Json.String fundingTx]
+
+  let watcher = "watch-" <> name
+  _ <- rpc node "createwallet" [Json.String watcher, Json.Bool True]
+  importDescriptor node watcher public
+  mine node 10
+  payee <- text =<< walletRpc node "miner" "getnewaddress" []
+  change <- walletRpc node "miner" "getnewaddress" []
+  -- The watcher has no address of its own, so the miner gets the change
+  unsigned <-
+    textAt "psbt"
+      =<< walletRpc
+        node
+        watcher
+        "walletcreatefundedpsbt"
+        [ Json.toJSON [Json.object ["txid" .= fundingTxid, "vout" .= (0 :: Int)]],
+          Json.object [Key.fromText payee .= (0.8 :: Double)],
+          lockTime,
+          Json.object ["changeAddress" .= change]
+        ]
+
+  psbt <- fromBase64 unsigned
+  signed <- mapM (\k -> either fail return (signPsbt btcRegTest (keySigner k.private.key) psbt)) keys
+  combined <- case signed of
+    [one] -> return one
+    _ -> fromBase64 =<< text =<< rpc node "combinepsbt" [Json.toJSON (map toBase64 signed)]
+  finalized <- rpc node "finalizepsbt" [Json.String (toBase64 combined)]
+  at "complete" finalized `shouldReturn` Json.Bool True
+  tx <- either fail return . S.decode . hexBytes =<< textAt "hex" finalized
+  (psbtTransaction =<< finalizePsbt btcRegTest combined) `shouldBe` Right tx
+  rpc node "sendrawtransaction" [Json.String (encodeHex (S.encode tx))]
+    `shouldReturn` Json.String (txHashToHex (txHash tx))
+
+-- | 'complexChecks' on PSBTs that a node of Bitcoin Core makes and signs as
+-- the tests run, as it made data/psbt_complex_core32.json. Set the variable
+-- @HASKOIN_COMPLEX_PSBT@ to the path of a file to keep them there, in the
+-- form of that file.
+coreComplexSpec :: Spec
+coreComplexSpec =
+  describe
+    ( "The PSBT of nine coins of every kind, which twelve wallets of Bitcoin Core "
+        <> coreVersion
+        <> " sign as the tests run"
+    )
+    $ aroundNode complexOfNode
+    $ do
+      version2Combination
+      complexChecks
+
+-- | Eight coins, one of each kind and each in wallets of its own, and the
+-- change of the miner that paid them: a PSBT spends all nine, each wallet
+-- signs it without finalizing, and Bitcoin Core combines, finalizes and
+-- extracts. The transaction pays almost all of the change in fees, which
+-- does not matter, since it is never sent.
+complexOfNode :: Node -> IO Complex
+complexOfNode node = do
+  _ <- rpc node "createwallet" [Json.String "miner"]
+  miner <- text =<< walletRpc node "miner" "getnewaddress" []
+  mine node 101
+  singles <-
+    mapM
+      single
+      [ ("p2pkh", \k -> "pkh(" <> k <> ")"),
+        ("p2sh_pk", \k -> "sh(pk(" <> k <> "))"),
+        ("p2sh_wsh_pk", \k -> "sh(wsh(pk(" <> k <> ")))"),
+        ("p2wpkh", \k -> "wpkh(" <> k <> ")"),
+        ("p2wsh_pk", \k -> "wsh(pk(" <> k <> "))")
+      ]
+  multis <-
+    mapM
+      multi
+      [ ("p2sh_ms", \m -> "sh(" <> m <> ")"),
+        ("p2sh_wsh_ms", \m -> "sh(wsh(" <> m <> "))"),
+        ("p2wsh_ms", \m -> "wsh(" <> m <> ")")
+      ]
+  let coins = singles <> multis
+  let amounts = Json.object [Key.fromText a .= (0.5 :: Double) | (a, _) <- coins]
+  funding <- text =<< walletRpc node "miner" "sendmany" [Json.String "", amounts]
+  outputs <- list =<< at "vout" =<< rpc node "getrawtransaction" [Json.String funding, Json.Bool True]
+  initial <-
+    text
+      =<< rpc
+        node
+        "createpsbt"
+        [ Json.toJSON [Json.object ["txid" .= funding, "vout" .= i] | i <- [0 .. length outputs - 1]],
+          Json.toJSON [Json.object [Key.fromText miner .= (3.99 :: Double)]]
+        ]
+  -- Each wallet leaves its signatures as partial signatures. Without
+  -- finalize=false, Core would finalize the inputs it can complete alone.
+  let signers = "miner" : concatMap snd coins
+  -- The arguments: the PSBT, sign, the sighash type, bip32derivs, finalize
+  let unfinalized = [Json.String initial, Json.Bool True, "ALL", Json.Bool True, Json.Bool False]
+  signed <- forM signers $ \w -> textAt "psbt" =<< walletRpc node w "walletprocesspsbt" unfinalized
+  combined <- text =<< rpc node "combinepsbt" [Json.toJSON signed]
+  complete <- textAt "psbt" =<< rpc node "finalizepsbt" [Json.String combined, Json.Bool False]
+  final <- textAt "hex" =<< rpc node "finalizepsbt" [Json.String combined, Json.Bool True]
+  let file =
+        Json.object $
+          ["initial_psbt" .= initial]
+            <> [Key.fromText (w <> "_psbt") .= s | (w, s) <- zip signers signed]
+            <> ["combined_psbt" .= combined, "complete_psbt" .= complete, "final_tx" .= final]
+  lookupEnv "HASKOIN_COMPLEX_PSBT" >>= mapM_ (\path -> BL.writeFile path (Json.encode file))
+  case Json.fromJSON file of
+    Json.Success complex -> return complex
+    Json.Error e -> fail ("The PSBTs of the node do not read: " <> e)
+  where
+    -- A wallet holds the private key of the coin
+    single (name, wrap) = do
+      let k = testKey (encodeUtf8 ("complex " <> name))
+      _ <- rpc node "createwallet" [Json.String name]
+      importDescriptor node name =<< withChecksum (wrap k.wif)
+      (,[name]) <$> addressOf (wrap k.publicHex)
+    -- Three wallets each hold one of the private keys of the coin, and the
+    -- first two sign
+    multi (name, wrap) = do
+      let ks = [testKey (encodeUtf8 ("complex " <> name <> " " <> T.pack (show i))) | i <- [1 .. 3 :: Int]]
+          keysOf i = [if j == i then k.wif else k.publicHex | (j, k) <- zip [1 ..] ks]
+          sorted i = "sortedmulti(2," <> T.intercalate "," (keysOf i) <> ")"
+          wallets = [name <> "_" <> T.pack (show i) | i <- [1 .. 3 :: Int]]
+      forM_ (zip [1 ..] wallets) $ \(i, w) -> do
+        _ <- rpc node "createwallet" [Json.String w]
+        importDescriptor node w =<< withChecksum (wrap (sorted i))
+      (,take 2 wallets) <$> addressOf (wrap (sorted (0 :: Int)))
+    withChecksum d = (\c -> d <> "#" <> c) <$> (textAt "checksum" =<< rpc node "getdescriptorinfo" [Json.String d])
+    addressOf d = do
+      public <- textAt "descriptor" =<< rpc node "getdescriptorinfo" [Json.String d]
+      firstText =<< rpc node "deriveaddresses" [Json.String public]
+
+-- | Mine blocks that pay the wallet of the miner
+mine :: Node -> Int -> IO ()
+mine node n = do
+  address <- walletRpc node "miner" "getnewaddress" []
+  _ <- rpc node "generatetoaddress" [Json.toJSON n, address]
+  return ()
+
+-- | Import a descriptor into a wallet, or fail with the reason the wallet
+-- gives
+importDescriptor :: Node -> Text -> Text -> IO ()
+importDescriptor node wallet descriptor = do
+  let request = Json.object ["desc" .= descriptor, "timestamp" .= ("now" :: Text)]
+  results <- list =<< walletRpc node wallet "importdescriptors" [Json.toJSON [request]]
+  forM_ results $ \r ->
+    at "success" r >>= \case
+      Json.Bool True -> return ()
+      _ -> fail ("The wallet " <> T.unpack wallet <> " refused " <> T.unpack descriptor <> ": " <> show r)
+
+emptyArray :: Json.Value
+emptyArray = Json.toJSON ([] :: [Json.Value])
+
+text :: Json.Value -> IO Text
+text (Json.String t) = return t
+text v = fail ("Not text: " <> show v)
+
+list :: Json.Value -> IO [Json.Value]
+list v = case Json.fromJSON v of
+  Json.Success l -> return l
+  Json.Error _ -> fail ("Not a list: " <> show v)
+
+firstText :: Json.Value -> IO Text
+firstText v =
+  list v >>= \case
+    first' : _ -> text first'
+    [] -> fail "An empty list"
+
+fromBase64 :: Text -> IO Psbt
+fromBase64 = either fail return . decodePsbtBase64 . encodeUtf8
+
+toBase64 :: Psbt -> Text
+toBase64 = decodeUtf8 . encodePsbtBase64
+
+{- The files of Bitcoin Core 32.1 -}
+
+-- The files live in data/psbt_core32.json: the PSBT of a payment as
+-- walletcreatefundedpsbt gives it in version 0 and in version 2, the
+-- version 2 one signed by walletprocesspsbt without finalizing, then
+-- finalized, and the transaction finalizepsbt extracts
+data Core32 = Core32
+  { preparedV0 :: Psbt,
+    preparedV2 :: Psbt,
+    signedV2 :: Psbt,
+    finalizedV2 :: Psbt,
+    extractedTx :: Tx
+  }
+
+instance Json.FromJSON Core32 where
+  parseJSON = Json.withObject "core32" $ \o ->
+    Core32
+      <$> psbtAt o "prepared_v0"
+      <*> psbtAt o "prepared_v2"
+      <*> psbtAt o "signed_v2"
+      <*> psbtAt o "finalized_v2"
+      <*> (either fail return . S.decode . hexBytes =<< o .: "final_tx")
+    where
+      psbtAt o name = either fail return . decodePsbtBase64 . encodeUtf8 =<< o .: name
+
+core32Spec :: Spec
+core32Spec =
+  describe "The files of Bitcoin Core 32.1, which writes version 2 unless asked for version 0" $ do
+    core <- runIO (readTestFile "psbt_core32.json" :: IO Core32)
+    it "are the same payment in both versions: the version 2 file is the version 0 file converted, and back" $ do
+      core.preparedV2.version `shouldBe` Version2
+      core.preparedV2.unsignedTx `shouldBe` core.preparedV0.unsignedTx
+      withVersion Version2 core.preparedV0 `shouldBe` core.preparedV2
+      withVersion Version0 core.preparedV2 `shouldBe` core.preparedV0
+
+    it "finalize into the PSBT Core finalized" $
+      finalizePsbt btc core.signedV2 `shouldBe` Right core.finalizedV2
+
+    it "give the transaction Core extracted" $
+      psbtTransaction core.finalizedV2 `shouldBe` Right core.extractedTx
+
+    -- The records name the key of the coin by the fingerprint bc560f95 of
+    -- a seed and the path m/44'/0'/0'/0/0: the account key at m/44'/0'/0'
+    -- of that seed signs. The coin is 50 BTC at the P2PKH script of that
+    -- key.
+    it "are signed with the account key the records name, into a transaction that verifies" $ do
+      let account = fromJust (xPrvImport btc "xprv9yHxeaLAZvxXb9VtJNesqk8avfN8misGAW9DUW9eacZJNqsfZxqKLmK5jfmvFideQqGesviJeagzSQYCuQySjgvt7TdfowKja5aJqbgyuNh")
+          signer = xPrvSigner account (Just (Derivation (fingerprintOf "bc560f95") "m/44'/0'/0'"))
+      coin <- expectRight (decodeSerial (hexBytes "76a914c80d55223e2f1061363add2a7b0363c285bf298d88ac"))
+      final <- expectRight (finalizePsbt btc =<< signPsbt btc signer core.preparedV2)
+      tx <- expectRight (psbtTransaction final)
+      final.version `shouldBe` Version2
+      verifyStdTx btc tx [(coin, 5000000000, OutPoint "fede72ccadbf9f16f826e3078578b0660526a37b48d4f894ab26f4cf5a95e89c" 0)] `shouldBe` True
+
+{- The checks of the signer and the finalizer -}
+
+signerChecksSpec :: Spec
+signerChecksSpec =
+  describe "The checks of the signer and the finalizer" $ do
+    let secret = PrivateKey secretOne True
+        public = derivePublicKey secret
+        otherPublic = compressedKey secretTwo
+        (psbt, coins) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))
+        parent = fromJust (either (const Nothing) id (nonWitnessUtxo (inputAt 0 psbt)))
+        coin = head parent.outputs
+        withInput m = withInputs [m] psbt
+        signer = keySigner secret.key
+        signed m = signPsbt btc signer (withInput (recordOf public m))
+        signatureCount s = fmap length (partialSignatures (inputAt 0 s))
+
+    -- BIP 174: "If a witness UTXO is provided, no non-witness signature
+    -- may be created"
+    it
+      "adds no signature to a legacy coin known from its witness \
+      \output only, which only a witness signature may use"
+      $ do
+        (signatureCount =<< signed (insertWitnessUtxo coin Map.empty)) `shouldBe` Right 0
+        let trusting = signer {requirePreviousTx = False}
+        (signatureCount =<< signPsbt btc trusting (withInput (insertWitnessUtxo coin Map.empty)))
+          `shouldBe` Right 0
+
+    -- The witness output beside the previous transaction claims 1 satoshi.
+    -- The coin holds 200,000,000. Bitcoin Core takes the previous
+    -- transaction and does not read the witness output then.
+    it "takes the coin from the previous transaction, and does not look at a witness output beside it" $ do
+      let claiming = insertWitnessUtxo (TxOut 1 coin.script) (insertNonWitnessUtxo parent Map.empty)
+      (signatureCount =<< signed (insertWitnessUtxo coin (insertNonWitnessUtxo parent Map.empty))) `shouldBe` Right 1
+      (signatureCount =<< signed claiming) `shouldBe` Right 1
+      inputCoins (withInput claiming) `shouldBe` Right [Just (InputCoin (TxOut 200000000 coin.script) True)]
+
+    it "refuses a sighash type no node accepts, and one whose fork id flag does not fit the network" $ do
+      signed (insertSigHashType 0 (insertNonWitnessUtxo parent Map.empty)) `shouldBe` Left "Input 0: the sighash type 0 is not one a node accepts"
+      signed (insertSigHashType 0x21 (insertNonWitnessUtxo parent Map.empty)) `shouldBe` Left "Input 0: the sighash type 33 is not one a node accepts"
+      signed (insertSigHashType (setForkIdFlag sigHashAll) (insertNonWitnessUtxo parent Map.empty)) `shouldBe` Left "Input 0: the sighash type has a fork id flag the network does not use"
+      signPsbt bch signer (withInput (recordOf public (insertSigHashType sigHashAll (insertNonWitnessUtxo parent Map.empty))))
+        `shouldBe` Left "Input 0: the sighash type lacks the fork id flag the network requires"
+      -- With the flag, the Bitcoin Cash digest signs
+      (signatureCount =<< signPsbt bch signer (withInput (recordOf public (insertSigHashType (setForkIdFlag sigHashAll) (insertNonWitnessUtxo parent Map.empty))))) `shouldBe` Right 1
+
+    it "refuses a sighash type the signer does not accept, and signs with it once the signer lists it" $ do
+      let acceptingSingle = signer {acceptedSigHashes = [sigHashSingle]}
+          askingSingle = insertSigHashType sigHashSingle (insertNonWitnessUtxo parent Map.empty)
+      signed askingSingle `shouldBe` Left "Input 0: the sighash type 3 is not one the signer accepts"
+      (signatureCount =<< signPsbt btc acceptingSingle (withInput (recordOf public askingSingle))) `shouldBe` Right 1
+      -- ANYONECANPAY makes another type: 0x81 is not 0x01
+      signed (insertSigHashType (setAnyoneCanPay sigHashAll) (insertNonWitnessUtxo parent Map.empty)) `shouldBe` Left "Input 0: the sighash type 129 is not one the signer accepts"
+
+    -- Two coins of the same script, spent by one transaction with one
+    -- output: input 1 has no output at its index
+    it
+      "adds no SIGHASH_SINGLE signature to a legacy input that has no output at \
+      \its index, signs the input that has one, and signs both on SegWit coins"
+      $ do
+        let witnessCoin = TxOut 200000000 (encodeSerial (PayWitnessPKHash (addressHash (encodeSerial public))))
+            parentOf c = Tx 1 [TxIn (OutPoint "e567952fb6cc33857f392efa3a46c995a28f69cca4bb1b37e0204dab1ec7a389" 1) "" 0xffffffff] [c, c] [] 0
+            spendingBoth p = Tx 2 [TxIn (OutPoint (txHash p) 0) "" 0xfffffffe, TxIn (OutPoint (txHash p) 1) "" 0xfffffffe] [TxOut 399999000 (hexBytes "76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac")] [] 0
+            askingSingle p = recordOf public (insertSigHashType sigHashSingle (insertNonWitnessUtxo p Map.empty))
+            psbtOf p = Psbt Version0 (spendingBoth p) Map.empty [askingSingle p, askingSingle p] [Map.empty]
+            acceptingSingle = signer {acceptedSigHashes = [sigHashSingle]}
+        signedLegacy <- expectRight (signPsbt btc acceptingSingle (psbtOf (parentOf coin)))
+        mapM (fmap length . partialSignatures) signedLegacy.inputs `shouldBe` Right [1, 0]
+        -- The BIP 143 digest commits to the coin, so the SegWit signature is fine
+        (signatureCount =<< signPsbt btc acceptingSingle (psbtOf (parentOf witnessCoin))) `shouldBe` Right 1
+        (fmap length . partialSignatures . inputAt 1 =<< signPsbt btc acceptingSingle (psbtOf (parentOf witnessCoin))) `shouldBe` Right 1
+
+    -- BIP 174: "If a redeemScript is provided, the scriptPubKey must be
+    -- for that redeemScript"
+    it
+      "adds no signature when the redeem script does not hash \
+      \to the coin, nor when the coin is not pay-to-script-hash"
+      $ do
+        let ms = PayMulSig [public, otherPublic] 1
+            msScript = either error id (encodeOutput ms)
+            wrongScript = either error id (encodeOutput (PayMulSig [otherPublic, public] 1))
+            (p2sh, _) = spendingPsbt (either error id (toP2SH msScript))
+            p2shParent = fromJust (either (const Nothing) id (nonWitnessUtxo (inputAt 0 p2sh)))
+            p2shInput m = withInputs [recordOf public (insertNonWitnessUtxo p2shParent m)] p2sh
+        (signatureCount =<< signPsbt btc signer (p2shInput (insertInputRedeemScript msScript Map.empty))) `shouldBe` Right 1
+        (signatureCount =<< signPsbt btc signer (p2shInput (insertInputRedeemScript wrongScript Map.empty)))
+          `shouldBe` Right 0
+        (signatureCount =<< signed (insertInputRedeemScript msScript (insertNonWitnessUtxo parent Map.empty)))
+          `shouldBe` Right 0
+
+    -- BIP 174: "If a witnessScript is provided, the scriptPubKey or the
+    -- redeemScript must be for that witnessScript"
+    it
+      "adds no signature when the witness script does not hash to \
+      \the witness program, nor when the coin has no witness script"
+      $ do
+        let ms = PayMulSig [public, otherPublic] 1
+            msScript = either error id (encodeOutput ms)
+            wrongScript = either error id (encodeOutput (PayMulSig [otherPublic, public] 1))
+            (p2wsh, _) = spendingPsbt (either error id (toP2WSH msScript))
+            p2wshInput m = withInputs [recordOf public (Map.union m (inputAt 0 p2wsh))] p2wsh
+        (signatureCount =<< signPsbt btc signer (p2wshInput (insertInputWitnessScript msScript Map.empty))) `shouldBe` Right 1
+        (signatureCount =<< signPsbt btc signer (p2wshInput (insertInputWitnessScript wrongScript Map.empty)))
+          `shouldBe` Right 0
+        (signatureCount =<< signed (insertInputWitnessScript msScript (insertNonWitnessUtxo parent Map.empty)))
+          `shouldBe` Right 0
+
+    it "leaves an input whose coin script is not standard as it is, and signs the others" $ do
+      let weird = TxOut 1000 (runPutS (serialize (Script [OP_1])))
+          parent2 = Tx 1 parent.inputs [coin, weird] [] 0
+          op0 = OutPoint (txHash parent2) 0
+          op1 = OutPoint (txHash parent2) 1
+          tx = Tx 2 [TxIn op0 "" 0xfffffffe, TxIn op1 "" 0xfffffffe] psbt.unsignedTx.outputs [] 0
+          both = Psbt Version0 tx Map.empty [recordOf public (insertNonWitnessUtxo parent2 Map.empty), insertNonWitnessUtxo parent2 Map.empty] [Map.empty, Map.empty]
+      s <- expectRight (signPsbt btc signer both)
+      map hasPartialSignatures s.inputs `shouldBe` [True, False]
+      f <- expectRight (finalizePsbt btc s)
+      map (isJust . finalScriptSig) f.inputs `shouldBe` [True, False]
+
+    it "signs a coin whose key it holds without a derivation record, by the hash of the key" $ do
+      (signatureCount =<< signPsbt btc signer (withInput (insertNonWitnessUtxo parent Map.empty))) `shouldBe` Right 1
+      -- A multisig coin names its keys
+      let ms = PayMulSig [public, otherPublic] 1
+          msScript = either error id (encodeOutput ms)
+          (p2sh, p2shCoins) = spendingPsbt (either error id (toP2SH msScript))
+          p2shParent = fromJust (either (const Nothing) id (nonWitnessUtxo (inputAt 0 p2sh)))
+          p2shFields = withInputs [insertInputRedeemScript msScript (insertNonWitnessUtxo p2shParent Map.empty)] p2sh
+      s <- expectRight (signPsbt btc signer p2shFields)
+      signatureCount s `shouldBe` Right 1
+      signsAndVerifies btc [secret] (p2shFields, p2shCoins) `shouldBe` Right True
+      -- The other key is not held
+      (signatureCount =<< signPsbt btc (keySigner secret.key) (fst (spendingPsbt (PayPKHash (addressHash (encodeSerial otherPublic)))))) `shouldBe` Right 0
+      coins `seq` return ()
+
+    it
+      "the finalizer leaves alone an input whose signature is not a signature, \
+      \has another sighash type than the input asks, or does not verify"
+      $ do
+        s <- expectRight (signed (insertNonWitnessUtxo parent Map.empty))
+        signature <- case either error id (partialSignatures (inputAt 0 s)) of
+          [(_, sig)] -> return sig
+          _ -> fail "one signature"
+        let withSig sig m = withInput (insertPartialSignature public sig m)
+            leftAlone unsigned = finalizePsbt btc unsigned `shouldBe` Right unsigned
+        -- 3045aa01 ends with the byte of SIGHASH_ALL, and is no signature
+        leftAlone (withSig "\x30\x45\xaa\x01" (insertNonWitnessUtxo parent Map.empty))
+        leftAlone (withSig signature (insertSigHashType sigHashNone (insertNonWitnessUtxo parent Map.empty)))
+        -- The signature of the same key on another transaction
+        let sameKeyOther = withInputs [recordOf public (insertNonWitnessUtxo parent Map.empty)] (Psbt Version0 (Tx 2 psbt.unsignedTx.inputs [] [] 0) Map.empty psbt.inputs [])
+        elsewhere <- expectRight (signPsbt btc signer sameKeyOther)
+        foreignSig <- case either error id (partialSignatures (inputAt 0 elsewhere)) of
+          [(_, sig)] -> return sig
+          _ -> fail "one signature"
+        leftAlone (withSig foreignSig (insertNonWitnessUtxo parent Map.empty))
+        -- The right signature finalizes
+        f <- expectRight (finalizePsbt btc (withSig signature (insertNonWitnessUtxo parent Map.empty)))
+        isJust (finalScriptSig (inputAt 0 f)) `shouldBe` True
+
+{- Taproot -}
+
+data Vectors371 = Vectors371
+  { refused371 :: [Vector],
+    accepted371 :: [Vector]
+  }
+
+instance Json.FromJSON Vectors371 where
+  parseJSON = Json.withObject "vectors" $ \o -> Vectors371 <$> o .: "invalid" <*> o .: "valid"
+
+-- | Why each invalid PSBT of BIP 371 is refused, as the end of the reason
+refusals371 :: [String]
+refusals371 =
+  [ "Input 0: the value of the key 0x17 is not an x-only public key",
+    "Input 0: the value of the key 0x13 is not a Taproot signature: decodeTaprootSig: a signature is 64 or 65 bytes, not 63",
+    "Input 0: the value of the key 0x13 is not a Taproot signature: decodeTaprootSig: a signature is 64 or 65 bytes, not 66",
+    "is not an x-only public key",
+    "Output 1: the value of the key 0x05 is not an x-only public key",
+    "is not an x-only public key",
+    "is not an x-only public key and a leaf hash",
+    "is not a Taproot signature: decodeTaprootSig: a signature is 64 or 65 bytes, not 66",
+    "is not a Taproot signature: decodeTaprootSig: a signature is 64 or 65 bytes, not 63",
+    "is not a control block",
+    "is not a control block"
+  ]
+
+-- | Why each invalid PSBT of BIP 373 is refused, as the end of the reason.
+-- An x-only key has 32 bytes where the BIP wants a compressed key of 33.
+refusals373 :: [String]
+refusals373 =
+  [ "is not a compressed public key",
+    "is not a list of compressed public keys",
+    "is not a compressed public key",
+    "is not a list of compressed public keys",
+    "is not a participant key and an aggregate key, with a leaf hash or none",
+    "is not a participant key and an aggregate key, with a leaf hash or none",
+    "is not a public nonce of 66 bytes",
+    "is not a participant key and an aggregate key, with a leaf hash or none",
+    "is not a participant key and an aggregate key, with a leaf hash or none",
+    "is not a partial signature of 32 bytes"
+  ]
+
+-- The vectors live in data/psbt_bip373.json, copied from the BIP. The
+-- library keeps the MuSig2 fields and does not sign with them.
+musig2Spec :: Vectors371 -> Spec
+musig2Spec vectors =
+  describe "The MuSig2 fields of BIP 373" $ do
+    describe "the invalid PSBTs are refused, each for its reason" $
+      forM_ (zip vectors.refused371 refusals373) $ \(v, reason) ->
+        it v.vecCase $ decodePsbt (bytesOf v) `shouldSatisfy` either (reason `isSuffixOf`) (const False)
+
+    describe "the valid PSBTs are read, and written back byte for byte" $
+      forM_ vectors.accepted371 $ \v ->
+        it v.vecCase $ (encodePsbt <$> decodePsbt (bytesOf v)) `shouldBe` Right (bytesOf v)
+
+    it "there are 10 invalid PSBTs and 14 valid ones" $
+      (length vectors.refused371, length vectors.accepted371) `shouldBe` (10, 14)
+
+    -- The key is the type and a compressed key, 34 bytes (0x22). The value
+    -- is no key, then one key, then one key and a byte, then a key that
+    -- is no point of the curve.
+    it "reads participant keys that are compressed public keys, as many as there are, on an input and on an output" $
+      forM_ ["00", "21" <> aPoint, "42" <> aPoint <> aPoint] $ \value -> do
+        (encodePsbt <$> decodePsbt (tinyPsbt "" ("221a" <> aPoint <> value) ""))
+          `shouldBe` Right (tinyPsbt "" ("221a" <> aPoint <> value) "")
+        (encodePsbt <$> decodePsbt (tinyPsbt "" "" ("2208" <> aPoint <> value)))
+          `shouldBe` Right (tinyPsbt "" "" ("2208" <> aPoint <> value))
+
+    it "refuses participant keys that are not whole compressed public keys on the curve" $ do
+      let refusal what =
+            Left . mconcat $
+              [ what <> ": the value of the key 0x1a with the data " <> T.unpack aPoint,
+                " is not a list of compressed public keys"
+              ]
+      decodePsbt (tinyPsbt "" ("221a" <> aPoint <> "22" <> aPoint <> "00") "") `shouldBe` refusal "Input 0"
+      decodePsbt (tinyPsbt "" ("221a" <> aPoint <> "21" <> notAPoint) "") `shouldBe` refusal "Input 0"
+      decodePsbt (tinyPsbt "" ("221a" <> notAPoint <> "00") "")
+        `shouldBe` Left
+          ("Input 0: the key 0x1a with the data " <> T.unpack notAPoint <> " is not a compressed public key")
+
+    -- The generator of the curve as an uncompressed key of 65 bytes: with
+    -- the type, a key of 66 bytes (0x42)
+    it "refuses an aggregate key that is an uncompressed public key" $ do
+      let generator =
+            "0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\
+            \483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
+      decodePsbt (tinyPsbt "" ("421a" <> generator <> "00") "")
+        `shouldSatisfy` either ("is not a compressed public key" `isSuffixOf`) (const False)
+
+    -- The key is the type, a participant key and an aggregate key, 67 bytes
+    -- (0x43), or 99 (0x63) with a leaf hash. A nonce has 66 bytes (0x42)
+    -- and a partial signature 32 (0x20).
+    it "reads a public nonce and a partial signature, with a leaf hash or none" $ do
+      let nonce = "42" <> T.replicate 66 "ab"
+          partial = "20" <> T.replicate 32 "ab"
+          leafHash' = T.replicate 32 "cd"
+      let entries =
+            [ "431b" <> aPoint <> aPoint <> nonce,
+              "631b" <> aPoint <> aPoint <> leafHash' <> nonce,
+              "431c" <> aPoint <> aPoint <> partial,
+              "631c" <> aPoint <> aPoint <> leafHash' <> partial
+            ]
+      forM_ entries $ \entry ->
+        (encodePsbt <$> decodePsbt (tinyPsbt "" entry "")) `shouldBe` Right (tinyPsbt "" entry "")
+
+    it
+      "refuses a public nonce or a partial signature under a \
+      \key that is no point of the curve, or of another length"
+      $ do
+        let nonce = "42" <> T.replicate 66 "ab"
+            refused entry =
+              decodePsbt (tinyPsbt "" entry "")
+                `shouldSatisfy` either (noSignerKey `isSuffixOf`) (const False)
+            noSignerKey = "is not a participant key and an aggregate key, with a leaf hash or none"
+        refused ("431b" <> notAPoint <> aPoint <> nonce)
+        refused ("431b" <> aPoint <> notAPoint <> nonce)
+        refused ("441b" <> aPoint <> aPoint <> "cd" <> nonce)
+        refused ("431c" <> aPoint <> notAPoint <> "20" <> T.replicate 32 "ab")
+
+    it "refuses a public nonce that has not 66 bytes, and a partial signature that has not 32" $ do
+      decodePsbt (tinyPsbt "" ("431b" <> aPoint <> aPoint <> "41" <> T.replicate 65 "ab") "")
+        `shouldSatisfy` either ("is not a public nonce of 66 bytes" `isSuffixOf`) (const False)
+      decodePsbt (tinyPsbt "" ("431c" <> aPoint <> aPoint <> "21" <> T.replicate 33 "ab") "")
+        `shouldSatisfy` either ("is not a partial signature of 32 bytes" `isSuffixOf`) (const False)
+
+taprootSpec :: Vectors371 -> Spec
+taprootSpec vectors =
+  describe "The Taproot fields of BIP 371" $ do
+    describe "the invalid PSBTs are refused, each for its reason" $
+      forM_ (zip vectors.refused371 refusals371) $ \(v, reason) ->
+        it v.vecCase $ decodePsbt (bytesOf v) `shouldSatisfy` either (reason `isSuffixOf`) (const False)
+
+    describe "the valid PSBTs are read, and written back byte for byte" $
+      forM_ vectors.accepted371 $ \v ->
+        it v.vecCase $ (encodePsbt <$> decodePsbt (bytesOf v)) `shouldBe` Right (bytesOf v)
+
+    let vectorAt i = psbtOfVector (vectors.accepted371 !! i)
+        xOnly text = fromJust (importXOnlyPubKey (hexBytes text))
+        digest text = fromJust (digestFromByteString (hexBytes text)) :: Digest SHA256
+        keyScript text = Script [opPushData (hexBytes text), OP_CHECKSIG]
+
+    it "read the internal key and the derivation of a key path input" $ do
+      psbt <- vectorAt 0
+      inputTapInternalKey (inputAt 0 psbt) `shouldBe` Right (Just (xOnly "fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa232"))
+      inputTapDerivations (inputAt 0 psbt) `shouldBe` Right [(xOnly "fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa232", TapDerivation [] (Derivation (fingerprintOf "772b2da7") "m/86'/1'/0'/1/0"))]
+      inputTapMerkleRoot (inputAt 0 psbt) `shouldBe` Right Nothing
+      tapKeySig (inputAt 0 psbt) `shouldBe` Right Nothing
+
+    it "read the key path signature of a signed input, and finalize it into a witness of that signature" $ do
+      psbt <- vectorAt 1
+      let sigHex = "bb53ec917bad9d906af1ba87181c48b86ace5aae2b53605a725ca74625631476fc6f5baedaf4f2ee0f477f36f58f3970d5b8273b7e497b97af2e3f125c97af34"
+          sig = fromJust (schnorrSig (hexBytes sigHex))
+      tapKeySig (inputAt 0 psbt) `shouldBe` (Just <$> taprootSignature sig sigHashDefault)
+      final <- expectRight (finalizePsbt btc psbt)
+      finalScriptWitness (inputAt 0 final) `shouldBe` Right (Just [hexBytes sigHex])
+      Map.keys (inputAt 0 final) `shouldBe` [Key 0x01 "", Key 0x08 ""]
+      tx <- expectRight (psbtTransaction final)
+      let coin = TxOut 5000000000 (hexBytes "51205a2c2cf5b52cf31f83ad2e8da63ff03183ecd8f609c7510ae8a48e03910a0757")
+      verifyStdTx btc tx [(either error id (decodeSerial coin.script), coin.value, (head tx.inputs).outpoint)] `shouldBe` True
+
+    it "read the internal key and the derivation of a key path output" $ do
+      psbt <- vectorAt 2
+      outputTapInternalKey (outputAt 0 psbt) `shouldBe` Right (Just (xOnly "1124da7aec92ccd06c954562647f437b138b95721a84be2bf2276bbddab3e671"))
+      outputTapDerivations (outputAt 0 psbt) `shouldBe` Right [(xOnly "1124da7aec92ccd06c954562647f437b138b95721a84be2bf2276bbddab3e671", TapDerivation [] (Derivation (fingerprintOf "772b2da7") "m/86'/1'/0'/0/5"))]
+      outputTapTree (outputAt 0 psbt) `shouldBe` Right Nothing
+
+    it "read the leaf scripts, the derivations with their leaves, the internal key and the Merkle root of a script path input" $ do
+      psbt <- vectorAt 3
+      leaves <- expectRight (tapLeafScripts (inputAt 0 psbt))
+      map (.script) leaves
+        `shouldBe` [ keyScript "2cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2",
+                     keyScript "4320b0bf16f011b53ea7be615924aa7f27e5d29ad20ea1155d848676c3bad1b2",
+                     keyScript "fa0f7a3cef3b1d0c0a6ce7d26e17ada0b2e5c92d19efad48b41859cb8a451ca9"
+                   ]
+      map (.leafVersion) leaves `shouldBe` [0xc0, 0xc0, 0xc0]
+      map (B.length . (.controlBlock)) leaves `shouldBe` [97, 65, 97]
+      inputTapInternalKey (inputAt 0 psbt) `shouldBe` Right (Just (xOnly "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0"))
+      inputTapMerkleRoot (inputAt 0 psbt) `shouldBe` Right (Just (digest "f0362e2f75a6f420a5bde3eb221d96ae6720cf25f81890c95b1d775acb515e65"))
+      records <- expectRight (inputTapDerivations (inputAt 0 psbt))
+      lookup (xOnly "2cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2") records
+        `shouldBe` Just (TapDerivation [digest "cd970e15f53fc0c82f950fd560ffa919b76172be017368a89913af074f400b09"] (Derivation (fingerprintOf "772b2da7") "m/86'/1'/2'/0/0"))
+      lookup (xOnly "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0") records
+        `shouldBe` Just (TapDerivation [] (Derivation (fingerprintOf "7c461e5d") "m"))
+      -- The leaf hash of the record is the hash of the leaf script
+      leafHash 0xc0 (keyScript "2cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2") `shouldBe` digest "cd970e15f53fc0c82f950fd560ffa919b76172be017368a89913af074f400b09"
+      -- The control blocks commit the leaves to the output key, with the Merkle root
+      let outKey = fromJust (importXOnlyPubKey (hexBytes "c2247efbfd92ac47f6f40b8d42d169175a19fa9fa10e4a25d7f35eb4dd85b692"))
+      forM_ leaves $ \leaf -> do
+        (v, internal, proof) <- expectRight (decodeControlBlock leaf.controlBlock)
+        verifyScriptPathData outKey (ScriptPathData Nothing [] leaf.script (odd v) 0xc0 internal proof Nothing) `shouldBe` True
+
+    it "read the script tree of a script path output, whose leaves build the tree of its output key" $ do
+      psbt <- vectorAt 4
+      let leaves =
+            [ TapLeaf 2 0xc0 (keyScript "736e572900fe1252589a2143c8f3c79f71a0412d2353af755e9701c782694a02"),
+              TapLeaf 2 0xc0 (keyScript "631c5f3b5832b8fbdebfb19704ceeb323c21f40f7a24f43d68ef0cc26b125969"),
+              TapLeaf 1 0xc0 (keyScript "44faa49a0338de488c8dfffecdfb6f329f380bd566ef20c8df6d813eab1c4273")
+            ]
+      outputTapTree (outputAt 0 psbt) `shouldBe` Right (Just leaves)
+      outputTapInternalKey (outputAt 0 psbt) `shouldBe` Right (Just (xOnly "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0"))
+      let tree = fromJust (tapTreeFromLeaves leaves)
+          output = TaprootOutput (xOnly "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0") (Just tree)
+      encodeSerial (forceRight (taprootScriptOutput output)) `shouldBe` (head psbt.unsignedTx.outputs).script
+      Map.lookup (Key 0x06 "") (insertOutputTapTree leaves Map.empty) `shouldBe` Map.lookup (Key 0x06 "") (outputAt 0 psbt)
+      records <- expectRight (outputTapDerivations (outputAt 0 psbt))
+      length records `shouldBe` 4
+
+    -- The tree of the vector has one leaf at depth 1 and two at depth 2,
+    -- and all three are signed. A control block is 33 bytes and 32 for
+    -- each level: 65 bytes at depth 1, 97 at depth 2.
+    it
+      "read the script path signatures of a signed input, and finalize \
+      \it with the signed leaf that has the shortest control block"
+      $ do
+        psbt <- vectorAt 5
+        sigs <- expectRight (tapScriptSigs (inputAt 0 psbt))
+        map (\((k, h), s) -> (exportXOnlyPubKey k, h, B.length (encodeTaprootSig s))) sigs
+          `shouldBe` [ (hexBytes "2cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2", digest "cd970e15f53fc0c82f950fd560ffa919b76172be017368a89913af074f400b09", 64),
+                       (hexBytes "4320b0bf16f011b53ea7be615924aa7f27e5d29ad20ea1155d848676c3bad1b2", digest "115f2e490af7cc45c4f78511f36057ce5c5a5c56325a29fb44dfc203f356e1f8", 64),
+                       (hexBytes "fa0f7a3cef3b1d0c0a6ce7d26e17ada0b2e5c92d19efad48b41859cb8a451ca9", digest "6f7d62059e9497a1a4a267569d9876da60101aff38e3529b9b939ce7f91ae970", 64)
+                     ]
+        final <- expectRight (finalizePsbt btc psbt)
+        witness <- expectRight (finalScriptWitness (inputAt 0 final))
+        fmap (map B.length) witness `shouldBe` Just [64, 34, 65]
+        tx <- expectRight (psbtTransaction final)
+        let coin = TxOut 5000000000 (hexBytes "5120c2247efbfd92ac47f6f40b8d42d169175a19fa9fa10e4a25d7f35eb4dd85b692")
+        verifyStdTx btc tx [(either error id (decodeSerial coin.script), coin.value, (head tx.inputs).outpoint)] `shouldBe` True
+
+    it "write the fields back as they were read" $
+      forM_ [0 .. 5] $ \i -> do
+        psbt <- vectorAt i
+        forM_ psbt.inputs $ \m -> do
+          key <- expectRight (inputTapInternalKey m)
+          forM_ key $ \k -> Map.lookup (Key 0x17 "") (insertInputTapInternalKey k Map.empty) `shouldBe` Map.lookup (Key 0x17 "") m
+          root <- expectRight (inputTapMerkleRoot m)
+          forM_ root $ \r -> Map.lookup (Key 0x18 "") (insertInputTapMerkleRoot r Map.empty) `shouldBe` Map.lookup (Key 0x18 "") m
+          sig <- expectRight (tapKeySig m)
+          forM_ sig $ \s -> Map.lookup (Key 0x13 "") (insertTapKeySig s Map.empty) `shouldBe` Map.lookup (Key 0x13 "") m
+          leaves <- expectRight (tapLeafScripts m)
+          Map.toList (foldr insertTapLeafScript Map.empty leaves) `shouldBe` [(k, v) | (k, v) <- Map.toList m, k.keyType == 0x15]
+          records <- expectRight (inputTapDerivations m)
+          Map.toList (foldr (uncurry insertInputTapDerivation) Map.empty records) `shouldBe` [(k, v) | (k, v) <- Map.toList m, k.keyType == 0x16]
+          sigs <- expectRight (tapScriptSigs m)
+          Map.toList (foldr (\((k, h), s) -> insertTapScriptSig k h s) Map.empty sigs) `shouldBe` [(k, v) | (k, v) <- Map.toList m, k.keyType == 0x14]
+        forM_ psbt.outputs $ \m -> do
+          key <- expectRight (outputTapInternalKey m)
+          forM_ key $ \k -> Map.lookup (Key 0x05 "") (insertOutputTapInternalKey k Map.empty) `shouldBe` Map.lookup (Key 0x05 "") m
+          records <- expectRight (outputTapDerivations m)
+          Map.toList (foldr (uncurry insertOutputTapDerivation) Map.empty records) `shouldBe` [(k, v) | (k, v) <- Map.toList m, k.keyType == 0x07]
+
+    prop "a Taproot coin without script tree, signed by its key path with the internal key and finalized, verifies" $
+      forAll arbitraryKeyPair $ \(secret, public) ->
+        let coinScript = forceRight (taprootScriptOutput (TaprootOutput public.point Nothing))
+            (psbt, coins) = spendingPsbt coinScript
+            fields = insertInputTapInternalKey public.point . insertInputTapDerivation public.point (TapDerivation [] (Derivation (fingerprintOf "d90c6a4f") "m/86'/0'/0'/0/0"))
+            withFields = withInputs (fields <$> psbt.inputs) psbt
+            signed = signPsbt btc (keySigner secret.key) withFields
+         in (signsAndVerifies btc [secret] (withFields, coins), fmap (fmap (fmap (.hash)) . tapKeySig . inputAt 0) signed) === (Right True, Right (Right (Just sigHashDefault)))
+
+    prop "a Taproot coin with a leaf that checks one key, signed by that leaf and finalized, verifies" $
+      forAll ((,) <$> arbitraryKeyPair <*> arbitraryKeyPair) $ \((secret, public), (_, internal)) ->
+        let leaf = Script [opPushData (exportXOnlyPubKey public.point), OP_CHECKSIG]
+            tree = MASTBranch (MASTLeaf 0xc0 leaf) (MASTLeaf 0xc0 (Script [OP_RETURN]))
+            output = TaprootOutput internal.point (Just tree)
+            coinScript = forceRight (taprootScriptOutput output)
+            (psbt, coins) = spendingPsbt coinScript
+            proof = case getMerkleProofs tree of
+              (_, _, p) : _ -> p
+              [] -> []
+            control = encodeControlBlock (0xc0 + keyParity (forceRight (taprootOutputKey output))) internal.point proof
+            fields =
+              insertInputTapInternalKey internal.point
+                . insertInputTapMerkleRoot (mastCommitment tree)
+                . insertTapLeafScript (TapLeafScript control leaf 0xc0)
+                . insertInputTapDerivation public.point (TapDerivation [leafHash 0xc0 leaf] (Derivation (fingerprintOf "d90c6a4f") "m/86'/0'/0'/0/1"))
+            withFields = withInputs (fields <$> psbt.inputs) psbt
+         in signsAndVerifies btc [secret] (withFields, coins) === Right True
+
+    it "the signer refuses a sighash type a Taproot signature may not use" $ do
+      let public = derivePublicKey (PrivateKey secretOne True)
+          (psbt, _) = spendingPsbt (forceRight (taprootScriptOutput (TaprootOutput public.point Nothing)))
+          fields = insertSigHashType (setForkIdFlag sigHashAll) . insertInputTapInternalKey public.point
+      signPsbt btc (keySigner secretOne) (onInputs fields psbt)
+        `shouldBe` Left "Input 0: the sighash type 65 is not one a Taproot signature may use"
+
+    -- The coin is the one of key 1, and the input names key 2 as its
+    -- internal key. A signature of key 2 would verify for no coin, and BIP
+    -- 174 has a signer make only valid signatures. Bitcoin Core does not
+    -- refuse such a PSBT, so the input is left as it is.
+    it "the signer adds no key path signature when the internal key of the input does not give the coin" $ do
+      let public = derivePublicKey (PrivateKey secretOne True)
+          other = compressedKey secretTwo
+          (psbt, _) = spendingPsbt (forceRight (taprootScriptOutput (TaprootOutput public.point Nothing)))
+          naming = withInputs [insertInputTapInternalKey other.point (inputAt 0 psbt)] psbt
+      -- The signer of key 2 holds the internal key that the input names
+      signPsbt btc (keySigner secretTwo) naming `shouldBe` Right naming
+      -- The signer of key 1 holds no key that the input names
+      signPsbt btc (keySigner secretOne) naming `shouldBe` Right naming
+      -- Without the internal key, the input is left alone
+      signPsbt btc (keySigner secretOne) psbt `shouldBe` Right psbt
+
+{- Properties -}
+
+propertiesSpec :: Spec
+propertiesSpec =
+  describe "Any PSBT" $ do
+    prop "is read back as it was written" $
+      forAll (arbitraryPsbt btc) $
+        \psbt -> decodePsbt (encodePsbt psbt) == Right psbt
+
+    prop "is read back from its base64 text" $
+      forAll (arbitraryPsbt btc) $
+        \psbt -> decodePsbtBase64 (encodePsbtBase64 psbt) == Right psbt
+
+    prop "combined with itself is itself" $
+      forAll (arbitraryPsbt btc) $
+        \psbt -> combinePsbt psbt psbt == Right psbt
+
+    -- The combiner of BIP 174 keeps every entry that either PSBT has. The
+    -- key type 0x7e is one no map knows.
+    prop "combined with a copy that has one more entry in every map, in either order, is that copy" $
+      forAll (arbitraryPsbt btc) $ \psbt ->
+        let oneMore = Map.insert (Key 0x7e "combiner test") "one more entry"
+            copy = Psbt psbt.version psbt.unsignedTx (oneMore psbt.globals) (oneMore <$> psbt.inputs) (oneMore <$> psbt.outputs)
+         in combinePsbt psbt copy == Right copy && combinePsbt copy psbt == Right copy
+
+{- What the decoder refuses -}
+
+-- | The unsigned transaction of 'tinyPsbt': version 2, one input that
+-- spends output 0 of the transaction whose id bytes are 00 01 … 1f, one
+-- output of 1,000 satoshi, lock time 0. It is 82 bytes long.
+tinyTx :: Text
+tinyTx = "0200000001000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f0000000000ffffffff01e803000000000000160014111111111111111111111111111111111111111100000000"
+
+-- | A PSBT of version 0 over 'tinyTx', with the entries given, in hex, in
+-- its global map, in the map of its input and in the map of its output.
+-- An entry is a key after its length, then a value after its length. The
+-- first entry is the transaction: 0x52 is its 82 bytes.
+tinyPsbt :: Text -> Text -> Text -> ByteString
+tinyPsbt globalEntries inputEntries outputEntries =
+  hexBytes ("70736274ff" <> "010052" <> tinyTx <> globalEntries <> "00" <> inputEntries <> "00" <> outputEntries <> "00")
+
+-- | The same payment as 'tinyPsbt' in version 2, with the entries given in
+-- the map of its input: the transaction version 2, one input, one output
+-- and the PSBT version 2 in the global map, the transaction id and the
+-- output index 0 in the input, the amount and the script in the output.
+tinyPsbt2 :: Text -> ByteString
+tinyPsbt2 inputEntries =
+  hexBytes $
+    "70736274ff"
+      <> ("01020402000000" <> "01040101" <> "01050101" <> "01fb0402000000" <> "00")
+      <> (inputEntries <> "010e20000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" <> "010f0400000000" <> "00")
+      <> ("010308e803000000000000" <> "01041600141111111111111111111111111111111111111111" <> "00")
+
+-- | 33 bytes that start like a compressed public key and are no point of
+-- the curve: the x coordinate ff…ff is above the field size
+notAPoint :: Text
+notAPoint = "02" <> T.replicate 32 "ff"
+
+-- | A public key of the BIP 174 vectors
+aPoint :: Text
+aPoint = "029583bf39ae0a609747ad199addd634fa6108559d6c5cd39b4c2183f1ab96e07f"
+
+-- | A transaction of 61 bytes that the input of 'tinyTx' does not spend:
+-- one input, one output of 5,000 satoshi with the script OP_1
+anotherTx :: Text
+anotherTx = "0100000001" <> T.replicate 32 "00" <> "ffffffff" <> "00" <> "ffffffff" <> "01" <> "8813000000000000" <> "0151" <> "00000000"
+
+-- | A leaf of a script tree as PSBT_OUT_TAP_TREE lists it: its depth, its
+-- leaf version, and after its length of 34 bytes the script
+-- @<32 bytes of 0x22> OP_CHECKSIG@. It is 37 bytes long.
+treeLeaf :: Text -> Text -> Text
+treeLeaf depth version = depth <> version <> "22" <> "20" <> T.replicate 32 "22" <> "ac"
+
+decoderChecksSpec :: Spec
+decoderChecksSpec =
+  describe "What the decoder refuses, as Bitcoin Core 32.1 does" $ do
+    it "reads the small PSBT that the cases below add one entry to, in both versions" $ do
+      (encodePsbt <$> decodePsbt (tinyPsbt "" "" "")) `shouldBe` Right (tinyPsbt "" "" "")
+      (encodePsbt <$> decodePsbt (tinyPsbt2 "")) `shouldBe` Right (tinyPsbt2 "")
+
+    -- The type of a key is a compact size integer. fd0000 is 0, and fd0200
+    -- is 2, over three bytes where one is enough.
+    it "refuses a key whose type is not in its shortest form" $ do
+      decodePsbt (tinyPsbt "03fd000001aa" "" "") `shouldBe` Left "The global map has a key whose type is not in its shortest form"
+      decodePsbt (tinyPsbt "" "03fd020001aa" "") `shouldBe` Left "Input 0 has a key whose type is not in its shortest form"
+      decodePsbt (tinyPsbt "" "" "09ff010000000000000001aa") `shouldBe` Left "Output 0 has a key whose type is not in its shortest form"
+
+    -- fe announces a type of four more bytes, and the key has one more
+    it "refuses a key that ends inside its type" $
+      decodePsbt (tinyPsbt "" "02fe0101aa" "") `shouldBe` Left "Input 0 has a key that ends inside its type"
+
+    -- Bitcoin Core reads no compact size above 0x02000000. fe00000003 is
+    -- 0x03000000, and ff0000000001000000 is 2^32.
+    it "refuses a key whose type is above the largest compact size Bitcoin Core reads" $ do
+      decodePsbt (tinyPsbt "" "05fe0000000301aa" "") `shouldBe` Left "Input 0 has a key whose type is beyond any type"
+      decodePsbt (tinyPsbt "" "09ff000000000100000001aa" "") `shouldBe` Left "Input 0 has a key whose type is beyond any type"
+
+    -- fdfd00 is the type 253 and fe00000002 the type 0x02000000, both in
+    -- their shortest form
+    it "reads a key whose type takes three or five bytes, and writes it back" $ do
+      (encodePsbt <$> decodePsbt (tinyPsbt "" "03fdfd0001aa" "")) `shouldBe` Right (tinyPsbt "" "03fdfd0001aa" "")
+      (encodePsbt <$> decodePsbt (tinyPsbt "" "05fe0000000201aa" "")) `shouldBe` Right (tinyPsbt "" "05fe0000000201aa" "")
+
+    -- The key is the type 0x02 and 33 bytes, 34 in all (0x22). The value is
+    -- a signature of nine bytes, the smallest BIP 66 allows, with SIGHASH_ALL.
+    it "refuses a partial signature under a key that is not a point of the curve" $
+      decodePsbt (tinyPsbt "" ("2202" <> notAPoint <> "09300602010102010101") "")
+        `shouldBe` Left ("Input 0: the key 0x02 with the data " <> T.unpack notAPoint <> " is not a public key")
+
+    it "reads a partial signature that is in the encoding of BIP 66 with a defined sighash byte" $
+      (encodePsbt <$> decodePsbt (tinyPsbt "" ("2202" <> aPoint <> "09300602010102010101") ""))
+        `shouldBe` Right (tinyPsbt "" ("2202" <> aPoint <> "09300602010102010101") "")
+
+    -- "garbage" in ASCII, then no value at all, then the signature above
+    -- with the sighash byte 0x04, which no node accepts
+    it "refuses a partial signature that is not in the encoding of BIP 66, or whose sighash byte is not defined" $ do
+      let refusal = Left ("Input 0: the value of the key 0x02 with the data " <> T.unpack aPoint <> " is not a signature in the encoding of BIP 66 with a defined sighash byte")
+      decodePsbt (tinyPsbt "" ("2202" <> aPoint <> "0767617262616765") "") `shouldBe` refusal
+      decodePsbt (tinyPsbt "" ("2202" <> aPoint <> "00") "") `shouldBe` refusal
+      decodePsbt (tinyPsbt "" ("2202" <> aPoint <> "09300602010102010104") "") `shouldBe` refusal
+
+    -- Each value ends with the sighash byte 0x01, which is defined, and
+    -- breaks one rule of BIP 66: bytes that are no DER at all, a length
+    -- byte that does not cover the signature (0x07 for 6 bytes), an R that
+    -- is negative (0x80), and an R with a zero byte it does not need (0001)
+    it "refuses a partial signature with a defined sighash byte that breaks a rule of BIP 66" $ do
+      let refusal = Left ("Input 0: the value of the key 0x02 with the data " <> T.unpack aPoint <> " is not a signature in the encoding of BIP 66 with a defined sighash byte")
+      decodePsbt (tinyPsbt "" ("2202" <> aPoint <> "0aaabbccddeeff00112201") "") `shouldBe` refusal
+      decodePsbt (tinyPsbt "" ("2202" <> aPoint <> "09300702010102010101") "") `shouldBe` refusal
+      decodePsbt (tinyPsbt "" ("2202" <> aPoint <> "09300602018002010101") "") `shouldBe` refusal
+      decodePsbt (tinyPsbt "" ("2202" <> aPoint <> "0a30070202000102010101") "") `shouldBe` refusal
+
+    -- The value is the fingerprint d90c6a4f and the path m/0'
+    it "refuses a derivation record under a key that is not a point of the curve, on an input and on an output" $ do
+      decodePsbt (tinyPsbt "" ("2206" <> notAPoint <> "08d90c6a4f00000080") "")
+        `shouldBe` Left ("Input 0: the key 0x06 with the data " <> T.unpack notAPoint <> " is not a public key")
+      decodePsbt (tinyPsbt "" "" ("2202" <> notAPoint <> "08d90c6a4f00000080"))
+        `shouldBe` Left ("Output 0: the key 0x02 with the data " <> T.unpack notAPoint <> " is not a public key")
+
+    -- BIP 32: a master key has depth 0, no parent fingerprint and the child
+    -- number 0. Bitcoin Core reads no other extended key of depth 0. Here
+    -- the child number 1, then the parent fingerprint 00000001.
+    it "refuses an extended public key of depth 0 that has a child number or a parent fingerprint" $ do
+      let xpubWith parent child =
+            "4f01" <> "0488b21e" <> "00" <> parent <> child <> T.replicate 32 "00" <> aPoint <> "04d90c6a4f"
+      decodePsbt (tinyPsbt (xpubWith "00000000" "00000001") "" "")
+        `shouldSatisfy` either ("is not an extended public key" `isSuffixOf`) (const False)
+      decodePsbt (tinyPsbt (xpubWith "00000001" "00000000") "" "")
+        `shouldSatisfy` either ("is not an extended public key" `isSuffixOf`) (const False)
+
+    -- BIP 174 gives a redeem script and a witness script as bytes, and
+    -- Bitcoin Core reads any. 4c is OP_PUSHDATA1 without its length.
+    it "reads a redeem script and a witness script that are no list of opcodes, on an input and on an output" $ do
+      let withScript =
+            [ tinyPsbt "" "0104014c" "",
+              tinyPsbt "" "0105014c" "",
+              tinyPsbt "" "" "0100014c",
+              tinyPsbt "" "" "0101014c"
+            ]
+      forM_ withScript $ \bytes ->
+        (encodePsbt <$> decodePsbt bytes) `shouldBe` Right bytes
+      (inputRedeemScript . inputAt 0 <$> decodePsbt (tinyPsbt "" "0104014c" ""))
+        `shouldBe` Right (Left "The redeem script is not a script: it does not decode")
+
+    -- One leaf at depth 0 of the leaf version 0xc0, whose script of one
+    -- byte is 4c: four bytes in all
+    it "reads a script tree whose leaf script is no list of opcodes" $ do
+      (encodePsbt <$> decodePsbt (tinyPsbt "" "" "01060400c0014c")) `shouldBe` Right (tinyPsbt "" "" "01060400c0014c")
+      (outputTapTree . outputAt 0 <$> decodePsbt (tinyPsbt "" "" "01060400c0014c"))
+        `shouldBe` Right (Left "The script tree has a leaf whose script is not a script: it does not decode")
+
+    -- The key is the type and the hash of the empty string by the
+    -- algorithm of the field, 21 bytes (0x15) or 33 (0x21). The value is
+    -- the empty string.
+    let ripemd160OfEmpty = "9c1185a5c5e9fc54612808977ee8f548b2258d31"
+        sha256OfEmpty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+        hash160OfEmpty = "b472a266d0bd89c13706a4132ccfb16f7c3b9fcb"
+        hash256OfEmpty = "5df6e0e2761359d30a8275058e299fcc0381534545f55cf43e41983f5d4c9456"
+        preimageKeys =
+          [("150a", ripemd160OfEmpty), ("210b", sha256OfEmpty), ("150c", hash160OfEmpty), ("210d", hash256OfEmpty)]
+
+    it "reads a hash preimage under its hash, for RIPEMD160, SHA256, HASH160 and HASH256" $
+      forM_ preimageKeys $ \(start, hash) ->
+        (encodePsbt <$> decodePsbt (tinyPsbt "" (start <> hash <> "00") ""))
+          `shouldBe` Right (tinyPsbt "" (start <> hash <> "00") "")
+
+    -- BIP 174: the preimage "must equal the key when run through" the
+    -- algorithm. The value is one byte of zero, under the hash of the
+    -- empty string.
+    it "refuses a hash preimage that does not hash to its key" $ do
+      let refusal t hash =
+            Left . mconcat $
+              [ "Input 0: the value of the key 0x" <> t <> " with the data " <> T.unpack hash,
+                " is not the preimage of the hash in its key"
+              ]
+      decodePsbt (tinyPsbt "" ("150a" <> ripemd160OfEmpty <> "0100") "") `shouldBe` refusal "0a" ripemd160OfEmpty
+      decodePsbt (tinyPsbt "" ("210b" <> sha256OfEmpty <> "0100") "") `shouldBe` refusal "0b" sha256OfEmpty
+      decodePsbt (tinyPsbt "" ("150c" <> hash160OfEmpty <> "0100") "") `shouldBe` refusal "0c" hash160OfEmpty
+      decodePsbt (tinyPsbt "" ("210d" <> hash256OfEmpty <> "0100") "") `shouldBe` refusal "0d" hash256OfEmpty
+
+    -- RIPEMD160 and HASH160 give 20 bytes, SHA256 and HASH256 give 32. Each
+    -- key here has 5 bytes of data.
+    it "refuses a hash preimage whose key is not a hash of the size of its algorithm" $ do
+      decodePsbt (tinyPsbt "" "060a11111111110100" "")
+        `shouldBe` Left "Input 0: the key 0x0a with the data 1111111111 is not a hash of 20 bytes"
+      decodePsbt (tinyPsbt "" "060b11111111110100" "")
+        `shouldBe` Left "Input 0: the key 0x0b with the data 1111111111 is not a hash of 32 bytes"
+      decodePsbt (tinyPsbt "" "060c11111111110100" "")
+        `shouldBe` Left "Input 0: the key 0x0c with the data 1111111111 is not a hash of 20 bytes"
+      decodePsbt (tinyPsbt "" "060d11111111110100" "")
+        `shouldBe` Left "Input 0: the key 0x0d with the data 1111111111 is not a hash of 32 bytes"
+
+    -- BIP 371 gives a signature as 64 or 65 bytes, and Bitcoin Core reads
+    -- any bytes of that length. The last bytes 0x00 and 0x04 name no
+    -- sighash type that BIP 341 allows, so no witness is made of these.
+    -- 0x41 is 65 bytes, and the key of a script path signature is the type
+    -- and 64 bytes, also 0x41.
+    it "reads a Taproot signature of 65 bytes whatever its last byte, as a key path and as a script path signature" $
+      forM_ ["00", "04"] $ \lastByte -> do
+        let keyPath = "0113" <> "41" <> T.replicate 64 "ab" <> lastByte
+            scriptPath = "4114" <> T.replicate 64 "22" <> "41" <> T.replicate 64 "ab" <> lastByte
+        (encodePsbt <$> decodePsbt (tinyPsbt "" keyPath "")) `shouldBe` Right (tinyPsbt "" keyPath "")
+        (encodePsbt <$> decodePsbt (tinyPsbt "" scriptPath "")) `shouldBe` Right (tinyPsbt "" scriptPath "")
+
+    -- The key is the type 0x01 and the 78 bytes of an extended key, 79 in
+    -- all (0x4f): the version 0488b21e, depth 0, no parent, index 0, a chain
+    -- code of zeros, and the public key
+    it "refuses an extended public key whose key is not a point of the curve" $ do
+      let xpubWith key = "4f01" <> "0488b21e" <> "00" <> "00000000" <> "00000000" <> T.replicate 32 "00" <> key <> "04d90c6a4f"
+      (encodePsbt <$> decodePsbt (tinyPsbt (xpubWith aPoint) "" "")) `shouldBe` Right (tinyPsbt (xpubWith aPoint) "" "")
+      decodePsbt (tinyPsbt (xpubWith notAPoint) "" "") `shouldSatisfy` either ("is not an extended public key" `isSuffixOf`) (const False)
+
+    -- 0x3d is the 61 bytes of the transaction
+    it "refuses a previous transaction that is not the one the input spends, in both versions" $ do
+      decodePsbt (tinyPsbt "" ("01003d" <> anotherTx) "") `shouldBe` Left "Input 0: the previous transaction is not the one the input spends"
+      decodePsbt (tinyPsbt2 ("01003d" <> anotherTx)) `shouldBe` Left "Input 0: the previous transaction is not the one the input spends"
+
+    -- An empty tree, then a leaf of the leaf version 0xc1, a leaf at depth
+    -- 129 (0x81), one leaf alone at depth 1, and three leaves at depth 1.
+    -- 0x25 is the 37 bytes of a leaf, 0x6f the 111 bytes of three.
+    it "refuses a script tree that is empty, has an odd leaf version, a leaf deeper than 128, or leaves that make no tree" $ do
+      decodePsbt (tinyPsbt "" "" "010600") `shouldBe` Left "Output 0: the value of the key 0x06 is an empty script tree"
+      decodePsbt (tinyPsbt "" "" ("010625" <> treeLeaf "00" "c1")) `shouldBe` Left "Output 0: the value of the key 0x06 has a leaf with an odd leaf version"
+      decodePsbt (tinyPsbt "" "" ("010625" <> treeLeaf "81" "c0")) `shouldBe` Left "Output 0: the value of the key 0x06 has a leaf deeper than 128"
+      decodePsbt (tinyPsbt "" "" ("010625" <> treeLeaf "01" "c0")) `shouldBe` Left "Output 0: the value of the key 0x06 is not a whole script tree"
+      decodePsbt (tinyPsbt "" "" ("01066f" <> treeLeaf "01" "c0" <> treeLeaf "01" "c0" <> treeLeaf "01" "c0")) `shouldBe` Left "Output 0: the value of the key 0x06 is not a whole script tree"
+
+    it "reads a script tree of one leaf at depth 0, and one of two leaves at depth 1" $ do
+      (encodePsbt <$> decodePsbt (tinyPsbt "" "" ("010625" <> treeLeaf "00" "c0"))) `shouldBe` Right (tinyPsbt "" "" ("010625" <> treeLeaf "00" "c0"))
+      (encodePsbt <$> decodePsbt (tinyPsbt "" "" ("01064a" <> treeLeaf "01" "c0" <> treeLeaf "01" "c0"))) `shouldBe` Right (tinyPsbt "" "" ("01064a" <> treeLeaf "01" "c0" <> treeLeaf "01" "c0"))
+
+    -- The length 1 of the value "aa", over five bytes and over nine
+    it "refuses a length written over five or nine bytes that is not in its shortest form" $ do
+      decodePsbt (hexBytes ("70736274ff" <> emptyTxEntry <> "0120" <> "fe01000000" <> "aa" <> "00")) `shouldBe` Left "A length in the global map is not in its shortest form"
+      decodePsbt (hexBytes ("70736274ff" <> emptyTxEntry <> "0120" <> "ff0100000000000000" <> "aa" <> "00")) `shouldBe` Left "A length in the global map is not in its shortest form"
+
+    -- The key is the type 0x15 and a control block of 33 bytes plus 32 per
+    -- node. 128 nodes make 4,130 bytes with the type (fd2210), and 129 make
+    -- 4,162 (fd4210). The value is a script of 34 bytes and the leaf version.
+    it "refuses a control block of 129 nodes, and reads one of 128" $ do
+      let leafEntry nodes len = len <> "15" <> "c0" <> T.replicate 32 "22" <> T.replicate (32 * nodes) "33" <> "23" <> "20" <> T.replicate 32 "22" <> "ac" <> "c0"
+      (B.length . encodePsbt <$> decodePsbt (tinyPsbt "" (leafEntry 128 "fd2210") "")) `shouldBe` Right (B.length (tinyPsbt "" (leafEntry 128 "fd2210") ""))
+      decodePsbt (tinyPsbt "" (leafEntry 129 "fd4210") "") `shouldSatisfy` either ("is not a control block" `isSuffixOf`) (const False)
+
+    -- An extended key of depth 0 has no path. The value is the fingerprint
+    -- and the one index 0'.
+    it "refuses an extended public key of depth 0 with a path of one index" $ do
+      let xpub = "4f01" <> "0488b21e" <> "00" <> "00000000" <> "00000000" <> T.replicate 32 "00" <> aPoint <> "08d90c6a4f00000080"
+      decodePsbt (tinyPsbt xpub "" "") `shouldSatisfy` either ("has a path that is not as deep as the key" `isSuffixOf`) (const False)
+
+    -- Two entries with the same key: the type 0x20 and 1,000 bytes of 0xab,
+    -- 1,001 in all (fde903)
+    it "names at most 40 bytes of the data of a key in a refusal, then its length" $ do
+      let entry = "fde903" <> "20" <> T.replicate 1000 "ab" <> "00"
+      decodePsbt (tinyPsbt (entry <> entry) "" "")
+        `shouldBe` Left ("The global map has the key 0x20 with the data " <> concat (replicate 40 "ab") <> "… (1000 bytes) twice")
+
+{- What the signer and the finalizer sign, and what they leave alone -}
+
+-- | A transaction that spends the two outputs of a previous transaction
+-- paying the two scripts, as a PSBT with that previous transaction on both
+-- inputs. Each output holds 2 BTC.
+spendingTwo :: ByteString -> ByteString -> Psbt
+spendingTwo scriptA scriptB = Psbt Version0 tx Map.empty [input, input] [Map.empty]
+  where
+    parent = Tx 1 [TxIn (OutPoint "e567952fb6cc33857f392efa3a46c995a28f69cca4bb1b37e0204dab1ec7a389" 1) "" 0xffffffff] [TxOut 200000000 scriptA, TxOut 200000000 scriptB] [] 0
+    tx = Tx 2 [TxIn (OutPoint (txHash parent) 0) "" 0xfffffffe, TxIn (OutPoint (txHash parent) 1) "" 0xfffffffe] [TxOut 399990000 (hexBytes "76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac")] [] 0
+    input = insertNonWitnessUtxo parent Map.empty
+
+signerScopeSpec :: Spec
+signerScopeSpec =
+  describe "What the signer and the finalizer sign, and what they leave alone" $ do
+    let secret = PrivateKey secretOne True
+        public = derivePublicKey secret
+        otherPublic = compressedKey secretTwo
+        signer = keySigner secretOne
+        ownScript = encodeSerial (PayPKHash (addressHash (encodeSerial public)))
+        otherScript = encodeSerial (PayPKHash (addressHash (encodeSerial otherPublic)))
+        (psbt, _) = spendingPsbt (PayPKHash (addressHash (encodeSerial public)))
+        parent = fromJust (either (const Nothing) id (nonWitnessUtxo (inputAt 0 psbt)))
+        coin = head parent.outputs
+        signatureCounts = mapM (fmap length . partialSignatures) . (.inputs)
+
+    -- BIP 32 gives a key a depth of one byte, so no key is 256 steps below
+    -- another
+    it "a signer built from an extended key holds no key for a record whose path has 256 steps" $ do
+      let master = makeXPrvKey "PSBT signer test"
+          tooDeep = Derivation (xPubFP (deriveXPubKey master)) (listToPath (replicate 256 0))
+      (xPrvSigner master Nothing).keyOfRecord public tooDeep `shouldBe` Nothing
+
+    it "signing leaves unsigned an input whose record names the signer's key with a path of 256 steps" $ do
+      let master = makeXPrvKey "PSBT signer test"
+          tooDeep = Derivation (xPubFP (deriveXPubKey master)) (listToPath (replicate 256 0))
+          withRecord = withInputs (insertInputDerivation public tooDeep <$> psbt.inputs) psbt
+      (signatureCounts =<< signPsbt btc (xPrvSigner master Nothing) withRecord) `shouldBe` Right [0]
+
+    -- The second record names a key the coin does not pay. A signer that
+    -- derives a key for every record can be made to work without end.
+    it "asks the signer for the key of a record only when the script of the coin names that key" $ do
+      let onlyOwn = signer {keyOfRecord = \asked _ -> if asked == public then Just secretOne else error "asked for the key of a record the coin does not name"}
+          withRecords = withInputs ((recordOf public . recordOf otherPublic) <$> psbt.inputs) psbt
+      (signatureCounts =<< signPsbt btc onlyOwn withRecords) `shouldBe` Right [1]
+
+    -- The coin pays the hash of key 2, and the record names key 1, which
+    -- the signer holds. BIP 174: "If a Signer cannot sign a transaction, it
+    -- must not add a Partial Signature."
+    it "adds no signature for a key the script of the coin does not name, even when a derivation record names it" $ do
+      let (other, _) = spendingPsbt (PayPKHash (addressHash (encodeSerial otherPublic)))
+      (signatureCounts =<< signPsbt btc signer (withInputs (recordOf public <$> other.inputs) other)) `shouldBe` Right [0]
+
+    it "adds no signature to a P2WSH coin whose witness script is missing, nor to a P2SH coin whose redeem script is missing" $ do
+      let multisig = forceRight (encodeOutput (PayMulSig [public, otherPublic] 2))
+          (p2wsh, _) = spendingPsbt (forceRight (toP2WSH multisig))
+          (p2sh, _) = spendingPsbt (forceRight (toP2SH multisig))
+      (signatureCounts =<< signPsbt btc signer (withInputs (recordOf public <$> p2wsh.inputs) p2wsh)) `shouldBe` Right [0]
+      (signatureCounts =<< signPsbt btc signer (withInputs (recordOf public <$> p2sh.inputs) p2sh)) `shouldBe` Right [0]
+
+    it "signs a P2SH-P2WPKH coin with its redeem script by the hash of its key, without a derivation record" $ do
+      let redeem = forceRight (encodeOutput (PayWitnessPKHash (addressHash (encodeSerial public))))
+          (nested, _) = spendingPsbt (forceRight (toP2SH redeem))
+      (signatureCounts =<< signPsbt btc signer (withInputs (insertInputRedeemScript redeem <$> nested.inputs) nested)) `shouldBe` Right [1]
+
+    -- 0x41 is SIGHASH_ALL (0x01) with SIGHASH_FORKID (0x40)
+    it "on the Bitcoin Cash networks, signs an input that asks for no sighash type with SIGHASH_ALL and the fork id flag" $
+      forM_ [bch, bchTest3, bchTest4, bchRegTest] $ \net ->
+        (map (B.last . snd) <$> (partialSignatures . inputAt 0 =<< signPsbt net signer psbt)) `shouldBe` Right [0x41]
+
+    -- Input 0 is a coin of key 1. Input 1 is a P2WSH coin of someone else,
+    -- whose witness script is <key 2> OP_CHECKSIGVERIFY <144>
+    -- OP_CHECKSEQUENCEVERIFY, which is no template the library knows.
+    it "signs and finalizes its own input, and leaves alone an input whose witness script is not a standard template" $ do
+      let timelocked = Script [opPushData (encodeSerial otherPublic), OP_CHECKSIGVERIFY, opPushData "\x90\x00", OP_CHECKSEQUENCEVERIFY]
+          both = spendingTwo ownScript (encodeSerial (forceRight (toP2WSH timelocked)))
+          withScript = withInputs [inputAt 0 both, insertInputWitnessScript timelocked (inputAt 1 both)] both
+      signed <- expectRight (signPsbt btc signer withScript)
+      signatureCounts signed `shouldBe` Right [1, 0]
+      inputAt 1 signed `shouldBe` inputAt 1 withScript
+      final <- expectRight (finalizePsbt btc signed)
+      map (isJust . finalScriptSig) final.inputs `shouldBe` [True, False]
+      inputAt 1 final `shouldBe` inputAt 1 withScript
+
+    -- One signature of the keys 1 and 2, each key pushed by OP_PUSHDATA1
+    -- (0x4c) and its length 0x21 = 33, where a multisig of the library has
+    -- the length alone. The signature of a multisig covers the bytes of the
+    -- script, and a 'ScriptOutput' has no place for the form of a push: the
+    -- signer would sign the script with direct pushes, which is another
+    -- script. So this one is no standard template, although the signer
+    -- holds key 1.
+    let longPushes =
+          Script
+            [ OP_1,
+              OP_PUSHDATA (hexBytes "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798") OPDATA1,
+              OP_PUSHDATA (hexBytes "02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5") OPDATA1,
+              OP_2,
+              OP_CHECKMULTISIG
+            ]
+
+    it "signs and finalizes its own input, and leaves alone a multisig coin whose keys are pushed by OP_PUSHDATA1" $ do
+      let both = spendingTwo ownScript (runPutS (serialize longPushes))
+          withRecord = withInputs [inputAt 0 both, recordOf public (inputAt 1 both)] both
+      signed <- expectRight (signPsbt btc signer withRecord)
+      signatureCounts signed `shouldBe` Right [1, 0]
+      inputAt 1 signed `shouldBe` inputAt 1 withRecord
+      final <- expectRight (finalizePsbt btc signed)
+      map (isJust . finalScriptSig) final.inputs `shouldBe` [True, False]
+      inputAt 1 final `shouldBe` inputAt 1 withRecord
+
+    it "adds no signature to a P2SH or P2WSH coin that commits to such a multisig, and gives no error" $ do
+      let (p2sh, _) = spendingPsbt (forceRight (toP2SH longPushes))
+          (p2wsh, _) = spendingPsbt (forceRight (toP2WSH longPushes))
+          withRedeem = withInputs (recordOf public . insertInputRedeemScript longPushes <$> p2sh.inputs) p2sh
+          withWitness = withInputs (recordOf public . insertInputWitnessScript longPushes <$> p2wsh.inputs) p2wsh
+      signPsbt btc signer withRedeem `shouldBe` Right withRedeem
+      signPsbt btc signer withWitness `shouldBe` Right withWitness
+
+    -- Bitcoin Core signs the bytes of the script, and a block may hold its
+    -- spend. The finalizer does not judge a signature of a script it does
+    -- not read.
+    it "the finalizer leaves alone such a multisig coin that holds a signature over the bytes of its script" $ do
+      let both = spendingTwo ownScript (runPutS (serialize longPushes))
+          digest = forceRight (txSigHash btc both.unsignedTx longPushes 200000000 1 sigHashAll)
+          signature = encodeTxSig btc (TxSignature (signHash secretOne digest) sigHashAll)
+          withSignature = withInputs [inputAt 0 both, insertPartialSignature public signature (inputAt 1 both)] both
+      finalizePsbt btc withSignature `shouldBe` Right withSignature
+
+    -- Input 1 is a P2PKH coin of key 2, known from its output alone. The
+    -- signer could not sign it anyway. Bitcoin Core leaves such an input
+    -- unsigned and signs the others.
+    it "leaves alone a legacy coin known from its witness output only when it holds no key for it, and signs its own input" $ do
+      let both = spendingTwo ownScript otherScript
+          witnessOnly = withInputs [inputAt 0 both, insertWitnessUtxo (TxOut 200000000 otherScript) Map.empty] both
+      (signatureCounts =<< signPsbt btc signer witnessOnly) `shouldBe` Right [1, 0]
+
+    -- Input 0 is a coin of key 1. Input 1 is a Taproot coin of someone
+    -- else, the coin of the BIP 371 vectors, with one entry that Bitcoin
+    -- Core 32.1 reads and that nobody can sign or finalize with. Core signs
+    -- input 0 of each. 79be…1798 is the x coordinate of the point G, and 5
+    -- is the x coordinate of no point of the curve: 5³ + 7 = 132 is not a
+    -- square modulo the field prime.
+    let theirTaproot = hexBytes "51205a2c2cf5b52cf31f83ad2e8da63ff03183ecd8f609c7510ae8a48e03910a0757"
+        pointG = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
+        noPoint = "0000000000000000000000000000000000000000000000000000000000000005"
+        -- A leaf hash that is the hash of no leaf, and 64 bytes that are
+        -- the signature of nobody
+        noLeaf = T.replicate 32 "cd"
+        noSignature = T.replicate 64 "ab"
+        -- What the entry is, the type of its key, the data of its key and
+        -- its value
+        unusable =
+          [ ("a leaf script that is cut short", 0x15, "c0" <> pointG, "4cc0"),
+            ("a leaf script whose control block names a key that is no point", 0x15, "c0" <> noPoint, "51c0"),
+            ("an internal key that is no point", 0x17, "", noPoint),
+            ("a derivation record of a key that is no point", 0x16, noPoint, "0000000000"),
+            ("a script path signature of a key that is no point", 0x14, noPoint <> noLeaf, noSignature)
+          ]
+
+    forM_ unusable $ \(what, keyType, keyData, value) ->
+      it ("signs and finalizes its own input, and leaves alone a Taproot coin of another party that has " <> what) $ do
+        let both = spendingTwo ownScript theirTaproot
+            entry = Map.insert (Key keyType (hexBytes keyData)) (hexBytes value)
+            withEntry = withInputs [inputAt 0 both, entry (inputAt 1 both)] both
+        decodePsbt (encodePsbt withEntry) `shouldBe` Right withEntry
+        signed <- expectRight (signPsbt btc signer withEntry)
+        signatureCounts signed `shouldBe` Right [1, 0]
+        inputAt 1 signed `shouldBe` inputAt 1 withEntry
+        final <- expectRight (finalizePsbt btc signed)
+        map (isJust . finalScriptSig) final.inputs `shouldBe` [True, False]
+        inputAt 1 final `shouldBe` inputAt 1 withEntry
+
+    -- A key path signature of a BIP 371 vector, for another transaction
+    let vectorSignature =
+          hexBytes
+            "bb53ec917bad9d906af1ba87181c48b86ace5aae2b53605a725ca74625631476\
+            \fc6f5baedaf4f2ee0f477f36f58f3970d5b8273b7e497b97af2e3f125c97af34"
+
+    -- Nobody can spend such a coin, with a signature or without one
+    it "signs and finalizes its own input, and leaves alone a Taproot coin whose output key is no point" $ do
+      let both = spendingTwo ownScript (hexBytes ("5120" <> noPoint))
+          claimed = withInputs [inputAt 0 both, Map.insert (Key 0x13 "") vectorSignature (inputAt 1 both)] both
+      forM_ [both, claimed] $ \psbt' -> do
+        signed <- expectRight (signPsbt btc signer psbt')
+        signatureCounts signed `shouldBe` Right [1, 0]
+        final <- expectRight (finalizePsbt btc signed)
+        map (isJust . finalScriptSig) final.inputs `shouldBe` [True, False]
+        inputAt 1 final `shouldBe` inputAt 1 psbt'
+
+    -- The parties of a PSBT add their coins in turn. Input 0 is a Taproot
+    -- coin of someone else, and the owner of input 1 has not added its coin
+    -- yet. A Taproot signature needs the coin of every input, and this
+    -- signer has none to make.
+    it "leaves alone a Taproot coin of another party while another input has no coin yet" $ do
+      let both = spendingTwo theirTaproot ownScript
+          waiting = withInputs [inputAt 0 both, Map.empty] both
+      signPsbt btc signer waiting `shouldBe` Right waiting
+
+    -- Input 0 is a legacy coin of the signer and input 1 a Taproot coin of
+    -- the signer. The owner of input 2 has not added its coin yet, and the
+    -- digest of a Taproot signature commits to the coin of every input.
+    -- Bitcoin Core signs input 0 and leaves input 1, and refuses nothing.
+    it "signs its legacy coin, and leaves its Taproot coin unsigned while another input has no coin yet" $ do
+      let keyPathCoin = forceRight (taprootScriptOutput (TaprootOutput public.point Nothing))
+          both = spendingTwo ownScript (encodeSerial keyPathCoin)
+          third = TxIn (OutPoint "e567952fb6cc33857f392efa3a46c995a28f69cca4bb1b37e0204dab1ec7a389" 0) "" 0xfffffffe
+          tx = Tx 2 (both.unsignedTx.inputs <> [third]) both.unsignedTx.outputs [] 0
+          ownTaproot = insertInputTapInternalKey public.point (inputAt 1 both)
+          waiting = Psbt Version0 tx Map.empty [inputAt 0 both, ownTaproot, Map.empty] both.outputs
+      signed <- expectRight (signPsbt btc signer waiting)
+      signatureCounts signed `shouldBe` Right [1, 0, 0]
+      drop 1 signed.inputs `shouldBe` [ownTaproot, Map.empty]
+
+    -- Without the coin of input 1 nobody can tell whether a Taproot
+    -- signature verifies, so the input is not ready, and Bitcoin Core
+    -- leaves it too.
+    it "the finalizer leaves alone a signed Taproot coin while another input has no coin yet" $ do
+      let both = spendingTwo theirTaproot ownScript
+          waiting = withInputs [Map.insert (Key 0x13 "") vectorSignature (inputAt 0 both), Map.empty] both
+      finalizePsbt btc waiting `shouldBe` Right waiting
+
+    -- Bitcoin Core refuses the whole PSBT too: a sighash type that the
+    -- caller did not ask for is a mismatch on any input that has its coin
+    it "refuses a PSBT in which another party's input asks for a sighash type the signer does not accept" $ do
+      let both = spendingTwo ownScript otherScript
+          asking = withInputs [inputAt 0 both, insertSigHashType (setAnyoneCanPay sigHashSingle) (inputAt 1 both)] both
+      signPsbt btc signer asking `shouldBe` Left "Input 1: the sighash type 131 is not one the signer accepts"
+
+    -- No node relays the spend of such a coin, and Bitcoin Core does not
+    -- sign it
+    it "adds no signature of an uncompressed key to a SegWit version 0 coin" $ do
+      let uncompressed = PublicKey public.point False
+          (p2wpkh, _) = spendingPsbt (PayWitnessPKHash (addressHash (encodeSerial uncompressed)))
+      signPsbt btc signer p2wpkh `shouldBe` Right p2wpkh
+
+    -- The signer of the library makes no such signature, so this one is
+    -- made here, as Bitcoin Core of an older version would have. It
+    -- verifies, and the input still may not be final.
+    it "the finalizer leaves alone a SegWit version 0 coin with a valid signature of an uncompressed key" $ do
+      let uncompressed = PublicKey public.point False
+          (p2wpkh, _) = spendingPsbt (PayWitnessPKHash (addressHash (encodeSerial uncompressed)))
+          scriptCode = forceRight (encodeOutput (PayPKHash (addressHash (encodeSerial uncompressed))))
+          digest = forceRight (txSigHashForkId btc p2wpkh.unsignedTx scriptCode 200000000 0 sigHashAll)
+          signature = encodeTxSig btc (TxSignature (signHash secretOne digest) sigHashAll)
+          claimed = withInputs (insertPartialSignature uncompressed signature <$> p2wpkh.inputs) p2wpkh
+      finalizePsbt btc claimed `shouldBe` Right claimed
+
+    -- The second signature is the one of key 1, filed under key 2: it does
+    -- not verify for key 2. The coin does not name key 2, so the finalizer
+    -- has no reason to look at it.
+    it "the finalizer does not look at a partial signature of a key the script of the coin does not name" $ do
+      signed <- expectRight (signPsbt btc signer psbt)
+      signature <- case partialSignatures (inputAt 0 signed) of
+        Right [(_, sig)] -> return sig
+        _ -> fail "one signature"
+      let withStray = withInputs (insertPartialSignature otherPublic signature <$> signed.inputs) signed
+      (finalScriptSig . inputAt 0 <$> finalizePsbt btc withStray) `shouldBe` (finalScriptSig . inputAt 0 <$> finalizePsbt btc signed)
+      (isJust . finalScriptSig . inputAt 0 <$> finalizePsbt btc withStray) `shouldBe` Right True
+
+    -- Bitcoin Core takes SIGHASH_ALL for an input that names no sighash
+    -- type, and gives no final script when a signature uses another
+    it "the finalizer leaves alone an input that names no sighash type and has a SIGHASH_NONE signature" $ do
+      let acceptingNone = signer {acceptedSigHashes = [sigHashNone]}
+      signed <- expectRight (signPsbt btc acceptingNone (withInputs (insertSigHashType sigHashNone <$> psbt.inputs) psbt))
+      let unnamed = withInputs (deleteSigHashType <$> signed.inputs) signed
+      finalizePsbt btc unnamed `shouldBe` Right unnamed
+
+    it "the finalizer leaves alone a signed legacy coin that is known from its witness output only" $ do
+      signed <- expectRight (signPsbt btc signer psbt)
+      let witnessOnly = withInputs [insertWitnessUtxo coin (Map.delete (Key 0x00 "") (inputAt 0 signed))] signed
+      finalizePsbt btc witnessOnly `shouldBe` Right witnessOnly
+
+    -- A signer written by a caller may answer with a key that is not the
+    -- one asked for. Its signature would be of no use to anyone.
+    it "signs with a key the signer gives only when it is the key the coin names" $ do
+      let wrongByRecord = signer {keyOfRecord = \_ _ -> Just secretTwo, keyOfHash = const Nothing}
+          wrongByHash = signer {keyOfRecord = \_ _ -> Nothing, keyOfHash = const (Just (PrivateKey secretTwo True))}
+          withRecord = withInputs (recordOf public <$> psbt.inputs) psbt
+      (signatureCounts =<< signPsbt btc wrongByRecord withRecord) `shouldBe` Right [0]
+      (signatureCounts =<< signPsbt btc wrongByHash psbt) `shouldBe` Right [0]
+
+    it "a signer of one key holds no key for the record of another key" $ do
+      let record = Derivation (fingerprintOf "00000000") "m/0"
+      (keySigner secretOne).keyOfRecord otherPublic record `shouldBe` Nothing
+      (keySigner secretOne).keyOfRecord public record `shouldBe` Just secretOne
+
+    -- The time lock 100 is below 500,000,000, so it would be read as a height
+    it "a constructor refuses an input whose map breaks the spec, such as a required time lock below 500000000" $ do
+      let modifiable = withFlags (Modifiable True True False 0) (withVersion Version2 (psbtOf (Tx 2 [] [] [] 0)))
+      addInput coinInput (Map.singleton (Key 0x11 "") (hexBytes "64000000")) modifiable
+        `shouldBe` Left "Input 0: the value of the key 0x11 is a time lock below 500000000"
+      addOutput paidOutput (Map.singleton (Key 0x06 "") "") modifiable
+        `shouldBe` Left "Output 0: the value of the key 0x06 is an empty script tree"
+      -- The previous transaction has one output, and the input spends its second
+      let previous = Tx 1 [coinInput] [paidOutput] [] 0
+      addInput (TxIn (OutPoint (txHash previous) 1) "" 0xffffffff) (insertNonWitnessUtxo previous Map.empty) modifiable
+        `shouldBe` Left "Input 0: the input spends an output its previous transaction does not have"
+      addInput (TxIn (OutPoint (txHash previous) 0) "" 0xffffffff) (insertNonWitnessUtxo emptyTx Map.empty) modifiable
+        `shouldBe` Left "Input 0: the previous transaction is not the one the input spends"
+
+    -- 0065cd1d is 500,000,000, the first lock time that is a time, and
+    -- ff64cd1d is 499,999,999
+    it "a required time lock of 500000000 is the lock time of the transaction, and one of 499999999 is refused" $ do
+      ((.unsignedTx.locktime) <$> decodePsbt (tinyPsbt2 "0111040065cd1d")) `shouldBe` Right 500000000
+      decodePsbt (tinyPsbt2 "011104ff64cd1d") `shouldBe` Left "Input 0: the value of the key 0x11 is a time lock below 500000000"
+
+{- One input at a time -}
+
+-- Bitcoin Core signs and finalizes a PSBT one input at a time
+-- (SignPSBTInput). An input that it cannot sign or finalize stays as it
+-- is, and the others go on. Its signer refuses a whole PSBT for a sighash
+-- type only. Each case here was given to Bitcoin Core 32.1 on regtest.
+inputByInputSpec :: Spec
+inputByInputSpec =
+  describe "The signer and the finalizer take one input at a time" $ do
+    let public = compressedKey secretOne
+        uncompressed = PublicKey public.point False
+        publicTwo = compressedKey secretTwo
+        publicThree = compressedKey secretThree
+        signer = keySigner secretOne
+        ownPkh = PayPKHash (addressHash (encodeSerial public))
+        ownWpkh = PayWitnessPKHash (addressHash (encodeSerial public))
+        theirPkh = PayPKHash (addressHash (encodeSerial publicTwo))
+        signatureCounts = mapM (fmap length . partialSignatures) . (.inputs)
+        leftAlone psbt = finalizePsbt btc psbt `shouldBe` Right psbt
+        signatureOf key psbt = fromJust . lookup key <$> expectRight (partialSignatures (inputAt 0 psbt))
+        -- 64 bytes that are the signature of nobody
+        noSignature = B.replicate 64 0xab
+
+    {- The signer -}
+
+    -- Input 1 is a coin of key 2 with a signature of the type SIGHASH_NONE,
+    -- and asks for no type, so it is signed with SIGHASH_ALL, the type 1
+    it
+      "the signer refuses a PSBT in which an input has a signature \
+      \of another sighash type than the one it is signed with"
+      $ do
+        let both = spendingTwo (encodeSerial ownPkh) (encodeSerial theirPkh)
+            acceptingNone = (keySigner secretTwo) {acceptedSigHashes = sigHashNone : defaultSigHashes}
+        let askingNone = withInputs [inputAt 0 both, insertSigHashType sigHashNone (inputAt 1 both)] both
+        asking <- expectRight (signPsbt btc acceptingNone askingNone)
+        signatureCounts asking `shouldBe` Right [0, 1]
+        signPsbt btc signer (onInputs deleteSigHashType asking)
+          `shouldBe` Left "Input 1: a signature of the input does not use the sighash type 1"
+
+    -- A Taproot signature of 65 bytes names its type in its last byte. An
+    -- input that asks for no type is signed with SIGHASH_DEFAULT, the type
+    -- 0, whose signatures have 64 bytes.
+    it "the signer refuses a PSBT whose Taproot input has a signature of 65 bytes and asks for no sighash type" $ do
+      let (keyOnly, _) = spendingPsbt (forceRight (taprootScriptOutput (TaprootOutput public.point Nothing)))
+          asking = onInputs (insertSigHashType sigHashAll . insertInputTapInternalKey public.point) keyOnly
+      signed <- expectRight (signPsbt btc signer asking)
+      signPsbt btc signer (onInputs deleteSigHashType signed)
+        `shouldBe` Left "Input 0: a signature of the input does not use the sighash type 0"
+
+    -- BIP 370 has a signer change the flags of version 2 "if the Signer
+    -- added a signature". Both coins are of key 2, one signed with ECDSA and
+    -- one a Taproot coin, and the signer holds key 1.
+    it "the signer leaves the flags of a version 2 PSBT as they are when it adds no signature" $ do
+      let theirKeyPath = forceRight (taprootScriptOutput (TaprootOutput publicTwo.point Nothing))
+      forM_ [theirPkh, theirKeyPath] $ \coin -> do
+        let open = withFlags (Modifiable True True False 0) (withVersion Version2 (fst (spendingPsbt coin)))
+        signPsbt btc signer open `shouldBe` Right open
+
+    -- The signature that is there is the one of key 2 for a coin of its
+    -- own, filed under key 1. Bitcoin Core does not sign again for a key
+    -- that has a signature.
+    it "the signer keeps the signature that an input has under its key already" $ do
+      theirs <-
+        signatureOf publicTwo =<< expectRight (signPsbt btc (keySigner secretTwo) (fst (spendingPsbt theirPkh)))
+      let already = onInputs (insertPartialSignature public theirs) (fst (spendingPsbt ownPkh))
+      signPsbt btc signer already `shouldBe` Right already
+
+    it
+      "the signer signs its coin that has its previous transaction, \
+      \and leaves its coin known from its witness output only"
+      $ do
+        let both = spendingTwo (encodeSerial ownWpkh) (encodeSerial ownWpkh)
+            witnessOutputOnly = insertWitnessUtxo (TxOut 200000000 (encodeSerial ownWpkh)) Map.empty
+            mixed = withInputs [inputAt 0 both, witnessOutputOnly] both
+        signed <- expectRight (signPsbt btc signer mixed)
+        signatureCounts signed `shouldBe` Right [1, 0]
+        inputAt 1 signed `shouldBe` inputAt 1 mixed
+
+    it "the signer signs a P2WSH multisig with its compressed key, and not with its uncompressed key" $ do
+      let multisig = forceRight (encodeOutput (PayMulSig [uncompressed, public, publicTwo] 2))
+          (p2wsh, _) = spendingPsbt (forceRight (toP2WSH multisig))
+      signed <- expectRight (signPsbt btc signer (onInputs (insertInputWitnessScript multisig) p2wsh))
+      (map fst <$> partialSignatures (inputAt 0 signed)) `shouldBe` Right [public]
+
+    -- The witness script of a P2WSH coin runs as a script: one that is a
+    -- witness program leaves two items, and no signature spends the coin
+    it
+      "the signer adds no signature to a P2WSH coin whose witness script \
+      \is a P2WPKH program, and the finalizer leaves a signed one alone"
+      $ do
+        let program = forceRight (encodeOutput ownWpkh)
+            (nested, _) = spendingPsbt (forceRight (toP2WSH program))
+            withScript = onInputs (insertInputWitnessScript program) nested
+        signPsbt btc signer withScript `shouldBe` Right withScript
+        signature <- signatureOf public =<< expectRight (signPsbt btc signer (fst (spendingPsbt ownWpkh)))
+        leftAlone (onInputs (insertPartialSignature public signature) withScript)
+
+    -- A multisig of 8 uncompressed keys is 3 + 8 × 66 = 531 bytes, over
+    -- the 520 bytes that a transaction can push, so nothing spends the
+    -- coin. Bitcoin Core adds a signature all the same, and makes no final
+    -- script of it. The library does not sign what cannot be spent, as
+    -- 'makeSignature' refuses it.
+    it "the signer adds no signature to a P2SH coin whose redeem script is longer than 520 bytes" $ do
+      let uncompressedTwo = PublicKey publicTwo.point False
+          long = forceRight (encodeOutput (PayMulSig (uncompressed : replicate 7 uncompressedTwo) 1))
+          (p2sh, _) = spendingPsbt (PayScriptHash (addressHash (runPutS (serialize long))))
+      B.length (runPutS (serialize long)) `shouldBe` 531
+      signPsbt btc signer (onInputs (insertInputRedeemScript long) p2sh)
+        `shouldBe` Right (onInputs (insertInputRedeemScript long) p2sh)
+
+    -- 2,100,000,000,000,000 satoshi are 21 million bitcoin, all there will
+    -- be. Bitcoin Core makes no SegWit version 0 signature above it.
+    it "the signer adds no signature to a SegWit version 0 coin that holds more than 21 million bitcoin" $ do
+      let (psbt, _) = spendingPsbt ownWpkh
+          trusting = signer {requirePreviousTx = False}
+          claiming amount = withInputs [insertWitnessUtxo (TxOut amount (encodeSerial ownWpkh)) Map.empty] psbt
+      (signatureCounts =<< signPsbt btc trusting (claiming 2100000000000000)) `shouldBe` Right [1]
+      signPsbt btc trusting (claiming 2100000000000001) `shouldBe` Right (claiming 2100000000000001)
+
+    -- 4c is OP_PUSHDATA1 without its length: a script that does not parse
+    it "the signer refuses a sighash type that it does not accept on an input whose coin script does not parse" $ do
+      let both = spendingTwo (encodeSerial ownPkh) "\x4c"
+          asking = withInputs [inputAt 0 both, insertSigHashType sigHashNone (inputAt 1 both)] both
+      (signatureCounts =<< signPsbt btc signer both) `shouldBe` Right [1, 0]
+      signPsbt btc signer asking `shouldBe` Left "Input 1: the sighash type 2 is not one the signer accepts"
+
+    {- The signer, on Taproot coins -}
+
+    -- A coin with the leaf of key 1 under the internal key of key 2, and
+    -- one with the same leaf under the internal key of key 1
+    let leaf = Script [opPushData (exportXOnlyPubKey public.point), OP_CHECKSIG]
+        other = Script [OP_RETURN]
+        treeUnder internal = onInputs fields psbt
+          where
+            tree = MASTBranch (MASTLeaf 0xc0 leaf) (MASTLeaf 0xc0 other)
+            output = TaprootOutput internal (Just tree)
+            parity = keyParity (forceRight (taprootOutputKey output))
+            control = encodeControlBlock (0xc0 + parity) internal [leafHash 0xc0 other]
+            (psbt, _) = spendingPsbt (forceRight (taprootScriptOutput output))
+            fields =
+              insertInputTapInternalKey internal
+                . insertInputTapMerkleRoot (mastCommitment tree)
+                . insertTapLeafScript (TapLeafScript control leaf 0xc0)
+        keyPathSigned = fmap isJust . tapKeySig . inputAt 0
+        leavesSigned = fmap length . tapScriptSigs . inputAt 0
+
+    it "the signer signs the leaf of its key on a Taproot coin whose internal key it does not hold" $ do
+      signed <- expectRight (signPsbt btc signer (treeUnder publicTwo.point))
+      (keyPathSigned signed, leavesSigned signed) `shouldBe` (Right False, Right 1)
+
+    it "the signer signs the key path alone when it holds the internal key and the key of a leaf" $ do
+      signed <- expectRight (signPsbt btc signer (treeUnder public.point))
+      (keyPathSigned signed, leavesSigned signed) `shouldBe` (Right True, Right 0)
+
+    it
+      "the signer signs no leaf of a Taproot input that has \
+      \a key path signature already, and keeps that signature"
+      $ do
+        let already = onInputs (Map.insert (Key 0x13 "") noSignature) (treeUnder publicTwo.point)
+        signPsbt btc signer already `shouldBe` Right already
+
+    it "the signer keeps the key path signature that a Taproot input has already, when it holds the internal key" $ do
+      let already = onInputs (Map.insert (Key 0x13 "") noSignature) (treeUnder public.point)
+      signPsbt btc signer already `shouldBe` Right already
+
+    it "the signer keeps the signature that a leaf has under its key already" $ do
+      let entry = Key 0x14 (exportXOnlyPubKey public.point <> convert (leafHash 0xc0 leaf))
+          already = onInputs (Map.insert entry noSignature) (treeUnder publicTwo.point)
+      signPsbt btc signer already `shouldBe` Right already
+
+    -- 5120 and the x coordinate of key 1: a coin whose output key is key 1
+    -- itself, as the descriptor rawtr() makes one
+    it
+      "the signer signs the key path of a Taproot coin whose output \
+      \key is its own key, when the input names no internal key"
+      $ do
+        let (raw, coins) = spendingPsbt (PayWitness 1 (exportXOnlyPubKey public.point))
+        tx <- expectRight (psbtTransaction =<< finalizePsbt btc =<< signPsbt btc signer raw)
+        verifyStdTx btc tx coins `shouldBe` True
+
+    -- Two coins of the signer and one output: input 1 has no output at its
+    -- index, and BIP 341 gives SIGHASH_SINGLE no digest there
+    it
+      "the signer signs the Taproot input that has an output at its \
+      \index for SIGHASH_SINGLE, and leaves the one that has none"
+      $ do
+        let coin = encodeSerial (PayWitness 1 (exportXOnlyPubKey public.point))
+            asking = onInputs (insertSigHashType sigHashSingle) (spendingTwo coin coin)
+        signed <- expectRight (signPsbt btc (signer {acceptedSigHashes = [sigHashSingle]}) asking)
+        mapM (fmap isJust . tapKeySig) signed.inputs `shouldBe` Right [True, False]
+        inputAt 1 signed `shouldBe` inputAt 1 asking
+
+    -- Bitcoin Cash has no SegWit and no Taproot: the script is one that
+    -- anyone can spend there
+    it
+      "on Bitcoin Cash, the signer and the finalizer leave \
+      \alone a coin whose script has the form of a Taproot output"
+      $ do
+        let (raw, _) = spendingPsbt (PayWitness 1 (exportXOnlyPubKey public.point))
+        signPsbt bch signer raw `shouldBe` Right raw
+        signedOnBitcoin <- expectRight (signPsbt btc signer raw)
+        finalizePsbt bch signedOnBitcoin `shouldBe` Right signedOnBitcoin
+
+    {- The finalizer -}
+
+    it
+      "the finalizer finalizes the input that is ready, and \
+      \leaves alone the input whose signature does not verify"
+      $ do
+        let both = spendingTwo (encodeSerial ownPkh) (encodeSerial ownPkh)
+        signed <- expectRight (signPsbt btc signer both)
+        first <- signatureOf public signed
+        -- The signature of input 0, on input 1
+        let swapped = withInputs [inputAt 0 signed, insertPartialSignature public first (inputAt 1 signed)] signed
+        final <- expectRight (finalizePsbt btc swapped)
+        map (isJust . finalScriptSig) final.inputs `shouldBe` [True, False]
+        inputAt 1 final `shouldBe` inputAt 1 swapped
+
+    -- A P2WSH coin of two signatures of the keys 1, 2 and 3, signed by all
+    -- three
+    let multisig = forceRight (encodeOutput (PayMulSig [public, publicTwo, publicThree] 2))
+        (twoOfThree, twoOfThreeCoins) = spendingPsbt (forceRight (toP2WSH multisig))
+        allThree = keysSigner [PrivateKey secretOne True, PrivateKey secretTwo True, PrivateKey secretThree True]
+        signedByAll = expectRight (signPsbt btc allThree (onInputs (insertInputWitnessScript multisig) twoOfThree))
+
+    -- Bitcoin Core takes the first signatures in the order of the keys of
+    -- the script, and does not try another choice when its witness fails
+    it
+      "the finalizer takes the signatures of the first keys of a multisig, \
+      \and leaves the input alone when one of them does not verify"
+      $ do
+        signed <- signedByAll
+        second <- signatureOf publicTwo signed
+        leftAlone (onInputs (insertPartialSignature public second) signed)
+
+    -- The witness of a P2WSH multisig: an empty item, the signatures, the
+    -- witness script
+    it "the finalizer does not look at a signature of a multisig that it does not use" $ do
+      signed <- signedByAll
+      first <- signatureOf public signed
+      second <- signatureOf publicTwo signed
+      final <- expectRight (finalizePsbt btc (onInputs (insertPartialSignature publicThree first) signed))
+      finalScriptWitness (inputAt 0 final) `shouldBe` Right (Just ["", first, second, runPutS (serialize multisig)])
+      (flip (verifyStdTx btc) twoOfThreeCoins <$> psbtTransaction final) `shouldBe` Right True
+
+    -- BIP 174 has the signer check the scripts of an input, and says
+    -- nothing of them to the finalizer. Bitcoin Core finalizes.
+    it
+      "the finalizer finalizes a P2WPKH coin that also has a redeem \
+      \script and a witness script, which such a coin does not use"
+      $ do
+        let (plain, coins) = spendingPsbt ownWpkh
+        signed <- expectRight (signPsbt btc signer plain)
+        let stray = onInputs (insertInputRedeemScript multisig . insertInputWitnessScript multisig) signed
+        tx <- expectRight (psbtTransaction =<< finalizePsbt btc stray)
+        verifyStdTx btc tx coins `shouldBe` True
+
+    -- The input asks for no type, so its signatures are of SIGHASH_ALL,
+    -- and a Taproot signature of 64 bytes is of SIGHASH_DEFAULT
+    it "the finalizer leaves alone a signed P2WPKH coin that also has a Taproot signature of 64 bytes" $ do
+      signed <- expectRight (signPsbt btc signer (fst (spendingPsbt ownWpkh)))
+      leftAlone (onInputs (Map.insert (Key 0x13 "") noSignature) signed)
+
+    -- BIP 174: the finalizer "must fail to finalize that input if any
+    -- signature does not match the specified sighash type"
+    it "the finalizer leaves alone an input that asks for the sighash type 0 and has a SIGHASH_ALL signature" $ do
+      signed <- expectRight (signPsbt btc signer (fst (spendingPsbt ownWpkh)))
+      leftAlone (onInputs (insertSigHashType sigHashDefault) signed)
+
+    -- The same rule on a Taproot coin. Its key path signature has 64 bytes,
+    -- so it is of the type 0. The partial signature is one of key 1 for
+    -- another coin, of the type SIGHASH_ALL. Bitcoin Core does not look at
+    -- it, and finalizes the input.
+    it "the finalizer leaves alone a Taproot input that asks for the sighash type 0 and has a partial signature" $ do
+      let (keyOnly, _) = spendingPsbt (forceRight (taprootScriptOutput (TaprootOutput public.point Nothing)))
+          asking = onInputs (insertSigHashType sigHashDefault . insertInputTapInternalKey public.point) keyOnly
+      signed <- expectRight (signPsbt btc signer asking)
+      -- Without the partial signature, the witness is the key path signature
+      (fmap (fmap length) . finalScriptWitness . inputAt 0 =<< finalizePsbt btc signed) `shouldBe` Right (Just 1)
+      stray <- signatureOf public =<< expectRight (signPsbt btc signer (fst (spendingPsbt ownPkh)))
+      leftAlone (onInputs (insertPartialSignature public stray) signed)
+
+    it "the finalizer clears the fields of the signers from an input that is final already" $ do
+      signed <- expectRight (signPsbt btc signer (fst (spendingPsbt ownPkh)))
+      final <- expectRight (finalizePsbt btc signed)
+      hasPartialSignatures (inputAt 0 final) `shouldBe` False
+      finalizePsbt btc (onInputs (Map.union (inputAt 0 signed)) final) `shouldBe` Right final
+
+    -- BIP 174 has the finalizer clear every field of an input but its coin
+    -- and the keys that the spec does not define. The types 0x0a to 0x0d
+    -- are the four hash preimages, and 0x1a to 0x1c the MuSig2 fields.
+    it "the finalizer clears the hash preimages and the MuSig2 fields from the input that it finalizes" $ do
+      signed <- expectRight (signPsbt btc signer (fst (spendingPsbt ownPkh)))
+      let extra = Map.fromList [(Key t "", "") | t <- [0x0a, 0x0b, 0x0c, 0x0d, 0x1a, 0x1b, 0x1c]]
+      final <- expectRight (finalizePsbt btc signed)
+      Map.keys (inputAt 0 final) `shouldBe` [Key 0x00 "", Key 0x07 ""]
+      finalizePsbt btc (onInputs (Map.union extra) signed) `shouldBe` Right final
+
+    {- The finalizer, on Taproot coins -}
+
+    -- A coin under the internal key of key 3. The leaf of key 1 is at depth
+    -- 1, with a control block of 65 bytes. The leaf of key 2 is at depth 2,
+    -- with one of 97 bytes. Both are signed.
+    let near = Script [opPushData (exportXOnlyPubKey public.point), OP_CHECKSIG]
+        far = Script [opPushData (exportXOnlyPubKey publicTwo.point), OP_CHECKSIG]
+        twoDepths =
+          MASTBranch (MASTLeaf 0xc0 near) (MASTBranch (MASTLeaf 0xc0 far) (MASTLeaf 0xc0 (Script [OP_RETURN])))
+        deepOutput = TaprootOutput publicThree.point (Just twoDepths)
+        controlOf script =
+          head
+            [ encodeControlBlock (0xc0 + keyParity (forceRight (taprootOutputKey deepOutput))) publicThree.point proof
+            | (_, s, proof) <- getMerkleProofs twoDepths,
+              s == script
+            ]
+        (deep, _) = spendingPsbt (forceRight (taprootScriptOutput deepOutput))
+        bothLeaves =
+          insertTapLeafScript (TapLeafScript (controlOf near) near 0xc0)
+            . insertTapLeafScript (TapLeafScript (controlOf far) far 0xc0)
+        bothKeys = keysSigner [PrivateKey secretOne True, PrivateKey secretTwo True]
+        signedLeaves = expectRight (signPsbt btc bothKeys (onInputs bothLeaves deep))
+        signatureOfLeaf point script psbt =
+          encodeTaprootSig . fromJust . lookup (point, leafHash 0xc0 script)
+            <$> expectRight (tapScriptSigs (inputAt 0 psbt))
+
+    -- Bitcoin Core takes the smallest witness
+    it "the finalizer spends a Taproot coin by the signed leaf that has the shortest control block" $ do
+      signed <- signedLeaves
+      signature <- signatureOfLeaf public.point near signed
+      (B.length (controlOf near), B.length (controlOf far)) `shouldBe` (65, 97)
+      final <- expectRight (finalizePsbt btc signed)
+      finalScriptWitness (inputAt 0 final)
+        `shouldBe` Right (Just [signature, runPutS (serialize near), controlOf near])
+
+    -- The leaf of key 1 is listed under a second control block, of 97
+    -- bytes, which commits it to no coin and comes first by its bytes.
+    -- Bitcoin Core takes the shortest control block of a leaf.
+    it "the finalizer takes the shortest control block of a leaf that the input lists under two" $ do
+      signed <- signedLeaves
+      signature <- signatureOfLeaf public.point near signed
+      let stray = B.cons 0xc0 (B.replicate 96 0)
+          listedTwice = Map.insert (Key 0x15 stray) (runPutS (serialize near) <> "\xc0")
+      (stray < controlOf near) `shouldBe` True
+      final <- expectRight (finalizePsbt btc (onInputs listedTwice signed))
+      finalScriptWitness (inputAt 0 final)
+        `shouldBe` Right (Just [signature, runPutS (serialize near), controlOf near])
+
+    -- The leaf of key 1 now has a control block of 65 bytes that commits
+    -- it to another tree. Bitcoin Core takes the smallest witness, which
+    -- fails, and does not try the other leaf.
+    it
+      "the finalizer does not try another leaf when the signed leaf \
+      \with the shortest control block is not committed to the coin"
+      $ do
+        signed <- signedLeaves
+        let stray = encodeControlBlock 0xc0 publicThree.point [leafHash 0xc0 (Script [OP_RETURN])]
+            moved =
+              Map.insert (Key 0x15 stray) (runPutS (serialize near) <> "\xc0")
+                . Map.delete (Key 0x15 (controlOf near))
+        leftAlone (onInputs moved signed)
+
+    it
+      "the finalizer leaves alone a Taproot input whose key path \
+      \signature does not verify, although a signed leaf would spend it"
+      $ do
+        signed <- signedLeaves
+        leftAlone (onInputs (Map.insert (Key 0x13 "") noSignature) signed)
+
+    -- 5 is the x coordinate of no point of the curve. A leaf that checks
+    -- such a key has the form of a leaf of one key, and Bitcoin Core takes
+    -- it when it has an entry of a signature and the shortest control
+    -- block.
+    it
+      "the finalizer does not try another leaf when the signed leaf \
+      \with the shortest control block checks a key that is no point"
+      $ do
+        let noPoint = B.replicate 31 0x00 <> "\x05"
+            noKeyLeaf = Script [opPushData noPoint, OP_CHECKSIG]
+            tree =
+              MASTBranch
+                (MASTLeaf 0xc0 noKeyLeaf)
+                (MASTBranch (MASTLeaf 0xc0 far) (MASTLeaf 0xc0 (Script [OP_RETURN])))
+            output = TaprootOutput publicThree.point (Just tree)
+            control script =
+              head
+                [ encodeControlBlock (0xc0 + keyParity (forceRight (taprootOutputKey output))) publicThree.point proof
+                | (_, s, proof) <- getMerkleProofs tree,
+                  s == script
+                ]
+            (psbt, _) = spendingPsbt (forceRight (taprootScriptOutput output))
+            entries =
+              insertTapLeafScript (TapLeafScript (control noKeyLeaf) noKeyLeaf 0xc0)
+                . insertTapLeafScript (TapLeafScript (control far) far 0xc0)
+            claimed = Map.insert (Key 0x14 (noPoint <> convert (leafHash 0xc0 noKeyLeaf))) noSignature
+        signed <- expectRight (signPsbt btc (keySigner secretTwo) (onInputs entries psbt))
+        (fmap length . tapScriptSigs . inputAt 0) signed `shouldBe` Right 1
+        (isJust <$>) . finalScriptWitness . inputAt 0 <$> finalizePsbt btc signed `shouldBe` Right (Right True)
+        leftAlone (onInputs claimed signed)
+
+{- The checks on Taproot signatures -}
+
+-- | The PSBT with each of its input maps changed
+onInputs :: (PsbtMap -> PsbtMap) -> Psbt -> Psbt
+onInputs f psbt = withInputs (f <$> psbt.inputs) psbt
+
+-- | The map with the entries of one key type changed
+onKeyType :: Word8 -> (Key -> ByteString -> (Key, ByteString)) -> PsbtMap -> PsbtMap
+onKeyType t f m = Map.fromList [if key.keyType == t then f key value else (key, value) | (key, value) <- Map.toList m]
+
+-- | Bytes with their last bit flipped
+flipLastBit :: ByteString -> ByteString
+flipLastBit bytes = B.init bytes <> B.singleton (B.last bytes `xor` 1)
+
+-- | An entry with the last bit of its value flipped, and one with the last
+-- bit of the data of its key flipped
+flipValue, flipKeyData :: Key -> ByteString -> (Key, ByteString)
+flipValue key value = (key, flipLastBit value)
+flipKeyData key value = (Key key.keyType (flipLastBit key.keyData), value)
+
+taprootChecksSpec :: Vectors371 -> Spec
+taprootChecksSpec vectors =
+  describe "The checks on Taproot signatures" $ do
+    let vectorAt i = psbtOfVector (vectors.accepted371 !! i)
+        internal = derivePubKey secretOne
+        leafKey = derivePubKey secretTwo
+        leaf = Script [opPushData (exportXOnlyPubKey leafKey), OP_CHECKSIG]
+        tree = MASTBranch (MASTLeaf 0xc0 leaf) (MASTLeaf 0xc0 (Script [OP_RETURN]))
+        output = TaprootOutput internal (Just tree)
+        parity = keyParity (forceRight (taprootOutputKey output))
+        control = encodeControlBlock (0xc0 + parity) internal [leafHash 0xc0 (Script [OP_RETURN])]
+        (withTree, _) = spendingPsbt (forceRight (taprootScriptOutput output))
+        treeFields = insertInputTapInternalKey internal . insertInputTapMerkleRoot (mastCommitment tree) . insertTapLeafScript (TapLeafScript control leaf 0xc0)
+        derivation = Derivation (fingerprintOf "d90c6a4f") "m/86'/0'/0'/0/0"
+        -- A signer that finds its keys by derivation record only, as one
+        -- built from an extended key does
+        byRecord secret = (keySigner secret) {keyOfHash = const Nothing}
+
+        leftAlone psbt = finalizePsbt btc psbt `shouldBe` Right psbt
+        witnessItems = fmap (fmap length) . finalScriptWitness . inputAt 0
+
+    -- A key path spend has one witness item, and the script path spend of
+    -- the vector three: the signature, the script and the control block
+    it "the finalizer finalizes the key path and the script path of the BIP 371 vectors" $ do
+      keyPath <- vectorAt 1
+      scriptPath <- vectorAt 5
+      (witnessItems <$> finalizePsbt btc keyPath) `shouldBe` Right (Right (Just 1))
+      (witnessItems <$> finalizePsbt btc scriptPath) `shouldBe` Right (Right (Just 3))
+
+    it "the finalizer leaves alone an input whose key path signature does not verify" $ do
+      psbt <- vectorAt 1
+      leftAlone (onInputs (onKeyType 0x13 flipValue) psbt)
+
+    it "the finalizer leaves alone an input whose script path signature does not verify" $ do
+      psbt <- vectorAt 5
+      leftAlone (onInputs (onKeyType 0x14 flipValue) psbt)
+
+    it "the finalizer leaves alone a signed leaf whose control block does not commit it to the output key" $ do
+      psbt <- vectorAt 5
+      leftAlone (onInputs (onKeyType 0x15 flipKeyData) psbt)
+
+    -- The signatures of both vectors are 64 bytes, which is SIGHASH_DEFAULT
+    it "the finalizer leaves alone a Taproot input whose signature does not use the sighash type the input names" $ do
+      keyPath <- vectorAt 1
+      scriptPath <- vectorAt 5
+      leftAlone (onInputs (insertSigHashType sigHashAll) keyPath)
+      leftAlone (onInputs (insertSigHashType sigHashAll) scriptPath)
+
+    -- Bitcoin Core takes SIGHASH_DEFAULT for a Taproot input that names no
+    -- sighash type, and then wants every signature to be 64 bytes
+    it "the finalizer leaves alone an input that names no sighash type and has a SIGHASH_ALL key path signature" $ do
+      let (keyOnly, _) = spendingPsbt (forceRight (taprootScriptOutput (TaprootOutput internal Nothing)))
+          asking = onInputs (insertSigHashType sigHashAll . insertInputTapInternalKey internal) keyOnly
+      signed <- expectRight (signPsbt btc (keySigner secretOne) asking)
+      (fmap (fmap (.hash)) . tapKeySig . inputAt 0) signed `shouldBe` Right (Just sigHashAll)
+      leftAlone (onInputs deleteSigHashType signed)
+
+    it "the signer refuses a Taproot coin that asks for a sighash type the signer does not accept" $ do
+      let (keyOnly, _) = spendingPsbt (forceRight (taprootScriptOutput (TaprootOutput internal Nothing)))
+      signPsbt btc (keySigner secretOne) (onInputs (insertSigHashType sigHashSingle . insertInputTapInternalKey internal) keyOnly)
+        `shouldBe` Left "Input 0: the sighash type 3 is not one the signer accepts"
+
+    -- BIP 371: the leaf hashes of a record "are of the leaves which involve
+    -- this public key". A key that is the internal key and also a leaf key
+    -- has a record with a leaf hash, and Bitcoin Core writes it that way.
+    it "signs the key path of a Taproot coin when the record of its internal key lists a leaf" $ do
+      let record = insertInputTapDerivation internal (TapDerivation [leafHash 0xc0 leaf] derivation)
+      signed <- expectRight (signPsbt btc (byRecord secretOne) (onInputs (record . treeFields) withTree))
+      (fmap isJust . tapKeySig . inputAt 0) signed `shouldBe` Right True
+
+    -- Bitcoin Core finds the key of a leaf by the record of the key, and
+    -- does not read the leaves that the record lists
+    it "signs a leaf with the key of a record of that key, whichever leaves the record lists" $ do
+      let listing hashes = insertInputTapDerivation leafKey (TapDerivation hashes derivation)
+          signatures f = fmap length . tapScriptSigs . inputAt 0 =<< signPsbt btc (byRecord secretTwo) (onInputs (f . treeFields) withTree)
+      signatures (listing [leafHash 0xc0 leaf]) `shouldBe` Right 1
+      signatures (listing [leafHash 0xc0 (Script [OP_RETURN])]) `shouldBe` Right 1
+      signatures (listing []) `shouldBe` Right 1
+      signatures id `shouldBe` Right 0
+
+    -- The leaf is in no tree of the coin: its control block names another
+    -- internal key. Bitcoin Core signs each leaf that an input lists and
+    -- does not read the control block. The signature is for this input and
+    -- this leaf alone, so it spends nothing, and the finalizer makes no
+    -- witness of it.
+    it
+      "signs a leaf that the input lists whatever its control \
+      \block commits to, and the finalizer leaves that input alone"
+      $ do
+        let stray = encodeControlBlock 0xc0 leafKey [leafHash 0xc0 (Script [OP_RETURN])]
+            fields = insertInputTapInternalKey internal . insertInputTapMerkleRoot (mastCommitment tree) . insertTapLeafScript (TapLeafScript stray leaf 0xc0)
+        signed <- expectRight (signPsbt btc (keySigner secretTwo) (onInputs fields withTree))
+        (fmap length . tapScriptSigs . inputAt 0) signed `shouldBe` Right 1
+        leftAlone signed
+
+    -- A signer written by a caller may answer with a key that is not the
+    -- one asked for. Its signature would verify for no key of the coin.
+    -- The input names key 1 as its internal key and key 2 in its leaf, each
+    -- with a record, and the signer answers with key 3.
+    it "signs neither the key path nor a leaf with a key the signer gives when it is not the key asked for" $ do
+      let records =
+            insertInputTapDerivation internal (TapDerivation [] derivation)
+              . insertInputTapDerivation leafKey (TapDerivation [leafHash 0xc0 leaf] derivation)
+          unsigned = onInputs (records . treeFields) withTree
+          wrongByRecord = (keySigner secretThree) {keyOfRecord = \_ _ -> Just secretThree, keyOfHash = const Nothing}
+          keyThree = PrivateKey secretThree True
+          wrongByHash = (keySigner secretThree) {keyOfRecord = \_ _ -> Nothing, keyOfHash = const (Just keyThree)}
+      signPsbt btc wrongByRecord unsigned `shouldBe` Right unsigned
+      signPsbt btc wrongByHash unsigned `shouldBe` Right unsigned
+
+    -- A coin whose tree holds the leaf of key 2 with the first leaf
+    -- version, and an input that has this leaf under a control block with
+    -- the second leaf version, and names the third in its value. The record
+    -- of key 2 lists the hash of the leaf with the third.
+    let leafOfVersion inTree inControl named = onInputs fields psbt
+          where
+            treeOf = MASTBranch (MASTLeaf inTree leaf) (MASTLeaf 0xc0 (Script [OP_RETURN]))
+            outputOf = TaprootOutput internal (Just treeOf)
+            parity = keyParity (forceRight (taprootOutputKey outputOf))
+            controlOf = encodeControlBlock (inControl + parity) internal [leafHash 0xc0 (Script [OP_RETURN])]
+            (psbt, _) = spendingPsbt (forceRight (taprootScriptOutput outputOf))
+            fields =
+              insertInputTapInternalKey internal
+                . insertInputTapMerkleRoot (mastCommitment treeOf)
+                . insertTapLeafScript (TapLeafScript controlOf leaf named)
+                . insertInputTapDerivation leafKey (TapDerivation [leafHash named leaf] derivation)
+        scriptSignatures = fmap length . tapScriptSigs . inputAt 0
+        -- A valid signature of key 2 for the leaf of version 0xc0, on the
+        -- input of the PSBT
+        signedLeaf unsigned = onInputs (insertTapScriptSig leafKey hashOfLeaf signature) unsigned
+          where
+            coin = fromJust (either (const Nothing) id (witnessUtxo (inputAt 0 unsigned)))
+            hashOfLeaf = leafHash 0xc0 leaf
+            ofLeaf = Just (hashOfLeaf, 0xffffffff)
+            digest = forceRight (taprootSigHash unsigned.unsignedTx [coin] 0 sigHashDefault Nothing ofLeaf)
+            signature = forceRight (taprootSignature (signSchnorr secretTwo (hashToMsg digest)) sigHashDefault)
+
+    -- BIP 342 gives <key> OP_CHECKSIG its meaning, and the signature its
+    -- digest, for the leaf version 0xc0 only
+    it "signs a leaf of the leaf version 0xc0, and not the same leaf of the leaf version 0xc2" $ do
+      (scriptSignatures =<< signPsbt btc (byRecord secretTwo) (leafOfVersion 0xc0 0xc0 0xc0)) `shouldBe` Right 1
+      (scriptSignatures =<< signPsbt btc (byRecord secretTwo) (leafOfVersion 0xc2 0xc2 0xc2)) `shouldBe` Right 0
+
+    -- Bitcoin Core signs the leaf of the value, of version 0xc0, and does
+    -- not read the control block. A spend takes the leaf version of the
+    -- control block: in the first case the leaf of the entry is not in the
+    -- tree, in the second it is and its control block spends a leaf that
+    -- is not. The finalizer makes no witness of either.
+    it "signs a leaf by the leaf version of its value, whatever leaf version its control block has" $ do
+      (scriptSignatures =<< signPsbt btc (byRecord secretTwo) (leafOfVersion 0xc2 0xc2 0xc0)) `shouldBe` Right 1
+      (scriptSignatures =<< signPsbt btc (byRecord secretTwo) (leafOfVersion 0xc0 0xc2 0xc0)) `shouldBe` Right 1
+
+    -- The witness would spend the leaf of version 0xc2: one that nodes do
+    -- not relay in the first case, and that is not in the tree in the
+    -- second. Bitcoin Core does not finalize such an input, and refuses
+    -- nothing.
+    it "the finalizer leaves alone a signed leaf whose leaf version is not the one of its control block" $ do
+      forM_ [leafOfVersion 0xc2 0xc2 0xc0, leafOfVersion 0xc0 0xc2 0xc0] $ \entry ->
+        finalizePsbt btc (signedLeaf entry) `shouldBe` Right (signedLeaf entry)
+
+    -- A Merkle root is a hash of 32 bytes, and this one has 31. The decoder
+    -- refuses such a PSBT, and a program can still build one. The signer
+    -- holds the internal key, and cannot tell which coin the key gives.
+    it "the signer adds no key path signature to its own coin when the Merkle root of the input is not a hash" $ do
+      let (keyOnly, _) = spendingPsbt (forceRight (taprootScriptOutput (TaprootOutput internal Nothing)))
+          shortRoot = Map.insert (Key 0x18 "") (B.replicate 31 0x00)
+          named = onInputs (shortRoot . insertInputTapInternalKey internal) keyOnly
+      signPsbt btc (keySigner secretOne) named `shouldBe` Right named
+
+    it "signs a Taproot coin of a PSBT of version 2 by its key path, and the PSBT stays of version 2" $ do
+      let (keyOnly, coins) = spendingPsbt (forceRight (taprootScriptOutput (TaprootOutput internal Nothing)))
+          version2 = withVersion Version2 (onInputs (insertInputTapInternalKey internal) keyOnly)
+      final <- expectRight (finalizePsbt btc =<< signPsbt btc (keySigner secretOne) version2)
+      final.version `shouldBe` Version2
+      tx <- expectRight (psbtTransaction final)
+      verifyStdTx btc tx coins `shouldBe` True
+
+{- The time a Taproot input with many leaves, records and signatures takes -}
+
+-- | The secret key that is the number, for the tests that need many keys
+secretOf :: Int -> SecKey
+secretOf i = fromString (replicate (64 - length digits) '0' <> digits)
+  where
+    digits = showHex i ""
+
+-- | A PSBT that spends a Taproot coin whose script tree has the leaves, all
+-- at the depth given, so they are a power of two. The internal key of the
+-- coin is the point G. The input has the coin, and each leaf that the test
+-- keeps, with the control block of its place in the tree.
+spendingTree :: (Script -> Bool) -> Word8 -> [Script] -> Psbt
+spendingTree kept depth scripts = onInputs (\m -> foldr insertTapLeafScript m leaves) psbt
+  where
+    internal = derivePubKey secretOne
+    tree = fromJust (tapTreeFromLeaves [TapLeaf depth 0xc0 script | script <- scripts])
+    output = TaprootOutput internal (Just tree)
+    control = encodeControlBlock (0xc0 + keyParity (forceRight (taprootOutputKey output))) internal
+    (psbt, _) = spendingPsbt (forceRight (taprootScriptOutput output))
+    leaves =
+      [ TapLeafScript (control proof) script version
+      | (version, script, proof) <- getMerkleProofs tree,
+        kept script
+      ]
+
+-- A PSBT that another party wrote can hold thousands of leaf scripts,
+-- derivation records and signatures on one input, at no cost to its
+-- writer. The signer and the finalizer once compared each leaf with each
+-- record or signature. The seconds in the comments are those of that code
+-- built without optimisation, on the computer where the tests were
+-- written. The code that looks up takes 0.1 to 0.5 seconds there.
+taprootCostSpec :: Spec
+taprootCostSpec =
+  describe "A Taproot input takes time by its size, and not by the square of its size: in under three seconds" $ do
+    let keyLeaf secret = Script [opPushData (exportXOnlyPubKey (derivePubKey secret)), OP_CHECKSIG]
+        -- 2048 leaves at depth 11, each the check of a key of its own
+        leaves = [keyLeaf (secretOf i) | i <- [1001 .. 3048]]
+        -- 16384 keys that are in no leaf
+        strangers = [derivePubKey (secretOf i) | i <- [100001 .. 116384]]
+        derivation = Derivation (fingerprintOf "d90c6a4f") "m/86'/0'/0'/0/0"
+        -- Whether the work leaves the PSBT as it is, when it answers within
+        -- the seconds. The PSBT is built before the time starts.
+        leavesAlone :: Int -> (Psbt -> Either String Psbt) -> Psbt -> IO (Maybe Bool)
+        leavesAlone seconds work psbt = do
+          _ <- evaluate (B.length (encodePsbt psbt))
+          timeout (seconds * 1000000) (evaluate (work psbt == Right psbt))
+
+    -- 2048 leaves × 16384 records = 33,554,432 comparisons of two keys: 13 seconds
+    it "the signer leaves alone 2048 leaves and 16384 records of keys it does not hold" $ do
+      let records m = foldr (\key -> insertInputTapDerivation key (TapDerivation [] derivation)) m strangers
+      leavesAlone 3 (signPsbt btc (keySigner secretThree)) (onInputs records (spendingTree (const True) 11 leaves))
+        `shouldReturn` Just True
+
+    -- The signatures are 64 bytes that verify for no key, filed under a
+    -- leaf hash that is the hash of no leaf of the input.
+    -- 2048 leaves × 16384 signatures = 33,554,432 comparisons of two keys: 13 seconds
+    it "the finalizer leaves alone 2048 leaves and 16384 signatures that are for none of them" $ do
+      let signature key = Map.insert (Key 0x14 (exportXOnlyPubKey key <> B.replicate 32 0xaa)) (B.replicate 64 0x01)
+          signatures m = foldr signature m strangers
+      leavesAlone 3 (finalizePsbt btc) (onInputs signatures (spendingTree (const True) 11 leaves))
+        `shouldReturn` Just True
+
+    -- One leaf can be at many places of a tree, and the input then has it
+    -- once for each place, each time with another control block. Here the
+    -- tree has 8192 leaves at depth 13: the same key check 4096 times, each
+    -- beside a leaf of its own. The record of the key lists 262144 leaves,
+    -- and not that one.
+    -- 4096 places × 262144 leaf hashes = 1,073,741,824 comparisons of two hashes: 13 seconds
+    it "the signer leaves alone one leaf at 4096 places, whose record lists 262144 other leaves" $ do
+      let own = keyLeaf secretTwo
+          beside i = Script [opPushData (S.encode i), OP_DROP]
+          others = [fromJust (digestFromByteString (B.replicate 28 0 <> S.encode i)) | i <- [1 .. 262144 :: Word32]]
+          record = insertInputTapDerivation (derivePubKey secretTwo) (TapDerivation others derivation)
+          scripts = concat [[own, beside i] | i <- [1 .. 4096 :: Word32]]
+      leavesAlone 3 (signPsbt btc (keySigner secretThree)) (onInputs record (spendingTree (== own) 13 scripts))
+        `shouldReturn` Just True
+
+{- The coins of a PSBT, and the previous transaction a signer may require -}
+
+coinsSpec :: Spec
+coinsSpec =
+  describe "The coins of a PSBT" $ do
+    let public = compressedKey secretOne
+        signer = keySigner secretOne
+        program = PayWitnessPKHash (addressHash (encodeSerial public))
+        (psbt, _) = spendingPsbt program
+        parent = fromJust (either (const Nothing) id (nonWitnessUtxo (inputAt 0 psbt)))
+        output = head parent.outputs
+        witnessOnly = withInputs [insertWitnessUtxo output Map.empty] psbt
+        signatureCounts = mapM (fmap length . partialSignatures) . (.inputs)
+
+    it "tells the coin of each input, and whether it comes from the previous transaction of the input" $ do
+      inputCoins psbt `shouldBe` Right [Just (InputCoin output True)]
+      inputCoins witnessOnly `shouldBe` Right [Just (InputCoin output False)]
+      inputCoins (withInputs [Map.empty] psbt) `shouldBe` Right [Nothing]
+
+    -- The coin holds 200,000,000 satoshi and the outputs pay 99,999,699 and
+    -- 100,000,000: 200,000,000 − 199,999,699 = 301
+    it "gives the fee when every coin comes from its previous transaction" $
+      psbtFee psbt `shouldBe` Right 301
+
+    it "gives no fee when the amount of a coin is only a claim, when a coin is missing, or when the outputs pay more than the coins hold" $ do
+      psbtFee witnessOnly `shouldBe` Left "Input 0: the coin is given as a witness output only, so its amount is not checked"
+      psbtFee (withInputs [Map.empty] psbt) `shouldBe` Left "Input 0 has no coin"
+      -- The same transaction with one more output of 302 satoshi
+      let tx = psbt.unsignedTx
+          paysMore = Psbt Version0 (Tx tx.version tx.inputs (tx.outputs <> [TxOut 302 ""]) [] tx.locktime) Map.empty psbt.inputs [Map.empty, Map.empty, Map.empty]
+      psbtFee paysMore `shouldBe` Left "The outputs pay more than the coins hold"
+
+    -- BIP 174: "The Signer may choose to fail to sign a segwit input if a
+    -- non-witness UTXO is not provided."
+    it
+      "a signer leaves unsigned a SegWit version 0 coin known from its \
+      \witness output only, and signs it with its previous transaction"
+      $ do
+        signPsbt btc signer witnessOnly `shouldBe` Right witnessOnly
+        (signatureCounts =<< signPsbt btc signer psbt) `shouldBe` Right [1]
+        (signatureCounts =<< signPsbt btc signer (withInputs [insertWitnessUtxo output (inputAt 0 psbt)] psbt)) `shouldBe` Right [1]
+
+    it "a signer told to trust witness outputs signs a SegWit version 0 coin known from its witness output only" $
+      (signatureCounts =<< signPsbt btc (signer {requirePreviousTx = False}) witnessOnly) `shouldBe` Right [1]
+
+    -- CVE-2020-14199. The signer holds two coins of 15 and 20 BTC. The
+    -- writer of the PSBT understates the first as 5 BTC and overstates the
+    -- second. A signature of each input commits to the amount of that input
+    -- alone, so the signature of the second input would be valid in a
+    -- transaction that burns the 10 BTC of difference as fee.
+    it
+      "a signer signs no SegWit version 0 coin of a PSBT that \
+      \states the amounts without the previous transactions"
+      $ do
+        let both = spendingTwo (encodeSerial program) (encodeSerial program)
+            claimed = withInputs [insertWitnessUtxo (TxOut 500000000 (encodeSerial program)) Map.empty, insertWitnessUtxo (TxOut 2000000000 (encodeSerial program)) Map.empty] both
+        signPsbt btc signer claimed `shouldBe` Right claimed
+
+    -- A Taproot signature commits to the amount of every coin (BIP 341)
+    it "a signer signs a Taproot coin known from its witness output only" $ do
+      let internal = derivePubKey secretOne
+          (taproot, _) = spendingPsbt (forceRight (taprootScriptOutput (TaprootOutput internal Nothing)))
       (fmap isJust . tapKeySig . inputAt 0 =<< signPsbt btc signer (withInputs (insertInputTapInternalKey internal <$> taproot.inputs) taproot)) `shouldBe` Right True
 
 {- The fields of version 2, read one by one -}
diff --git a/test/Haskoin/Transaction/TaprootSpec.hs b/test/Haskoin/Transaction/TaprootSpec.hs
--- a/test/Haskoin/Transaction/TaprootSpec.hs
+++ b/test/Haskoin/Transaction/TaprootSpec.hs
@@ -13,7 +13,8 @@
 module Haskoin.Transaction.TaprootSpec (spec) where
 
 import Control.Applicative ((<|>))
-import Control.Monad (forM, forM_, (<=<))
+import Control.Exception (evaluate)
+import Control.Monad (forM, forM_, void, (<=<))
 import Crypto.Hash (Digest, SHA256, digestFromByteString, hashFinalize, hashUpdate)
 import Data.Aeson
 import Data.Aeson.Types
@@ -24,14 +25,17 @@
 import Data.Bytes.Put (putByteString, putWord8, runPutS)
 import Data.Bytes.Serial (deserialize, serialize)
 import Data.Bytes.VarInt qualified as Base128
-import Data.Either (isLeft)
+import Data.Either (isLeft, isRight)
+import Data.Map.Strict qualified as Map
 import Data.Maybe (fromJust, isJust, isNothing)
 import Data.Serialize qualified as S
+import Data.Set qualified as Set
 import Data.Text (Text)
 import Data.Text qualified
 import Data.Word (Word32, Word64, Word8)
 import Haskoin
 import Haskoin.Util.Arbitrary
+import System.Timeout (timeout)
 import Test.HUnit (assertBool, (@?=))
 import Test.Hspec
 import Test.Hspec.QuickCheck (prop)
@@ -68,7 +72,8 @@
     prop "has the x coordinate of the public key of the output secret key" $
       forAll arbitraryKeyPair $ \(k, p) ->
         let tweaked = fromJust (taprootOutputSecKey k.key Nothing)
-         in exportXOnlyPubKey (derivePubKey tweaked) === exportXOnlyPubKey (taprootOutputKey (TaprootOutput p.point Nothing))
+         in Right (exportXOnlyPubKey (derivePubKey tweaked))
+              === (exportXOnlyPubKey <$> taprootOutputKey (TaprootOutput p.point Nothing))
 
     -- The test vectors of BIP 86: the keys at m/86'/0'/0'/0/0, 0/1 and
     -- 1/0 of the mnemonic "abandon ... about"
@@ -78,9 +83,9 @@
             secret = (derivePath (path :: DerivPath) root).key
             output = TaprootOutput (derivePubKey secret) Nothing
         encodeHex (exportXOnlyPubKey (derivePubKey secret)) `shouldBe` internalKey
-        encodeHex (exportXOnlyPubKey (taprootOutputKey output)) `shouldBe` outputKey
-        encodeHex (encodeSerial (taprootScriptOutput output)) `shouldBe` "5120" <> outputKey
-        (addrToText btc =<< outputAddress btc (taprootScriptOutput output)) `shouldBe` Just address
+        encodeHex (exportXOnlyPubKey (either error id (taprootOutputKey output))) `shouldBe` outputKey
+        encodeHex (encodeSerial (either error id (taprootScriptOutput output))) `shouldBe` "5120" <> outputKey
+        (addrToText btc =<< outputAddress btc (either error id (taprootScriptOutput output))) `shouldBe` Just address
         -- The output secret key signs for the output key
         fmap (encodeHex . exportXOnlyPubKey . derivePubKey) (taprootOutputSecKey secret Nothing) `shouldBe` Just outputKey
 
@@ -90,7 +95,7 @@
         let output = TaprootOutput (derivePubKey c.internalSecret) (MASTCommitment <$> c.merkleRoot)
             program = BS.drop 2 (testKeyPath.spent !! c.index).script
         encodeHex (exportXOnlyPubKey (derivePubKey c.internalSecret)) `shouldBe` c.internalPubKey
-        exportXOnlyPubKey (taprootOutputKey output) `shouldBe` program
+        exportXOnlyPubKey (either error id (taprootOutputKey output)) `shouldBe` program
         let tweaked = fromJust (taprootOutputSecKey c.internalSecret (MASTCommitment <$> c.merkleRoot))
         tweaked `shouldBe` fromJust (secKey (hexBytes c.tweakedSecret))
         digest <- expectRight (taprootSigHash testKeyPath.unsignedTx testKeyPath.spent c.index c.hashType Nothing Nothing)
@@ -99,6 +104,12 @@
         -- auxiliary randomness, as signSchnorr signs
         fmap (encodeHex . encodeTaprootSig) (taprootSignature (signSchnorr tweaked (hashToMsg digest)) c.hashType) `shouldBe` Right (head c.witness)
 
+    it "the digest of each input of the vector, from the hashes that its inputs share" $ do
+      hashes <- expectRight (taprootTxHashes testKeyPath.unsignedTx testKeyPath.spent)
+      forM_ testKeyPath.cases $ \c ->
+        fmap (encodeHex . runPutS . serialize) (taprootSigHashWith hashes c.index c.hashType Nothing Nothing)
+          `shouldBe` Right c.sigHash
+
     it "the fully signed transaction of the vector verifies against the coins it spends" $
       verifyStdTx btc testKeyPath.signedTx (coinsOf testKeyPath) `shouldBe` True
 
@@ -119,6 +130,20 @@
       forM_ noTree $ \c ->
         (signed.witness !! c.index) `shouldBe` [hexBytes (head c.witness)]
 
+    -- Two signing parameters for one coin of 100,000 satoshi. They differ
+    -- by the amount, which the digest commits to: 100,000 and 100,001.
+    it "signTx signs a Taproot input with the first signing parameters given for its outpoint" $ do
+      let secret = (fst bip86Key).key
+          coinScript = either error id (taprootScriptOutput (TaprootOutput (derivePubKey secret) Nothing))
+          outpoint = OutPoint "1111111111111111111111111111111111111111111111111111111111111111" 0
+          right = SigInput coinScript 100000 outpoint sigHashDefault Nothing
+          wrong = SigInput coinScript 100001 outpoint sigHashDefault Nothing
+          verifies parameters =
+            (\tx -> verifyStdTx btc tx [(coinScript, 100000, outpoint)])
+              <$> signTx btc (buildTx [outpoint] [(coinScript, 99000)]) parameters [secret]
+      verifies [right, wrong] `shouldBe` Right True
+      verifies [wrong, right] `shouldBe` Right False
+
     -- The witness of each input is in the vector, so this checks the
     -- signer against the BIP for all seven inputs and hash types
     it "signTaprootInput signs each Taproot input of the vector with its output secret key, and gives the witness of the vector" $
@@ -137,7 +162,23 @@
       taprootSigHash tx spent 0 (setForkIdFlag sigHashAll) Nothing Nothing `shouldBe` Left "taprootSigHash: invalid hash type 65"
       -- The transaction has two outputs: input 3 has none at its index
       taprootSigHash tx spent 3 sigHashSingle Nothing Nothing `shouldBe` Left "taprootSigHash: SIGHASH_SINGLE without an output at the input index"
+      -- A wrong index and missing coins: the index is told
+      taprootSigHash tx (take 8 spent) 9 sigHashDefault Nothing Nothing
+        `shouldBe` Left "taprootSigHash: input index out of range"
 
+    it "taprootTxHashes refuses missing coins, and taprootSigHashWith refuses what taprootSigHash refuses" $ do
+      let tx = testKeyPath.unsignedTx
+          spent = testKeyPath.spent
+      void (taprootTxHashes tx (take 8 spent)) `shouldBe` Left "taprootSigHash: one spent output per input is required"
+      hashes <- expectRight (taprootTxHashes tx spent)
+      let digest i hashType annex = taprootSigHashWith hashes i hashType annex Nothing
+      digest 9 sigHashDefault Nothing `shouldBe` Left "taprootSigHash: input index out of range"
+      digest (-1) sigHashDefault Nothing `shouldBe` Left "taprootSigHash: input index out of range"
+      digest 0 0x04 Nothing `shouldBe` Left "taprootSigHash: invalid hash type 4"
+      digest 3 sigHashSingle Nothing
+        `shouldBe` Left "taprootSigHash: SIGHASH_SINGLE without an output at the input index"
+      digest 0 sigHashDefault (Just "hello") `shouldBe` Left "taprootSigHash: an annex starts with 0x50"
+
     it "taprootSigHash commits to the annex and to the leaf of a script path spend" $ do
       let tx = testKeyPath.unsignedTx
           spent = testKeyPath.spent
@@ -191,7 +232,7 @@
         leaf = Script [OP_2DROP, OP_1]
         tree = MASTBranch (MASTLeaf tapscriptLeafVersion leaf) (MASTLeaf tapscriptLeafVersion (Script [OP_1]))
         output = TaprootOutput internalKey (Just tree)
-        outputKey = taprootOutputKey output
+        outputKey = either error id (taprootOutputKey output)
         [(_, _, proof), _] = getMerkleProofs tree
         spend = ScriptPathData {annex = Nothing, stack = ["aa", "bbbb"], script = leaf, extIsOdd = odd (keyParity outputKey), leafVersion = tapscriptLeafVersion, internalKey, control = proof, opaqueScript = Nothing}
         control = encodeControlBlock (tapscriptLeafVersion + keyParity outputKey) internalKey proof
@@ -232,7 +273,8 @@
 
     it "a script path spend of bytes that are not opcodes verifies against the output key that commits to those bytes" $ do
       let opaque = "\x50\x4c"
-          key = taprootOutputKey (TaprootOutput internalKey (Just (MASTCommitment (leafHashBytes 0xc0 opaque))))
+          committed = MASTCommitment (leafHashBytes 0xc0 opaque)
+          key = either error id (taprootOutputKey (TaprootOutput internalKey (Just committed)))
           opaqueSpend = ScriptPathData {annex = Nothing, stack = [], script = Script [], extIsOdd = odd (keyParity key), leafVersion = 0xc0, internalKey, control = [], opaqueScript = Just opaque}
       verifyScriptPathData key opaqueSpend `shouldBe` True
       verifyScriptPathData key opaqueSpend {opaqueScript = Just "\x50\x4d"} `shouldBe` False
@@ -257,7 +299,8 @@
       verifyScriptPathData outputKey spend {extIsOdd = not spend.extIsOdd} `shouldBe` False
       verifyScriptPathData outputKey spend {control = []} `shouldBe` False
       verifyScriptPathData outputKey spend {script = Script [OP_1]} `shouldBe` False
-      verifyScriptPathData (taprootOutputKey (TaprootOutput internalKey Nothing)) spend `shouldBe` False
+      let keyOnly = either error id (taprootOutputKey (TaprootOutput internalKey Nothing))
+      verifyScriptPathData keyOnly spend `shouldBe` False
 
     it "a control block is 33 bytes plus 32 per node, with at most 128 nodes" $ do
       let node = BS.replicate 32 1
@@ -346,8 +389,8 @@
           internal = fromJust (importXOnlyPubKey (hexBytes "cba52b4389f798ec8ba66d9520ce532af2fe642b970010e2fbd0ec36bce36970"))
       BS.length (hexBytes multiALeaf) `shouldBe` 138
       digestHex (leafHash 0xc0 leaf) `shouldBe` "c6831caa9b274f379336d6bcc789aa6e82760d573e3750b97df37e624d8e6c90"
-      encodeHex (encodeSerial (taprootScriptOutput (TaprootOutput internal (Just (MASTLeaf 0xc0 leaf)))))
-        `shouldBe` "51207fd815afed80f6bc581ac94aa52d85c50d2bddff7347e1094936eb71e2f18936"
+      (encodeHex . encodeSerial <$> taprootScriptOutput (TaprootOutput internal (Just (MASTLeaf 0xc0 leaf))))
+        `shouldBe` Right "51207fd815afed80f6bc581ac94aa52d85c50d2bddff7347e1094936eb71e2f18936"
 
     it "of script bytes that are not a list of opcodes is taken on the bytes" $
       -- 50 4c is OP_SUCCESS80 followed by an OP_PUSHDATA1 with no length.
@@ -369,7 +412,7 @@
       xOnly internal `shouldBe` "cba52b4389f798ec8ba66d9520ce532af2fe642b970010e2fbd0ec36bce36970"
       digestHex oldLeafHash `shouldBe` "4a0b2a93f8430729d9467c0bc91d26d54b63802e627783bf808694c8e8dbc372"
     it "has the output key of the tree that holds the old leaf hash as a commitment" $
-      xOnly (taprootOutputKey (TaprootOutput internal (Just (MASTCommitment oldLeafHash))))
+      xOnly (either error id (taprootOutputKey (TaprootOutput internal (Just (MASTCommitment oldLeafHash)))))
         `shouldBe` "15e87fb4cb019af07cf16fa2b9a8451536bd86321dcc11053c70d9038ec97c80"
     it "is spent by its key path with the secret key tweaked with that commitment" $
       fmap (xOnly . derivePubKey) (taprootOutputSecKey internalSecret (Just (MASTCommitment oldLeafHash)))
@@ -378,7 +421,7 @@
       -- The tree {pk(1cf7198d…2500), multi_a leaf}
       let short = Script [opPushData (hexBytes "1cf7198d10d0552c8df4d0380372a5fa224a1226fc3a49546a416086442d2500"), OP_CHECKSIG]
           oldTree = MASTBranch (MASTLeaf 0xc0 short) (MASTCommitment oldLeafHash)
-          oldKey = taprootOutputKey (TaprootOutput internal (Just oldTree))
+          oldKey = either error id (taprootOutputKey (TaprootOutput internal (Just oldTree)))
           proofs = [proof | (_, _, proof) <- getMerkleProofs oldTree]
           spendOf proof = ScriptPathData {annex = Nothing, stack = [], script = short, extIsOdd = odd (keyParity oldKey), leafVersion = 0xc0, internalKey = internal, control = proof, opaqueScript = Nothing}
       xOnly oldKey `shouldBe` "120ed04aacce013f8ed3b63a53143aec81a4c05fa0a263a693d14aa8bebd7efd"
@@ -389,7 +432,7 @@
           tree = MASTBranch (MASTLeaf 0xc0 short) (MASTLeaf 0xc0 (scriptOf multiALeaf))
       -- Root and key computed in Python from the text of BIP 341
       digestHex (mastCommitment tree) `shouldBe` "4bff8cf0bd46ff4d4470c11a7f407dfee7078c7675b877691310c0ee0058c620"
-      xOnly (taprootOutputKey (TaprootOutput internal (Just tree))) `shouldBe` "b672ffdc20bf79cf4bda88ec7a0ad9c53c91e032f2bc169af425eae9dac8afe0"
+      xOnly (either error id (taprootOutputKey (TaprootOutput internal (Just tree)))) `shouldBe` "b672ffdc20bf79cf4bda88ec7a0ad9c53c91e032f2bc169af425eae9dac8afe0"
 
   describe "Merkle proofs" $ do
     -- tr(ecd5eddb…7670,{pk(A),{pk(B),{pk(C),pk(D)}}}). The Merkle root and
@@ -404,7 +447,7 @@
           d = pkLeaf "33045c7755fc6aef51859ad00d7393f1d23ff8b0bd6acf0d6c6d7a72502d905a"
           tree = MASTBranch a (MASTBranch b (MASTBranch c d))
           internal = fromJust (importXOnlyPubKey (hexBytes "ecd5eddb647ff233131e292cef048228bce3a3b045319d563b57d59e294c7670"))
-          outputKey = taprootOutputKey (TaprootOutput internal (Just tree))
+          outputKey = either error id (taprootOutputKey (TaprootOutput internal (Just tree)))
           controlBlocks = [encodeHex (encodeControlBlock (0xc0 + keyParity outputKey) internal proof) | (_, _, proof) <- getMerkleProofs tree]
       digestHex (mastCommitment tree) `shouldBe` "e0f4dd44e6affb70c64661b32d78666ce2296fcdf9abdcbbe9482e91398f4ac5"
       controlBlocks
@@ -426,7 +469,7 @@
       forAll (arbitraryMAST True) $ \tree ->
         let (_, p) = bip86Key
             internal = fromJust (importXOnlyPubKey (exportXOnlyPubKey p.point))
-            outputKey = taprootOutputKey (TaprootOutput internal (Just tree))
+            outputKey = either error id (taprootOutputKey (TaprootOutput internal (Just tree)))
             spendOf (version, script, proof) = ScriptPathData {annex = Nothing, stack = [], script, extIsOdd = odd (keyParity outputKey), leafVersion = version, internalKey = internal, control = proof, opaqueScript = Nothing}
             proofs = getMerkleProofs tree
          in (map (\(_, _, proof) -> length proof) proofs, map (verifyScriptPathData outputKey . spendOf) proofs)
@@ -480,15 +523,34 @@
       -- the first input without one
       taprootSigHash testKeyPath.unsignedTx testKeyPath.spent 2 sigHashSingle Nothing Nothing
         `shouldBe` Left "taprootSigHash: SIGHASH_SINGLE without an output at the input index"
+    -- The first input has the sequence number 0xfffffffe and is signed with
+    -- SIGHASH_ALL|ANYONECANPAY (0x81). The second has 0xfffffffd and is
+    -- signed with SIGHASH_SINGLE|ANYONECANPAY (0x83).
+    it "of an input signed with ANYONECANPAY commits to the sequence number of that input" $ do
+      let spent = replicate 2 (coin anyoneCanPayCoin)
+          digestAt i hashType =
+            encodeHex . runPutS . serialize <$> taprootSigHash (txOf anyoneCanPayTx) spent i hashType Nothing Nothing
+      digestAt 0 0x81 `shouldBe` Right "0055ae93be20be76bdd1aebf526c2184fc92aeedb8107141cf08a7d153bd63f1"
+      digestAt 1 0x83 `shouldBe` Right "01b065079f55a45bd2b76aaf8650277f1818442b8fca98e205b0e31bd2517be5"
 
   describe "verifyStdTx on Taproot inputs" $ do
     let coinOfTx = oneCoin
-    it "accepts the key path spend with an annex that Bitcoin Core 32.1 mined on regtest" $ do
+    -- Bitcoin Core 32.1 relayed and mined this spend on regtest, with the
+    -- relay policy of mainnet. The test of 'taprootSigHash' above states
+    -- the digests of its two signatures.
+    it "verifies two key path inputs signed with ANYONECANPAY, whose sequence numbers are not 0xffffffff" $ do
+      let tx = txOf anyoneCanPayTx
+          script = either error id (decodeSerial (hexBytes anyoneCanPayCoin))
+      verifyStdTx btc tx [(script, 100000, input.outpoint) | input <- tx.inputs] `shouldBe` True
+    -- Bitcoin Core 32.1 mined these two spends on regtest, and does not
+    -- relay a Taproot input with an annex: "bad-witness-nonstandard". The
+    -- tests of 'taprootSigHash' above state the digests of their signatures.
+    it "refuses the key path spend with an annex, which nodes do not relay" $ do
       let tx = txOf keyPathAnnexTx
-      verifyStdTx btc tx (coinOfTx tx "512028066f61c28af1ecb48c7948f8b5770838eec15223c8697a8e40510c2c29ea04") `shouldBe` True
-    it "accepts the script path spend of a single key leaf with an annex that Bitcoin Core 32.1 mined on regtest" $ do
+      verifyStdTx btc tx (coinOfTx tx "512028066f61c28af1ecb48c7948f8b5770838eec15223c8697a8e40510c2c29ea04") `shouldBe` False
+    it "refuses the script path spend of a single key leaf with an annex, which nodes do not relay" $ do
       let tx = txOf scriptPathAnnexTx
-      verifyStdTx btc tx (coinOfTx tx "5120a354b6c111a5f8339fd8ea5bc6147f8ca829029188e4d3f7622751417328be18") `shouldBe` True
+      verifyStdTx btc tx (coinOfTx tx "5120a354b6c111a5f8339fd8ea5bc6147f8ca829029188e4d3f7622751417328be18") `shouldBe` False
     -- The witness holds a valid signature of the leaf key over the leaf
     -- "<key> OP_CHECKSIG", and a control block that names the same key as
     -- internal key. The coin's output key does not commit to that leaf.
@@ -510,17 +572,19 @@
           outpoint = OutPoint "1111111111111111111111111111111111111111111111111111111111111111" 0
           spendWith version = do
             let output = TaprootOutput internal (Just (MASTLeaf version leafScript))
-                coinScript = taprootScriptOutput output
+                coinScript = either error id (taprootScriptOutput output)
                 unsigned = buildTx [outpoint] [(coinScript, 99000)]
             digest <- taprootSigHash unsigned [TxOut 100000 (encodeSerial coinScript)] 0 sigHashDefault Nothing (Just (leafHash version leafScript, 0xffffffff))
             signature <- taprootSignature (signSchnorr leafSecret.key (hashToMsg digest)) sigHashDefault
             witness <-
               encodeTaprootWitness . ScriptPathSpend $
-                ScriptPathData {annex = Nothing, stack = [encodeTaprootSig signature], script = leafScript, extIsOdd = odd (keyParity (taprootOutputKey output)), leafVersion = version, internalKey = internal, control = [], opaqueScript = Nothing}
+                ScriptPathData {annex = Nothing, stack = [encodeTaprootSig signature], script = leafScript, extIsOdd = odd (keyParity (either error id (taprootOutputKey output))), leafVersion = version, internalKey = internal, control = [], opaqueScript = Nothing}
             return (verifyStdTx btc (Tx unsigned.version unsigned.inputs unsigned.outputs [witness] unsigned.locktime) [(coinScript, 100000, outpoint)])
       spendWith 0xc0 `shouldBe` Right True
       spendWith 0xc2 `shouldBe` Right False
 
+  sharedHashesCostSpec
+
   describe "Control blocks" $
     it "are refused when the internal key is not the x coordinate of a point" $
       -- ff…ff is above the field size, so it is no x coordinate
@@ -568,11 +632,29 @@
       checkTapTree (MASTLeaf 0xc2 (Script [OP_1])) `shouldBe` Right ()
       checkTapTree (MASTLeaf 0xc1 (Script [OP_1])) `shouldBe` Left "checkTapTree: the leaf version 193 is odd"
       checkTapTree (MASTLeaf 0x50 (Script [OP_1])) `shouldBe` Left "checkTapTree: the leaf version 0x50 would read as an annex"
+    -- Bitcoin Core builds no output for such a tree (TaprootBuilder::Add).
+    -- A leaf at depth 129 could never be spent. The root of the tree, as a
+    -- commitment, still gives the output of the tree as it is.
+    it "gives the output of a tree down to depth 128, and refuses a tree down to depth 129" $ do
+      let output tree = TaprootOutput (snd bip86Key).point (Just tree)
+          tooDeep = "checkTapTree: a node is deeper than 128"
+      isRight (taprootOutputKey (output (chain 128))) `shouldBe` True
+      isRight (taprootScriptOutput (output (chain 128))) `shouldBe` True
+      taprootOutputKey (output (chain 129)) `shouldBe` Left tooDeep
+      taprootScriptOutput (output (chain 129)) `shouldBe` Left tooDeep
+      isRight (taprootScriptOutput (output (MASTCommitment (mastCommitment (chain 129))))) `shouldBe` True
+    it "gives no output for a tree with a leaf version that a control block cannot carry" $ do
+      let output version = TaprootOutput (snd bip86Key).point (Just (MASTLeaf version (Script [OP_1])))
+      isRight (taprootScriptOutput (output 0xc2)) `shouldBe` True
+      taprootScriptOutput (output 0xc1) `shouldBe` Left "checkTapTree: the leaf version 193 is odd"
+      taprootOutputKey (output 0x50) `shouldBe` Left "checkTapTree: the leaf version 0x50 would read as an annex"
     it "the proof of a leaf at depth 128 verifies, and the proof of a leaf at depth 129 does not" $ do
       let (_, p) = bip86Key
           internal = fromJust (importXOnlyPubKey (exportXOnlyPubKey p.point))
           deepest tree =
-            let outputKey = taprootOutputKey (TaprootOutput internal (Just tree))
+            -- The root of the tree gives its output key, whatever its depth
+            let root = MASTCommitment (mastCommitment tree)
+                outputKey = either error id (taprootOutputKey (TaprootOutput internal (Just root)))
                 (version, script, proof) = last (getMerkleProofs tree)
                 spend = ScriptPathData {annex = Nothing, stack = [], script, extIsOdd = odd (keyParity outputKey), leafVersion = version, internalKey = internal, control = proof, opaqueScript = Nothing}
              in (length proof, verifyScriptPathData outputKey spend)
@@ -657,6 +739,84 @@
       n <- frequency [(3, choose (1, 127)), (3, choose (128, 252)), (2, choose (253, 600)), (2, elements [127, 128, 252, 253])]
       return (Script (replicate n OP_NOP))
 
+-- | BIP 341 has the digest of every input of a transaction commit to four
+-- hashes over all its inputs and one over all its outputs, which "may be
+-- cached across signatures of the same transaction". Each test fails by its
+-- time when a function computes them again for each input: 5000 times the
+-- hashes of 5000 inputs. The seconds in the comments are those of such
+-- code built without optimisation, on the computer where the tests were
+-- written. The code that computes the hashes once takes under a second
+-- there.
+sharedHashesCostSpec :: Spec
+sharedHashesCostSpec =
+  describe
+    "A transaction of 5000 Taproot inputs takes time by its size, \
+    \and not by the square of its size: in under three seconds"
+    $ do
+      let count = 5000
+          secret = (fst bip86Key).key
+          internal = derivePubKey secret
+          coinScript = either error id (taprootScriptOutput (TaprootOutput internal Nothing))
+          coin = TxOut 100000 (encodeSerial coinScript)
+          funding = "1111111111111111111111111111111111111111111111111111111111111111"
+          outpoints = [OutPoint funding i | i <- [1 .. 5000]]
+          unsigned = buildTx outpoints [(coinScript, 99000)]
+          sigInputs = [SigInput coinScript 100000 outpoint sigHashDefault Nothing | outpoint <- outpoints]
+          signed = either error id (signTx btc unsigned sigInputs [secret])
+          -- The PSBT of the transaction: each input has its coin and the
+          -- internal key of the coin
+          psbt =
+            let empty = psbtOf unsigned
+                input = insertInputTapInternalKey internal (insertWitnessUtxo coin Map.empty)
+             in Psbt empty.version empty.unsignedTx empty.globals (replicate count input) empty.outputs
+          signedPsbt = either error id (signPsbt btc (keySigner secret) psbt)
+          -- Whether the work gives the answer, when it does within three
+          -- seconds. What the work starts from is built before the time
+          -- starts.
+          answers :: (Eq a) => Int -> a -> a -> IO (Maybe Bool)
+          answers built work answer = do
+            _ <- evaluate built
+            timeout 3000000 (evaluate (work == answer))
+          sizeOf = BS.length . encodeSerial
+
+      -- 15 seconds
+      it "taprootSigHashWith gives a digest of its own to each input, from the hashes that they share" $ do
+        let digests = do
+              hashes <- taprootTxHashes unsigned (replicate count coin)
+              mapM (\i -> taprootSigHashWith hashes i sigHashDefault Nothing Nothing) [0 .. count - 1]
+        answers (sizeOf unsigned) (Set.size . Set.fromList <$> digests) (Right 5000) `shouldReturn` Just True
+
+      -- 16 seconds
+      it "signTx signs every input with a signature of 64 bytes" $ do
+        let signatureSizes = map (map BS.length) . (.witness)
+            signatures = signatureSizes <$> signTx btc unsigned sigInputs [secret]
+        answers (sizeOf unsigned) signatures (Right (replicate 5000 [64]))
+          `shouldReturn` Just True
+
+      -- 16 seconds
+      it "verifyStdTx verifies the signed transaction" $
+        answers (sizeOf signed) (verifyStdTx btc signed [(coinScript, 100000, outpoint) | outpoint <- outpoints]) True
+          `shouldReturn` Just True
+
+      -- 16 seconds
+      it "judgeInputs says of every input of the signed transaction that it is verified" $
+        answers (sizeOf signed) (judgeInputs btc signed (replicate count (Just coin))) (replicate 5000 InputVerified)
+          `shouldReturn` Just True
+
+      -- 16 seconds
+      it "signPsbt adds a key path signature of 64 bytes to every input" $ do
+        let signatureSizes = map (fmap (fmap (BS.length . encodeTaprootSig)) . tapKeySig) . (.inputs)
+            signedInputs = signatureSizes <$> signPsbt btc (keySigner secret) psbt
+        answers (BS.length (encodePsbt psbt)) signedInputs (Right (replicate 5000 (Right (Just 64))))
+          `shouldReturn` Just True
+
+      -- 16 seconds
+      it "finalizePsbt gives every input a final witness of one signature of 64 bytes" $ do
+        let witnessSizes = map (fmap (fmap (map BS.length)) . finalScriptWitness) . (.inputs)
+            finalInputs = witnessSizes <$> finalizePsbt btc signedPsbt
+        answers (BS.length (encodePsbt signedPsbt)) finalInputs (Right (replicate 5000 (Right (Just [64]))))
+          `shouldReturn` Just True
+
 digestHex :: Digest SHA256 -> Text
 digestHex = encodeHex . BA.convert
 
@@ -683,6 +843,24 @@
 scriptPathAnnexTx = "010000000001016be84449b8f2ec0559b321b2aed59ba273f79710a73c5a7e3cbce8e57178c2260100000000ffffffff01d07e010000000000160014cabe51bbc4203c9221901541c9e9d3ac219e6ca80441fe2a5388123bdc28dc0635796683a24418375c1e94b9d9074889d4b6865224dd6a0ae16d63d454d1dcdbd86f7291f5be5ce2d0cb785adddc1cbd9bd9b8cda3bd012220864f1c660fd3842d2b45acae2d2c181378c3c397d9c8f6a36dce7e1b3f2fa01fac21c1bc4d541d1be26036455459e9fd4fb8c9e2b829b17eb18fb5f66bbbdedc1c61681750616e6e6578206f66206120736372697074207061746800000000"
 codeSeparatorTx = "01000000000101a1b61db207932647112026e232f793c6d807f666f46ebb23b526e68342630f820100000000ffffffff01d07e010000000000160014cabe51bbc4203c9221901541c9e9d3ac219e6ca8044093e3dfc003f3d11aca5c6301aa52f55fe916b01036710653c56ff829d393489a26834188c932372f93aadf116a55c540f68e049f2b17b69760ea22190b944b57401f03095eb9fe08f9462b86196fccd3dfffc2702c6c0b186593bed2ae31f4b963a5b36a40a4c0c76c3da7caf03f39b358773ce914999a772d638d3f5f18d49aa945201da5064215e4cad73afbc2f5cc5d1c537452b49b3660ab201ef739b808950e5cadab203ef9208927082a726fea24d87dabbb476a30c669f1aa0d98bdfc29ad7e30d33dac21c0db5c3a57b4b60a18c53d60623fc64fbd97c21fe61e9a0508919f1bbe7e658aa900000000"
 
+-- | A spend of two Taproot coins of 100,000 satoshi by their key path, which
+-- Bitcoin Core 32.1 relayed and mined on regtest. Its inputs have the
+-- sequence numbers 0xfffffffe and 0xfffffffd, and the hash types
+-- SIGHASH_ALL|ANYONECANPAY and SIGHASH_SINGLE|ANYONECANPAY.
+anyoneCanPayTx :: Text
+anyoneCanPayTx =
+  "020000000001024a884fd05241f5d864cf6cd5dd8bb19f89c0b0b10fb6bd806b3be7ee56d9c0730100000000feffffff0a50\
+  \bfca9dd73133b8941a03243bb3bee8355a73ceb570d016d09a9e2bb35c670100000000fdffffff02b8820100000000002251\
+  \205cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bcd07e0100000000002251205cbdf0646e5d\
+  \b4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc01418d197e78f4779ecaa9f0a411e9f466385e961729b2fe\
+  \b6a534438b12ae47dc3410f09ee8e9ac294be0780d01beab6faac04af3b37e78d36547a70c49d4b6d6b6810141b9d6be7fc2\
+  \a1abe3a1dd70c980918100ebd5ad47070d8e3362c9e19b1160b8a95f7fc166e7ae67aa6f4fe662e0b4088b11bf770b55d0f2\
+  \85e3bcddd9d142e2838300000000"
+
+-- | The output script of both coins that 'anyoneCanPayTx' spends
+anyoneCanPayCoin :: Text
+anyoneCanPayCoin = "51205cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc"
+
 -- | A script path spend of a coin whose output key does not commit to the
 -- leaf. The leaf is "<key> OP_CHECKSIG", its signature is valid, and the
 -- control block names the same key as internal key.
@@ -729,14 +907,14 @@
 
 testOutputKey :: TestScriptPubKey -> IO ()
 testOutputKey testData = do
-  XOnlyPubKey (taprootOutputKey theOutput) @?= theOutputKey
+  XOnlyPubKey (either error id (taprootOutputKey theOutput)) @?= theOutputKey
   where
     theOutput = tspkGiven testData
     theOutputKey = XOnlyPubKey . spkiTweakedPubKey $ tspkIntermediary testData
 
 testScriptOutput :: TestScriptPubKey -> IO ()
 testScriptOutput testData =
-  taprootScriptOutput (tspkGiven testData) @?= (spkeScriptPubKey . tspkExpected) testData
+  either error id (taprootScriptOutput (tspkGiven testData)) @?= (spkeScriptPubKey . tspkExpected) testData
 
 testControlBlocks :: TestScriptPubKey -> IO ()
 testControlBlocks testData = do
@@ -744,7 +922,7 @@
   mapM_ checkVerification scriptPathSpends
   where
     theOutput = tspkGiven testData
-    theOutputKey = taprootOutputKey theOutput
+    theOutputKey = either error id (taprootOutputKey theOutput)
     exampleControlBlocks = spkeControlBlocks $ tspkExpected testData
     -- The control block is the last item of the witness: the stack is
     -- empty, so it comes after the script
@@ -771,7 +949,7 @@
   computedAddress @?= (Just . spkeAddress . tspkExpected) testData
   where
     computedAddress =
-      (addrToText btc <=< outputAddress btc)
+      (addrToText btc <=< outputAddress btc <=< eitherToMaybe)
         . taprootScriptOutput
         $ tspkGiven testData
 
diff --git a/test/Haskoin/Transaction/VerdictSpec.hs b/test/Haskoin/Transaction/VerdictSpec.hs
--- a/test/Haskoin/Transaction/VerdictSpec.hs
+++ b/test/Haskoin/Transaction/VerdictSpec.hs
@@ -14,7 +14,8 @@
 import Data.Bytes.Serial (deserialize, serialize)
 import Data.Either (rights)
 import Data.Maybe (fromJust, mapMaybe)
-import Data.Word (Word64, Word8)
+import Data.Text (Text)
+import Data.Word (Word16, Word64, Word8)
 import Haskoin.Address
 import Haskoin.Crypto
 import Haskoin.Network.Constants
@@ -27,9 +28,69 @@
 import Test.Hspec.QuickCheck
 import Test.QuickCheck
 
-secret :: Word8 -> SecKey
-secret n = fromJust (secKey (B.replicate 31 0 <> B.singleton n))
+hex :: Text -> ByteString
+hex = fromJust . decodeHex
 
+-- | The transaction of these bytes.
+txOf :: Text -> Tx
+txOf = either error id . runGetS deserialize . hex
+
+-- | The answer of 'judgeInputs' for a transaction whose one input spends a
+-- coin of 1,000,000 with this script.
+judged :: Network -> ByteString -> Tx -> [InputVerdict]
+judged net locked tx = judgeInputs net tx [Just (TxOut 1000000 locked)]
+
+-- | The answers of 'verifyStdTx' and of 'judgeInputs' for such a
+-- transaction. The script of the coin must be a standard output.
+verdicts :: Network -> ByteString -> Tx -> (Bool, [InputVerdict])
+verdicts net locked = verdictsOf net [locked]
+
+-- | The same answers for a transaction of several inputs, which spend coins
+-- of 1,000,000 with these scripts, in order.
+verdictsOf :: Network -> [ByteString] -> Tx -> (Bool, [InputVerdict])
+verdictsOf net locked tx =
+  ( verifyStdTx net tx [(either error id (decodeSerial l), 1000000, i.outpoint) | (l, i) <- zip locked tx.inputs],
+    judgeInputs net tx [Just (TxOut 1000000 l) | l <- locked]
+  )
+
+-- | Every signed transaction with one input in this spelling gets these
+-- three answers: that of 'verifyStdTx', the verdict of 'judgeInputs' on that
+-- input, and whether it says verified of every other input, which are as
+-- the signer wrote them. 'verifyStdTx' gets every coin that it can take: a
+-- script that is no standard output cannot be given to it.
+answersFor :: Network -> Spelling -> (Bool, InputVerdict, Bool) -> Property
+answersFor net spelling expected =
+  forAll (arbitraryRespelled net spelling) $ \r -> answers r === expected
+  where
+    answers r = case splitAt r.index (judgeInputs net r.tx (map Just r.coins)) of
+      (before, verdict : after) ->
+        (verifyStdTx net r.tx (coinsOf r), verdict, all (== InputVerified) (before <> after))
+      _ -> error "answersFor: no verdict for the input"
+    coinsOf r = [(so, c.value, i.outpoint) | (c, i) <- zip r.coins r.tx.inputs, Right so <- [decodeSerial c.script]]
+
+-- | A multisig script: two signatures of three keys, each key after the
+-- push of its 0x21 = 33 bytes.
+directPushes :: ByteString
+directPushes =
+  hex
+    "5221031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5\
+    \dd078f21024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451\
+    \a7254d07662102531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3\
+    \c5bdbdcb1fe33753ae"
+
+-- | The same script with OP_PUSHDATA1 before the length of each key: 0x4c
+-- 0x21.
+longPushes :: ByteString
+longPushes =
+  hex
+    "524c21031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9\
+    \d5dd078f4c21024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374\
+    \c451a7254d07664c2102531fe6068134503d2723133227c867ac8fa6c83c537e\
+    \9a44c3c5bdbdcb1fe33753ae"
+
+secret :: Word16 -> SecKey
+secret n = fromJust (secKey (B.replicate 30 0 <> B.pack [fromIntegral (n `div` 256), fromIntegral n]))
+
 -- | The compressed bytes of the public key of a secret.
 pubBytes :: SecKey -> ByteString
 pubBytes = exportPubKey True . derivePubKey
@@ -103,6 +164,13 @@
           sig = ecdsa other 0x01 (txSigHash btc unsigned pkhScript value 0 sigHashAll)
       judgeInputs btc (spending (pushing [sig, pubBytes other]) []) [prev (PayPKHash h160)]
         `shouldBe` [InputForged]
+    -- No key hashes to the hash that the coin names but its key, so the
+    -- script fails before the signature is looked at.
+    it "says forged of an empty item where the key goes, pushed by OP_0" $ do
+      let unsigned = spending "" []
+          sig = ecdsa k 0x01 (txSigHash btc unsigned pkhScript value 0 sigHashAll)
+          inputScript = runPutS (serialize (Script [opPushData sig, OP_0]))
+      judgeInputs btc (spending inputScript []) [prev (PayPKHash h160)] `shouldBe` [InputForged]
     it "does the same for a witness key hash, plain and nested" $ do
       let unsigned = spending "" []
           sig = ecdsa k 0x01 (txSigHashForkId btc unsigned pkhScript value 0 sigHashAll)
@@ -116,6 +184,21 @@
           signed = head (rights [signTaprootInput (spending "" []) [out] 0 sigHashDefault s | s <- [k, negated]])
           negated = fromJust (secKey . (.get) =<< tweakNegate =<< tweak k.get)
       three btc signed (Just out)
+    -- The digest of a Taproot input commits to the index of the input. The
+    -- transaction spends two coins of one key, and each input then gets
+    -- the signature that the key made for the other.
+    it "says forged of a Taproot signature that the key of the coin made for another input" $ do
+      let out = TxOut value (encodeSerial (PayWitness 1 (B.drop 1 pub)))
+          one = spending "" []
+          two = one {inputs = one.inputs <> [TxIn (OutPoint coin.hash 1) "" maxBound]} :: Tx
+          signInput i s tx = signTaprootInput tx [out, out] i sigHashDefault s
+          signBoth s = signInput 0 s two >>= signInput 1 s
+          -- the secret of the key with an even y, whichever of the two it is
+          signed = head (rights (map signBoth [k, negated]))
+          negated = fromJust (secKey . (.get) =<< tweakNegate =<< tweak k.get)
+          exchanged = signed {witness = reverse signed.witness} :: Tx
+      judgeInputs btc signed [Just out, Just out] `shouldBe` [InputVerified, InputVerified]
+      judgeInputs btc exchanged [Just out, Just out] `shouldBe` [InputForged, InputForged]
     it "leaves a hash type other than all, and a script, to a node" $ do
       let unsigned = spending "" []
           none = ecdsa k 0x02 (txSigHash btc unsigned pkhScript value 0 sigHashNone)
@@ -124,6 +207,536 @@
       judgeInputs btc (spending (pushing ["anything"]) []) [prev (PayScriptHash h160)]
         `shouldBe` [InputUndecided]
 
+    -- BIP 141: the input script of a witness program nested in a script
+    -- hash "must be exactly a push of the BIP16 redeemScript". Bitcoin Core
+    -- takes the shortest push only, in a block too. The digest does not
+    -- cover the input script, so the signature is as good with any push.
+    it "leaves a nested witness key hash to a node when its program is not pushed by its length" $ do
+      let -- version 0 and the hash of the key, and the coin locked to the hash of those 22 bytes
+          program = hex "00145dedfbf9ea599dd4e3ca6a80b333c472fd0b3f69"
+          locked = Just (TxOut value (hex "a9146ba336543ab7de40a61b3b192cbc51449f9700b087"))
+          sig =
+            hex
+              "304402203e31df15158bff1249b9d8cf8606b9e8ecafc487afbc1c1b1a5d490d\
+              \882756260220368907754469222876fb2914f4dae1f697b30f7c1a2d1115ae16\
+              \122e61ab444601"
+          spend push = spending (hex push <> program) [sig, pub]
+          verdict tx = judgeInputs btc tx [locked]
+      -- the push of 0x16 = 22 bytes
+      verdict (spend "16") `shouldBe` [InputVerified]
+      -- OP_PUSHDATA1, OP_PUSHDATA2 and OP_PUSHDATA4, with a length of 22
+      verdict (spend "4c16") `shouldBe` [InputUndecided]
+      verdict (spend "4d1600") `shouldBe` [InputUndecided]
+      verdict (spend "4e16000000") `shouldBe` [InputUndecided]
+      -- not the form of such an input: not called forged either
+      verdict (tampered (spend "4c16")) `shouldBe` [InputUndecided]
+
+  -- On Bitcoin a block may hold these inputs, and nodes do not relay them.
+  -- 'verifyStdInput' refuses them, and nothing else says verified there.
+  describe "judgeInputs on what Bitcoin does not relay" $ do
+    it "leaves a signature with a high S to a node" $ do
+      let locked = Just (TxOut value (hex "76a9145dedfbf9ea599dd4e3ca6a80b333c472fd0b3f6988ac"))
+          lowS =
+            hex
+              "3044022053d92d1e62bcca206dd7c77d38678770a59da63dcac8cb937fb29f2d\
+              \17e7578c022019a9519939d9302a8d5af75a9d8b8c69852044e1669d2faa3d70\
+              \c1df8dea332301"
+          -- the same signature with n - S for S, n being the order of the
+          -- curve: n - 19a95199...8dea3323 = e656ae66...424c0e1e
+          highS =
+            hex
+              "3045022053d92d1e62bcca206dd7c77d38678770a59da63dcac8cb937fb29f2d\
+              \17e7578c022100e656ae66c626cfd572a508a562747395358e980548ab709182\
+              \619cad424c0e1e01"
+          verdict sig = judgeInputs btc (spending (pushing [sig, pub]) []) [locked]
+      verdict lowS `shouldBe` [InputVerified]
+      verdict highS `shouldBe` [InputUndecided]
+    it "leaves a hybrid key to a node" $ do
+      let -- the key with both coordinates, after 0x06 for an even y
+          hybrid =
+            hex
+              "065cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9\
+              \bc6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264\
+              \da"
+          -- a coin locked to the hash of those 65 bytes, and the signature that spends it
+          locked = Just (TxOut value (hex "76a914db71dd1ddf9d451854b7ec1bdba7ba5e317da0ba88ac"))
+          sig =
+            hex
+              "3044022048cf36bd41def24e245932e5546cb6b379875b7bdf50001bbd7aef3a\
+              \95296c8b022014cc18d596e34a5832971472930ecd76a7b10457ddda46d474f6\
+              \c6a9f305c7a501"
+          spend = spending (pushing [sig, hybrid]) []
+      judgeInputs btc spend [locked] `shouldBe` [InputUndecided]
+      judgeInputs btc (tampered spend) [locked] `shouldBe` [InputForged]
+
+  -- BIP 141: the last item of the witness is the witness script, and
+  -- "SHA256 of the witnessScript must match the 32-byte witness program" of
+  -- the coin. A multisig script has other spellings with the same keys:
+  -- each key after OP_PUSHDATA1 and its length. They are other bytes, with
+  -- another hash. The witness is not part of the transaction id, so anyone
+  -- can make that copy of a spend seen on the network, without a key. The
+  -- signatures stay as they are. The four spends below went to
+  -- Bitcoin Core 32.1 on regtest. It mined the two with the script of the
+  -- coin. It refused the two others, in a block too: "Witness program hash
+  -- mismatch".
+  describe "verifyStdTx and judgeInputs on the witness script of a multisig" $ do
+    let -- the script whose hash the coins hold, and its other spelling
+        committed = directPushes
+        respelled = longPushes
+        -- the script of a coin locked to the committed script: version 0 and its SHA-256
+        native = hex "002063ae81f48889f3ebcce92fc39fbb9fe63e409780e0855ec83a4fd3fbabdb1d97"
+        -- the script of a coin locked to the hash of those 34 bytes, which its spend pushes
+        nested = hex "a914564d22ea4f58d584581a583a1c166b3bac576c9387"
+        nativeSigs =
+          [ hex
+              "3045022100ed7967e9c66f5d5a564fbcc29f50665bcbd32ce570e60745fdad78\
+              \4624f4fe280220162ab62660b642ff8eba5ab63d35b2364c5a231bb86323c01e\
+              \f1c72649bbebf601",
+            hex
+              "304402200f50fde78f7e99ed7e3e62e8daeaba614906874e97badc436611e9bb\
+              \e36b968302205091d9399745a5bc6c195521bab9db4176dc629589e914310946\
+              \871a363fac3d01"
+          ]
+        nestedSigs =
+          [ hex
+              "3045022100f89c908335723920c0a73d9a64f15d84870b2b210c08d17932eb76\
+              \08838a49fc02205942d6ddb90f463c0a14f02ba50fb54722d88f54163e05289c\
+              \bcfd9fd8162e9101",
+            hex
+              "3045022100b2968abc569b51be887d7232a39809c7fc89ff85217b5a4fb51f25\
+              \7328f03a2202201866428e3a11412b028f344aa31aa529c50749c25357213ddd\
+              \4041db6409530001"
+          ]
+        funding = "718e60722e5e95b5d5e8b51c7b127d7a4abe13c7d3b3dc39a3329f6dd2e025ec"
+        -- The spend of an output of the funding transaction, a coin of
+        -- 1,000,000: it pays 998,000, and its witness is the empty item of
+        -- a multisig, the signatures and the witness script.
+        spend n inputScript sigs witnessScript =
+          Tx
+            { version = 2,
+              inputs = [TxIn (OutPoint funding n) inputScript maxBound],
+              outputs = [TxOut 998000 (hex "001479b000887626b294a914501a4cd226b58b235983")],
+              witness = [[""] <> sigs <> [witnessScript]],
+              locktime = 0
+            }
+        spendNative = spend 0 "" nativeSigs
+        spendNested = spend 1 (pushing [native]) nestedSigs
+    it "verify the spend whose witness script is the one the coin commits to, native and nested" $ do
+      verdicts btc native (spendNative committed) `shouldBe` (True, [InputVerified])
+      verdicts btc nested (spendNested committed) `shouldBe` (True, [InputVerified])
+    it "do not verify the spend whose witness script has the same keys in other bytes" $ do
+      verdicts btc native (spendNative respelled) `shouldBe` (False, [InputUndecided])
+      verdicts btc nested (spendNested respelled) `shouldBe` (False, [InputUndecided])
+    it "the transaction id is the same with either witness script" $ do
+      txHash (spendNative committed) `shouldBe` "839c20e76404a63c13f52ba1d0315a021da94d2bf1db35b6cdd87e0a0c184849"
+      txHash (spendNative respelled) `shouldBe` "839c20e76404a63c13f52ba1d0315a021da94d2bf1db35b6cdd87e0a0c184849"
+      txHash (spendNested committed) `shouldBe` "ef83742b3c751f249a87c7bd3c1b67b4c31178f0717ce34db4267822e68ed530"
+      txHash (spendNested respelled) `shouldBe` "ef83742b3c751f249a87c7bd3c1b67b4c31178f0717ce34db4267822e68ed530"
+
+  -- The signature of a multisig input covers the bytes of the script of its
+  -- coin. A coin can be locked to a multisig script whose keys are pushed
+  -- by OP_PUSHDATA1: a signature over the script with direct pushes does
+  -- not open it. A 'ScriptOutput' has no place for the form of a push, so
+  -- such a script is not read as a multisig, and its spend is left to a
+  -- node. The spends below went to a node on regtest. Each coin holds
+  -- 1,000,000.
+  describe "judgeInputs on a multisig coin whose keys are not direct pushes, on Bitcoin" $ do
+    -- Three spends of outputs of one transaction, each with two signatures,
+    -- as Bitcoin Core 32.1 judged them.
+    it "verifies the spend of the coin with direct pushes, which the node mined" $
+      verdicts
+        btc
+        directPushes
+        ( txOf
+            "0200000001ec25e0d26d9f32a339dcb3d3c713be4a7a7d127b1cb5e8d5b5955e\
+            \2e72608e71060000009300483045022100a5387c1620665c031ce80a104208f6\
+            \26374a0781027150f14eb64634b04ec72b022041ffaaf22514397786df9b2b68\
+            \661fdea31c817631279b08e020f8b20362346701483045022100a92973c2d2fe\
+            \b0879cbc3087b19ed14e28a30317e8a5762da9745aaa3b911a8602207d379d91\
+            \88205de7b9716dcad08808a1cf6f878e503100fd5abd265ae3a4641401ffffff\
+            \ff01703a0f000000000016001479b000887626b294a914501a4cd226b58b2359\
+            \8300000000"
+        )
+        `shouldBe` (True, [InputVerified])
+    -- The node refused it in a block: "Script evaluated without error but
+    -- finished with a false/empty top stack element".
+    it "leaves to a node a spend signed over the script with direct pushes, which no block holds" $
+      judged
+        btc
+        longPushes
+        ( txOf
+            "0200000001ec25e0d26d9f32a339dcb3d3c713be4a7a7d127b1cb5e8d5b5955e\
+            \2e72608e71020000009300483045022100e88795128ae0b9b6d40c214ec18db0\
+            \af30f8e767d56aa310a833453ffd8756eb02202824216c8d9970a0e87410a68e\
+            \16a016a399f3c96fee7ce55f1060a4bb7685ed014830450221009353260467d9\
+            \ed68eb8f410a5a20320fcfed9409720649ab1614366d929e6ad002207fa39e2c\
+            \96d486e4434f82a19bb0bcfcea387e42ea1352eef5483668319307db01ffffff\
+            \ff01703a0f000000000016001479b000887626b294a914501a4cd226b58b2359\
+            \8300000000"
+        )
+        `shouldBe` [InputUndecided]
+    -- The node took it in a block, and refused to relay it: "Data push
+    -- larger than necessary".
+    it "leaves to a node a spend signed over the script of the coin, which a block may hold" $
+      judged
+        btc
+        longPushes
+        ( txOf
+            "0200000001ec25e0d26d9f32a339dcb3d3c713be4a7a7d127b1cb5e8d5b5955e\
+            \2e72608e7102000000910047304402207470ee65b26aa2d695dd8600a1855b7b\
+            \2a7a5c9fb0aff53c30468a7ac984ae3f02207bc27899ce27a2dcd083d5206ed2\
+            \93335f6bef709c165a5cb317eba7954bdd3801473044022023a558b88ac8809c\
+            \5a33000ec7b017b6cf52878bb1bca227dec708ae8cfe6d2302200aa7dd56cf11\
+            \bd84894d140f4db2c055de9b13f01b19e7eb0ca571df11ed784801ffffffff01\
+            \703a0f000000000016001479b000887626b294a914501a4cd226b58b23598300\
+            \000000"
+        )
+        `shouldBe` [InputUndecided]
+
+  -- On Bitcoin Cash every push must be the shortest one, in a block too. A
+  -- coin whose script pushes its keys by OP_PUSHDATA1 can never be spent:
+  -- Bitcoin Cash Node 29.2.0 refused each of these spends in a block, "Data
+  -- push larger than necessary", and drops the peer that sends one.
+  describe "judgeInputs on a multisig coin whose keys are not direct pushes, on Bitcoin Cash" $ do
+    let -- two signatures of three keys, each key after the push of its 0x21 = 33 bytes
+        direct =
+          hex
+            "522103bed082a6f8b35a9ac543ddc156457e7a1fb5d7137e4c5386ec562faaff\
+            \3a35ca2102136dcd2e55f06b38331491ccc9768f0d4f77dc956b64384d431c6a\
+            \1c6986615821021d1e6f9a58d67a27fe816ce13bec19c3bdd826af44ed65cc46\
+            \e75b8314782bef53ae"
+        -- the same script with OP_PUSHDATA1 before the length of each key: 0x4c 0x21
+        long =
+          hex
+            "524c2103bed082a6f8b35a9ac543ddc156457e7a1fb5d7137e4c5386ec562faa\
+            \ff3a35ca4c2102136dcd2e55f06b38331491ccc9768f0d4f77dc956b64384d43\
+            \1c6a1c698661584c21021d1e6f9a58d67a27fe816ce13bec19c3bdd826af44ed\
+            \65cc46e75b8314782bef53ae"
+        -- the scripts of the coins locked to the hash of each of the two scripts
+        hashOfDirect = hex "a914a693c2298e10413786f327a0520cf62bf1653ab887"
+        hashOfLong = hex "a9143f449a91b806d6829814e309a919369b1446a71987"
+    it "verifies the spends of the coins with direct pushes, which the node mined" $ do
+      -- ECDSA signatures, of the bare coin
+      verdicts
+        bchRegTest
+        direct
+        ( txOf
+            "02000000012f3a23a55f10c78a8ee83e665cbdc7b3a1cf2815ff2e67a661bf4e\
+            \dc778fa63c0300000092004830450221008f7f827d134d4cb2e0205997dd838b\
+            \72f6d6fffe657fa0473c725ba9c4ce9ffa02201ae06e89fe8aa760b882904448\
+            \be6f38d2001e9f01d6ede050182a7706a8bd6941473044022049831b15326b0f\
+            \ef2e1fea8115b51d457c2bdac599fababd95f7e25136888c2702201ca9878c61\
+            \01d926d6590b776874b70bc6502220b0b072c761ee3dd1cf446d1441ffffffff\
+            \01703a0f00000000001976a91471b6ade29bcdff95817522a958176e1a10a65d\
+            \bf88ac00000000"
+        )
+        `shouldBe` (True, [InputVerified])
+      -- Schnorr signatures, of the coin locked to the hash of the script
+      judged
+        bchRegTest
+        hashOfDirect
+        ( txOf
+            "02000000012f3a23a55f10c78a8ee83e665cbdc7b3a1cf2815ff2e67a661bf4e\
+            \dc778fa63c02000000f0534184d3472649c647ab263caccefb7f5f73e2b01a81\
+            \378defc71e24aad0d0a114449b09ba4ec67cdd4615d077df229f4e30abbb5370\
+            \bdb1ac1e2a37382199aac6064141e408d335002105856d9d10e4d6715923f212\
+            \628e3aead2b576e643ab1ecd373a5cf0228c91bb6ec811f77ec0918bd6e05235\
+            \e025227fd5bb8154019acc71b9f1414c69522103bed082a6f8b35a9ac543ddc1\
+            \56457e7a1fb5d7137e4c5386ec562faaff3a35ca2102136dcd2e55f06b383314\
+            \91ccc9768f0d4f77dc956b64384d431c6a1c6986615821021d1e6f9a58d67a27\
+            \fe816ce13bec19c3bdd826af44ed65cc46e75b8314782bef53aeffffffff0170\
+            \3a0f00000000001976a91471b6ade29bcdff95817522a958176e1a10a65dbf88\
+            \ac00000000"
+        )
+        `shouldBe` [InputVerified]
+    it "leaves to a node a spend of the bare coin with ECDSA signatures over the script with direct pushes" $
+      judged
+        bchRegTest
+        long
+        ( txOf
+            "02000000012f3a23a55f10c78a8ee83e665cbdc7b3a1cf2815ff2e67a661bf4e\
+            \dc778fa63c00000000910047304402206e1f326182c3958f2431249f8b20ef02\
+            \2bdbf522543fb9250d153495deda45b1022058566b3cb6e3ea0d58031e811178\
+            \1d5f84a0287165f73122338c499800480fa94147304402205647841b5b7406a5\
+            \5e4a791ab5388608d09c3adb962ca6bd44c2c71a4262b5bc02206ebaab455b02\
+            \e3c52653cae4c43a0e5cc36a149354b3fd5f66c7b25c96ebd7d141ffffffff01\
+            \703a0f00000000001976a91471b6ade29bcdff95817522a958176e1a10a65dbf\
+            \88ac00000000"
+        )
+        `shouldBe` [InputUndecided]
+    it "leaves to a node a spend of the bare coin with Schnorr signatures over the script with direct pushes" $
+      judged
+        bchRegTest
+        long
+        ( txOf
+            "02000000012f3a23a55f10c78a8ee83e665cbdc7b3a1cf2815ff2e67a661bf4e\
+            \dc778fa63c00000000855341507484b8ba32cb475c439383248cb9b5e911454e\
+            \bc9f009675dcec9a76f12e2ffd034897bd7b45adc70a49f455abfa05d46e5e0f\
+            \602a950e4b8419edd4708c154141277f382eeca3e93a8ef0ca54ead15ea2d351\
+            \34cb2c0466df1993f328b1933d40c3a548d4efb9b3ed840b2fdfb58240ef9cda\
+            \982baebc9d3764ac6606ec08409d41ffffffff01703a0f00000000001976a914\
+            \71b6ade29bcdff95817522a958176e1a10a65dbf88ac00000000"
+        )
+        `shouldBe` [InputUndecided]
+    it "leaves to a node such a spend of the coin locked to the hash of the script" $
+      judged
+        bchRegTest
+        hashOfLong
+        ( txOf
+            "02000000012f3a23a55f10c78a8ee83e665cbdc7b3a1cf2815ff2e67a661bf4e\
+            \dc778fa63c01000000f35341c867eaec03b91941010cda272a0745f944e9d7f8\
+            \7904232eacd59012db39b35be264e5bfedc52e802cb3ce39620ec1d28500b68f\
+            \1b8235210c0c8cf985ba9d414141b089c593e1b3152a04a280ea50402523017e\
+            \2b725ba3da7d32c91cf8fb34ab75a676957d280bfeabf17f3bb18e501381b785\
+            \5be35fe62495194643e61caf9ebe414c6c524c2103bed082a6f8b35a9ac543dd\
+            \c156457e7a1fb5d7137e4c5386ec562faaff3a35ca4c2102136dcd2e55f06b38\
+            \331491ccc9768f0d4f77dc956b64384d431c6a1c698661584c21021d1e6f9a58\
+            \d67a27fe816ce13bec19c3bdd826af44ed65cc46e75b8314782bef53aeffffff\
+            \ff01703a0f00000000001976a91471b6ade29bcdff95817522a958176e1a10a6\
+            \5dbf88ac00000000"
+        )
+        `shouldBe` [InputUndecided]
+
+  -- Bitcoin Cash applies to every block three rules of encoding that Bitcoin
+  -- applies only to what it relays: the S of an ECDSA signature is low
+  -- (LOW_S), a key is compressed or uncompressed (STRICTENC), and data is
+  -- pushed by the shortest push that holds it (MINIMALDATA). Each
+  -- transaction below went to Bitcoin Cash Node 29.2.0 on regtest. Its first
+  -- input is a plain spend, and its second input is the one that the test
+  -- is about. The node took the transactions that keep the three rules. It
+  -- refused each other one with "mandatory-script-verify-flag-failed", the
+  -- reason for which it drops the peer that sent the transaction.
+  describe "verifyStdTx and judgeInputs on what no block of Bitcoin Cash holds" $ do
+    let -- the script of the coin of the first input, locked to a key hash
+        first = hex "76a914670caa79e51d78ed0c583b89ff39d9c49b7199e788ac"
+        -- the coin of the second input, locked to the hash of the key 02552c63...2a84
+        keyHash = hex "76a914db3f00d429f2715383cc594258ec11d6de52669788ac"
+        -- a transaction up to the input script of its second input, which
+        -- spends the coin locked to the key hash
+        start =
+          "0200000002bd30e74505225b6e250d6254e743c9375329f1ec140c0f330c2a81\
+          \fe77493ab60f0000006b483045022100df1a1c4bef63f9d732768d57b3cd690b\
+          \6d343029b41fe88f5d19f251338face902201661eaffaf61e3a60c055d736289\
+          \60ae09346c5f77e38c415a59e7812c0e28b041210256b328b30c8bf5839e2405\
+          \8747879408bdb36241dc9c2e7c619faa12b2920967fdffffffbd30e74505225b\
+          \6e250d6254e743c9375329f1ec140c0f330c2a81fe77493ab603000000"
+        -- what follows that input script: the sequence, two outputs and the lock time
+        end =
+          "fdffffff02a0bb0d00000000001976a91479b000887626b294a914501a4cd226\
+          \b58b23598388acc07a1000000000001976a914ebc0ee0b2ab9e8277a600c2514\
+          \75e22a3241a1c188ac00000000"
+        -- the answers for the transaction whose second input has this
+        -- script, written after its length
+        spend script = verdictsOf bchRegTest [first, keyHash] (txOf (start <> script <> end))
+    it "verify the spends that keep the three rules, which the node took" $ do
+      -- an ECDSA signature after the push of its 0x48 = 72 bytes, then the
+      -- key after the push of its 0x21 = 33 bytes
+      spend
+        "6b483045022100fe866c7d7a79393c11175ad82fc8de9350f31a11394a827fcb\
+        \bf66ea1d2cf0b302204ed891157ee41a89f5a4c23fe3e4fc2f1cd1498d4e5ec3\
+        \75029f6f849e137f4e412102552c630b64b54bf50210c9e253d38bd4949c72e2\
+        \2873500f6285c2bede312a84"
+        `shouldBe` (True, [InputVerified, InputVerified])
+      -- a Schnorr signature after the push of its 0x41 = 65 bytes, which
+      -- 'verifyStdTx' does not read
+      spend
+        "64412eafe74e802f469cb0fcbdbbe31884691f205a1a56b2d93b36d779323f47\
+        \05cc25358fda1954d7b9f39a5f4221f6d08850b2b799ebfd0abdcb1f44ce0cea\
+        \a70b412102552c630b64b54bf50210c9e253d38bd4949c72e22873500f6285c2\
+        \bede312a84"
+        `shouldBe` (False, [InputVerified, InputVerified])
+    it "do not verify an ECDSA signature with a high S" $
+      -- the first signature above with n - S for S, n being the order of
+      -- the curve: n - 4ed89115...9e137f4e = b1276eea...3222c1f3
+      spend
+        "6c493046022100fe866c7d7a79393c11175ad82fc8de9350f31a11394a827fcb\
+        \bf66ea1d2cf0b3022100b1276eea811be5760a5b3dc01c1b03cf9ddd935960e9\
+        \dcc6bd32ef083222c1f3412102552c630b64b54bf50210c9e253d38bd4949c72\
+        \e22873500f6285c2bede312a84"
+        `shouldBe` (False, [InputVerified, InputUndecided])
+    it "do not verify a key in the hybrid form" $
+      -- The second input spends a coin locked to the hash of the same key
+      -- written with both coordinates after 0x06, and its signature is
+      -- good.
+      verdictsOf
+        bchRegTest
+        [first, hex "76a9143f20fee78bcb773cf5be7ee3f12e7ffc340830c788ac"]
+        ( txOf
+            "0200000002bd30e74505225b6e250d6254e743c9375329f1ec140c0f330c2a81\
+            \fe77493ab60f0000006b483045022100c3d639833017a65fa7bed3a3cd7f9c85\
+            \c60cc0f55a70d84719bc9e8fda30bde9022078aee3f447ed47044c7947b62619\
+            \b05b61f6128b1abd9687f2de29b04ed0ba5f41210256b328b30c8bf5839e2405\
+            \8747879408bdb36241dc9c2e7c619faa12b2920967fdffffffbd30e74505225b\
+            \6e250d6254e743c9375329f1ec140c0f330c2a81fe77493ab60d0000008b4830\
+            \45022100c151bff7da6ba95495aacb8ff59e2c6b7b49764121ae559e11242713\
+            \d29b5b5c022029eafd90bc648920c18f6ecbc4678e3a6f5214e9a0774cda0beb\
+            \827cb6905c91414106552c630b64b54bf50210c9e253d38bd4949c72e2287350\
+            \0f6285c2bede312a84e3ca35a0c8c0cf4c40398e720377e1ee09c7a6b0fd0568\
+            \3d5fe02d8f68231466fdffffff02a0bb0d00000000001976a91479b000887626\
+            \b294a914501a4cd226b58b23598388acc07a1000000000001976a914ebc0ee0b\
+            \2ab9e8277a600c251475e22a3241a1c188ac00000000"
+        )
+        `shouldBe` (False, [InputVerified, InputUndecided])
+    it "do not verify a key or an ECDSA signature that is not pushed by the shortest push" $ do
+      -- the valid spend with OP_PUSHDATA1 before the length of the key: 0x4c 0x21
+      spend
+        "6c483045022100fe866c7d7a79393c11175ad82fc8de9350f31a11394a827fcb\
+        \bf66ea1d2cf0b302204ed891157ee41a89f5a4c23fe3e4fc2f1cd1498d4e5ec3\
+        \75029f6f849e137f4e414c2102552c630b64b54bf50210c9e253d38bd4949c72\
+        \e22873500f6285c2bede312a84"
+        `shouldBe` (False, [InputVerified, InputUndecided])
+      -- the valid spend with OP_PUSHDATA2 before the length of the signature: 0x4d 0x48 0x00
+      spend
+        "6d4d48003045022100fe866c7d7a79393c11175ad82fc8de9350f31a11394a82\
+        \7fcbbf66ea1d2cf0b302204ed891157ee41a89f5a4c23fe3e4fc2f1cd1498d4e\
+        \5ec375029f6f849e137f4e412102552c630b64b54bf50210c9e253d38bd4949c\
+        \72e22873500f6285c2bede312a84"
+        `shouldBe` (False, [InputVerified, InputUndecided])
+    it "do not verify a Schnorr signature that is not pushed by the shortest push" $
+      -- the valid spend with OP_PUSHDATA4 before the length of the signature: 0x4e 0x41 0x00 0x00 0x00
+      spend
+        "684e410000002eafe74e802f469cb0fcbdbbe31884691f205a1a56b2d93b36d7\
+        \79323f4705cc25358fda1954d7b9f39a5f4221f6d08850b2b799ebfd0abdcb1f\
+        \44ce0ceaa70b412102552c630b64b54bf50210c9e253d38bd4949c72e2287350\
+        \0f6285c2bede312a84"
+        `shouldBe` (False, [InputVerified, InputUndecided])
+    it "do not verify a multisig with Schnorr signatures whose field of bits is not pushed by its opcode" $ do
+      let -- the coin of the second input: two signatures of three keys
+          twoOfThree =
+            hex
+              "522102552c630b64b54bf50210c9e253d38bd4949c72e22873500f6285c2bede\
+              \312a8421030f0fb9a244ad31a369ee02b7abfbbb0bfa3812b9a39ed93346d03d\
+              \67d412d17721022f1b310f4c065331bc0d79ba4661bb9822d67d7c4a1b0a1892\
+              \e1fd0cd23aa68d53ae"
+          -- a transaction up to the input script of its second input,
+          -- which spends that coin
+          startOfMultisig =
+            "0200000002bd30e74505225b6e250d6254e743c9375329f1ec140c0f330c2a81\
+            \fe77493ab60f0000006a47304402207b92790f3145f2c30048db725e7e184d0f\
+            \56e2d921ec5d7548118e8bb75e4c9b022026f590f98b3d50c6fe8c4e19ef62c5\
+            \4160813fb917b5d03b2c7419a5165fab7d41210256b328b30c8bf5839e240587\
+            \47879408bdb36241dc9c2e7c619faa12b2920967fdffffffbd30e74505225b6e\
+            \250d6254e743c9375329f1ec140c0f330c2a81fe77493ab606000000"
+          spendOfMultisig script =
+            verdictsOf bchRegTest [first, twoOfThree] (txOf (startOfMultisig <> script <> end))
+      -- The bits 0b011 name the first two keys. The node took them as
+      -- OP_3, the byte 0x53, before the two signatures.
+      spendOfMultisig
+        "85534189ad1a4e4571427393606bf673906fcd23b34b272565c61c402b02f3bf\
+        \0f70391154fb060bc776c427772c1ec7379f3c31b14171bcdc978867887acbba\
+        \3d5dbb4141f77f97c4a106af0a26e39a0dd7cb740ba1e0c2bc90cddb70adc18c\
+        \89b1969f0a5f0c4e02f0182b3c2c816d11bfb0568b1381d22e1c308fa5d081b7\
+        \f44543351b41"
+        `shouldBe` (False, [InputVerified, InputVerified])
+      -- the same bits as one byte of data after OP_PUSHDATA1: 0x4c 0x01 0x03
+      spendOfMultisig
+        "874c01034189ad1a4e4571427393606bf673906fcd23b34b272565c61c402b02\
+        \f3bf0f70391154fb060bc776c427772c1ec7379f3c31b14171bcdc978867887a\
+        \cbba3d5dbb4141f77f97c4a106af0a26e39a0dd7cb740ba1e0c2bc90cddb70ad\
+        \c18c89b1969f0a5f0c4e02f0182b3c2c816d11bfb0568b1381d22e1c308fa5d0\
+        \81b7f44543351b41"
+        `shouldBe` (False, [InputVerified, InputUndecided])
+    -- The second input spends a coin locked to the hash of a script that
+    -- asks for two signatures of eight keys. The first and the last key
+    -- sign, so the bits are 0b10000001, the byte 0x81.
+    describe "a multisig with Schnorr signatures whose field of bits is 0x81" $ do
+      let twoOfEight = hex "a914cc42e7ae705e45609df7c35f91739beb07503a9a87"
+          -- a transaction up to the input script of its second input
+          startOfEight =
+            "020000000297840471ad17d047f8eaeea6be46191efe4b06de6ff022bfe7531b\
+            \75539f49a3100000006b483045022100c716c53177583c6cba7d5821e4cc5efb\
+            \a9f55f5b8bdad8dd841687449318cf2f0220160b350f4c8ff8dec0470624947a\
+            \d71ac8d6cbfc12930ba49df8b9c05f098f5941210256b328b30c8bf5839e2405\
+            \8747879408bdb36241dc9c2e7c619faa12b2920967fdffffff97840471ad17d0\
+            \47f8eaeea6be46191efe4b06de6ff022bfe7531b75539f49a30d000000"
+          -- what follows the bits in that input script: the two signatures,
+          -- and the script of 0x0113 = 275 bytes after OP_PUSHDATA2
+          afterBits =
+            "4142ca12be6b6f5ffef66a83bdeac7384577fd651e34383da87ed19ebca0f8e0\
+            \2fcdbb95bb8b706787119e73d084c0f350273abbdec260704b622e11356137f6\
+            \d541418a7a0a965224e2b0524fbfbe9da002d7f892ebdcf834d1e81290c910ac\
+            \1a276fca0598732282028495ef858d6c900e10244f996860fa0e18e25818167c\
+            \88d0f7414d1301522102552c630b64b54bf50210c9e253d38bd4949c72e22873\
+            \500f6285c2bede312a8421030f0fb9a244ad31a369ee02b7abfbbb0bfa3812b9\
+            \a39ed93346d03d67d412d17721022f1b310f4c065331bc0d79ba4661bb9822d6\
+            \7d7c4a1b0a1892e1fd0cd23aa68d210299c2aa85d2b21a62f396907a802a58e5\
+            \21dafd5bddaccbd72786eea189bc4dc921021a7a569e91dbf60581509c7fc946\
+            \d1003b60c7dee85299538db6353538d595742103a92c9b7cac68758de5783ed8\
+            \e5123598e4ad137091e42987d3bad8a08e35bf3d21034f355bdcb7cc0af728ef\
+            \3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa21036360e856310ce5d2\
+            \94e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f758ae"
+          spendOfEight script = verdictsOf bchRegTest [first, twoOfEight] (txOf (startOfEight <> script <> end))
+      -- The shortest push of the byte 0x81 is OP_1NEGATE, the byte 0x4f. The
+      -- input script is 1 + 410 = 411 bytes long, 0x019b.
+      it "verify it when OP_1NEGATE pushes the bits, which the node took" $
+        spendOfEight ("fd9b014f" <> afterBits) `shouldBe` (False, [InputVerified, InputVerified])
+      -- The same bits as one byte of data: 0x01 0x81. The node: "Data push
+      -- larger than necessary".
+      it "do not verify it when the bits are pushed as a byte of data" $
+        spendOfEight ("fd9c010181" <> afterBits) `shouldBe` (False, [InputVerified, InputUndecided])
+    -- On Bitcoin a block may hold that push, and nodes do not relay it
+    it "on Bitcoin, do not verify a key that is not pushed by the shortest push either" $ do
+      let sig = ecdsa k 0x01 (txSigHash btc (spending "" []) pkhScript value 0 sigHashAll)
+          -- the key after OP_PUSHDATA1 and its length
+          tx = spending (runPutS (serialize (Script [opPushData sig, OP_PUSHDATA pub OPDATA1]))) []
+      verifyStdTx btc tx [(PayPKHash h160, value, coin)] `shouldBe` False
+      judgeInputs btc tx [prev (PayPKHash h160)] `shouldBe` [InputUndecided]
+
+  -- Transactions that Bitcoin Cash Node 29.2.0 and Bitcoin Core 32.1 judged
+  -- on regtest. Each has one input, signed by the key 03974d27...ce40 with a
+  -- good ECDSA signature whose r and s take 29 bytes each: its DER form is
+  -- 6 + 29 + 29 = 64 bytes, where most signatures have 70 to 72. Bitcoin
+  -- Cash Node reads a signature of 64 bytes as a Schnorr signature. It
+  -- refused both transactions with "mandatory-script-verify-flag-failed",
+  -- the reason for which it drops the peer that sent the transaction.
+  describe "verifyStdTx and judgeInputs on an ECDSA signature of 64 bytes" $ do
+    it "on Bitcoin Cash, say forged of a key hash input, where the node reads a Schnorr signature" $
+      -- The node: "Signature must be zero for failed CHECK(MULTI)SIG
+      -- operation". The signature is after the push of its 0x41 = 65
+      -- bytes: 64 and the hash type.
+      verdicts
+        bchRegTest
+        (hex "76a91473dd2b9cb7ce0af55615372357094ba779b743e588ac")
+        ( txOf
+            "02000000012106f47f465220eccf0f8bf413656ba995d6e2241703ca77b2bc32\
+            \053a922e2c000000006441303e021d412389f0428046438bea9c0e2427db23ab\
+            \0bce6fe36d851e0dc86b41ed021d20576521b06f9bc52aacf1dee9900a53c82c\
+            \9e9ad11dae4edc0d6164db412103974d27bb4ae05f5f64805ba2d39802f702e1\
+            \3213b52d10e048e7daaf063bce40ffffffff01583e0f00000000001976a91400\
+            \79e2c6e56eccf59e088ee40cfd3b503362157c88acec135901"
+        )
+        `shouldBe` (False, [InputForged])
+    it "on Bitcoin Cash, do not verify a multisig input, where the node takes no signature of that length" $
+      -- The node: "Signature cannot be 65 bytes in CHECKMULTISIG". The coin
+      -- is locked to the hash of a script that asks for one signature of
+      -- two keys.
+      verdicts
+        bchRegTest
+        (hex "a914d52daac634cd249e6674061cf065f05cf388213587")
+        ( txOf
+            "0200000001d0f0c7264bb826a67ef0ec644850b16b222507010305eddc64cb69\
+            \193f57531b000000008b0041303e021d412389f0428046438bea9c0e2427db23\
+            \ab0bce6fe36d851e0dc86b41ed021d2bb4f160b75b0483b12fa6b358c685c20c\
+            \04299e64c997a0605bbaeea94147512103974d27bb4ae05f5f64805ba2d39802\
+            \f702e13213b52d10e048e7daaf063bce402102d77b272781a48f7a51de424305\
+            \f88043665e45d084546195268a458c675db59552aeffffffff01583e0f000000\
+            \00001976a9140079e2c6e56eccf59e088ee40cfd3b503362157c88ac29983f00"
+        )
+        `shouldBe` (False, [InputUndecided])
+    it "on Bitcoin, verify a witness key hash input, which the node put in a block" $
+      verdicts
+        btcRegTest
+        (hex "001473dd2b9cb7ce0af55615372357094ba779b743e5")
+        ( txOf
+            "02000000000101a9e92b1b6c32297125fbe2ec62992e4f0367bb79e16d6bf2e6\
+            \192c681e7bc3480100000000ffffffff01583e0f00000000001976a9140079e2\
+            \c6e56eccf59e088ee40cfd3b503362157c88ac0241303e021d412389f0428046\
+            \438bea9c0e2427db23ab0bce6fe36d851e0dc86b41ed021d45d27dbe1a69e0b6\
+            \a7fdd755a5050c8aa396901d3d6e15a054bead1bda012103974d27bb4ae05f5f\
+            \64805ba2d39802f702e13213b52d10e048e7daaf063bce40904ce700"
+        )
+        `shouldBe` (True, [InputVerified])
+
   describe "judgeInputs on Bitcoin Cash" $ do
     let unsigned = spending "" []
         digest prefix = txSigHashCashToken bch unsigned prefix pkhScript value 0 (setForkIdFlag sigHashAll)
@@ -147,9 +760,8 @@
     -- regtest, both with Schnorr signatures. The first spends a coinbase
     -- of 50 coins to the same key and makes 1,000 fungible tokens. The
     -- second spends that output, tokens and all.
-    let parse h = either error id (runGetS deserialize (fromJust (decodeHex h))) :: Tx
-        genesis =
-          parse
+    let genesis =
+          txOf
             "0200000001f28fd1cdb4293ae6bb76e580c5a3469fb926690471f3ffb798ef0a\
             \cda9886525000000006441e31c237fe3a1a45f6c32c779c78025f29bd735fa44\
             \d18c182bc1c08fbbcab25f08cbd8c1937dccd38acf37ef2bf8907e75029d622c\
@@ -158,7 +770,7 @@
             \cdb4293ae6bb76e580c5a3469fb926690471f3ffb798ef0acda988652510fde8\
             \0376a9145dd6bc82b5a42053b8f7802e68d296ac3578537a88ac00000000"
         spend =
-          parse
+          txOf
             "0200000001db5f2a09c11a2aaceb0d9bfa755006380257d48dab94a73cfd4d69\
             \c2e2d122a6000000006441f52f838cf46e41b8c630334d2b6edefdb49f67fd19\
             \45ee864321da50b1fa652b6b2db4b517110ee5598cbf5193eac763a56d59bfe2\
@@ -210,40 +822,58 @@
       verdict (spendWith OP_5 [ecdsaSig, sign (secrets !! 2)]) `shouldBe` [InputUndecided]
 
   describe "verifyStdInput on a multisig of Taproot" $ do
-    let secrets = map secret [11, 12, 13]
-        xOnly = B.drop 1 . pubBytes
-        leaf =
-          Script $
-            [opPushData (xOnly (head secrets)), OP_CHECKSIG]
-              <> concat [[opPushData (xOnly s), OP_CHECKSIGADD] | s <- drop 1 secrets]
-              <> [OP_2, OP_NUMEQUAL]
+    let xOnly = B.drop 1 . pubBytes
         internal = derivePubKey (secret 14)
-        tree = TaprootOutput {internalKey = internal, mast = Just (MASTLeaf tapscriptLeafVersion leaf)}
-        out = TxOut value (encodeSerial (taprootScriptOutput tree))
         unsigned = spending "" []
-        leafOf = Just (leafHash tapscriptLeafVersion leaf, 0xffffffff)
-        digest = either error id (taprootSigHash unsigned [out] 0 sigHashDefault Nothing leafOf)
-        sign s = (signSchnorr s (hashToMsg digest)).get
-        spendWith items =
-          let path =
-                ScriptPathSpend
-                  ScriptPathData
-                    { annex = Nothing,
-                      stack = items,
-                      script = leaf,
-                      extIsOdd = odd (keyParity (taprootOutputKey tree)),
-                      leafVersion = tapscriptLeafVersion,
-                      internalKey = internal,
-                      control = [],
-                      opaqueScript = Nothing
-                    }
-           in unsigned {witness = [either error id (encodeTaprootWitness path)]} :: Tx
+        -- A coin of one leaf, the multisig of the keys of these secrets
+        -- that asks for this number of signatures: its tree, its output,
+        -- the signature of a secret over the spend of the leaf, and that
+        -- spend with these witness items.
+        multisigCoin asked keys = (tree, out, sign, spendWith)
+          where
+            leaf =
+              Script $
+                [opPushData (xOnly (head keys)), OP_CHECKSIG]
+                  <> concat [[opPushData (xOnly s), OP_CHECKSIGADD] | s <- drop 1 keys]
+                  <> [asked, OP_NUMEQUAL]
+            tree = TaprootOutput {internalKey = internal, mast = Just (MASTLeaf tapscriptLeafVersion leaf)}
+            out = TxOut value (encodeSerial (either error id (taprootScriptOutput tree)))
+            leafOf = Just (leafHash tapscriptLeafVersion leaf, 0xffffffff)
+            digest = either error id (taprootSigHash unsigned [out] 0 sigHashDefault Nothing leafOf)
+            sign s = (signSchnorr s (hashToMsg digest)).get
+            spendWith items =
+              let path =
+                    ScriptPathSpend
+                      ScriptPathData
+                        { annex = Nothing,
+                          stack = items,
+                          script = leaf,
+                          extIsOdd = odd (keyParity (either error id (taprootOutputKey tree))),
+                          leafVersion = tapscriptLeafVersion,
+                          internalKey = internal,
+                          control = [],
+                          opaqueScript = Nothing
+                        }
+               in unsigned {witness = [either error id (encodeTaprootWitness path)]} :: Tx
+        secrets = map secret [11, 12, 13]
+        (tree, out, sign, spendWith) = multisigCoin OP_2 secrets
         verdict tx = judgeInputs btc tx [Just out]
+        -- The spend of a leaf that asks for one signature of this many
+        -- keys, signed by the first key: an empty item for each other key,
+        -- then the signature. The answers of 'verifyStdInput' and of
+        -- 'judgeInputs' for it.
+        oneOf count = (verifyStdInput btc spend [(bigCoin, value, coin)] 0, verdictOf)
+          where
+            bigCoin = either error id (taprootScriptOutput bigTree)
+            keys = map secret [1001 .. 1000 + count]
+            (bigTree, bigOut, bigSign, bigSpend) = multisigCoin OP_1 keys
+            spend = bigSpend (replicate (fromIntegral count - 1) "" <> [bigSign (secret 1001)])
+            verdictOf = judgeInputs btc spend [Just bigOut]
     it "verifies two signatures of three keys, with an item for each key, the last first" $ do
       verdict (spendWith [sign (secrets !! 2), "", sign (head secrets)]) `shouldBe` [InputVerified]
       verdict (spendWith ["", sign (secrets !! 1), sign (head secrets)]) `shouldBe` [InputVerified]
       let lastTwo = spendWith [sign (secrets !! 2), sign (secrets !! 1), ""]
-      verifyStdInput btc lastTwo [(taprootScriptOutput tree, value, coin)] 0 `shouldBe` True
+      verifyStdInput btc lastTwo [(either error id (taprootScriptOutput tree), value, coin)] 0 `shouldBe` True
     it "does not verify one signature, three, a signature of another key, or one of other outputs" $ do
       verdict (spendWith ["", "", sign (head secrets)]) `shouldBe` [InputUndecided]
       verdict (spendWith [sign (secrets !! 2), sign (secrets !! 1), sign (head secrets)]) `shouldBe` [InputUndecided]
@@ -252,6 +882,15 @@
       verdict (tampered (spendWith [sign (secrets !! 2), "", sign (head secrets)])) `shouldBe` [InputUndecided]
       -- an item for a key is missing
       verdict (spendWith [sign (secrets !! 1), sign (head secrets)]) `shouldBe` [InputUndecided]
+    -- The stack holds at most 1000 items after each opcode (BIP 342). The
+    -- witness puts an item there for each key, and the script first pushes
+    -- a key on top of them: 999 + 1 = 1000.
+    it "verifies a leaf of 999 keys, the most that a block can hold" $
+      oneOf 999 `shouldBe` (True, [InputVerified])
+    -- 1000 + 1 = 1001 items. Bitcoin Core 32.1 refuses the spend in a
+    -- block: "Stack size limit exceeded".
+    it "does not verify a leaf of 1000 keys, whose signature is good: no block can hold its spend" $
+      oneOf 1000 `shouldBe` (False, [InputUndecided])
 
   describe "splitTokenPrefix" $ do
     let category = B.replicate 32 0xaa
@@ -273,6 +912,294 @@
       splitTokenPrefix ("\xef" <> category <> "\x10\x00" <> script) `shouldBe` Nothing
       splitTokenPrefix ("\xef" <> category <> "\x10\xfd\x05\x00" <> script) `shouldBe` Nothing
       splitTokenPrefix ("\xef" <> category) `shouldBe` Nothing
+
+  -- Spends of the outputs of one transaction, each a coin of 1,000,000, as
+  -- Bitcoin Core 32.1 judged them on regtest with the relay policy of
+  -- mainnet (-acceptnonstdtxn=0). It took every one of them in a block,
+  -- and its mempool refused some. The verifiers answer for the mempool: a
+  -- caller hands a verified transaction to its peers.
+  describe "verifyStdTx and judgeInputs on spends that Bitcoin Core 32.1 takes in a block" $ do
+    let -- a coin of the hash of a compressed key
+        keyHashCoin = hex "76a91479b000887626b294a914501a4cd226b58b23598388ac"
+        -- a coin of the hash of a multisig script: one signature of two
+        -- compressed keys
+        scriptHashCoin = hex "a914e75f3c8e0ac1f7a0257aa5224fbca71ae406f1be87"
+        -- a coin of the hash of an uncompressed key, version 0
+        witnessKeyHashCoin = hex "00146ff3443c994fb2c821969dae53bd5b5052d8394f"
+        -- the same witness program in a script hash
+        nestedKeyHashCoin = hex "a914d2ceb3d73c391a8aeb3a26de640112a32142d6fa87"
+        -- a coin of the hash of a witness script: an uncompressed key and
+        -- OP_CHECKSIG
+        witnessKeyCoin =
+          hex
+            "00208b47cde638bfae62a33fc0e99c5080e26c26fb72b8336fb612c2b15b5203\
+            \0a90"
+        -- a coin of the hash of a witness script that names the hash of an
+        -- uncompressed key
+        witnessScriptKeyHashCoin =
+          hex
+            "0020c1ef90ba4e56f20642830c9aa414cc739e5c78eda0b10542783afba9be1b\
+            \51ba"
+        -- a coin of the hash of a witness script: one signature of an
+        -- uncompressed key or of a compressed key, in that order
+        uncompressedFirstCoin =
+          hex
+            "00208bd26d11700bfe773d46cd6afafd62dc593309a150fbd43e6725346e1752\
+            \072c"
+        -- the same with the compressed key first
+        uncompressedLastCoin =
+          hex
+            "0020c062f57c576e379b94f85af81a91df800027c1e396a95d188a6faa75bc48\
+            \0596"
+        -- a Taproot coin without a script tree
+        taprootKeyCoin =
+          hex
+            "51208c5db7f797196d6edc4dd7df6048f4ea6b883a6af6af032342088f436543\
+            \790f"
+        -- a Taproot coin with one leaf: a key and OP_CHECKSIG
+        taprootLeafCoin =
+          hex
+            "51202d5f0e6381d7ae8ac0398aed9667dce8ae22ec0052ff0d7f4da46dafc4e3\
+            \0108"
+        keyHashSpend =
+          txOf
+            "02000000011167db886c9b3a5684c47b5c8c8f05962dfd4b6e8d5624fba50e26\
+            \29504c5657000000006a47304402207574cc799e4fb6dd2fa4f12fb566abf877\
+            \7861ce44deaa804e649e1168beb6b002202384dd2ae1c07854407fbc0f866e57\
+            \33c3cfeb40c79bce978961b83cb0d04c8c0121031b84c5567b126440995d3ed5\
+            \aaba0565d71e1834604819ff9c17f5e9d5dd078fffffffff01703a0f00000000\
+            \0016001479b000887626b294a914501a4cd226b58b23598300000000"
+        keyByLongerPush =
+          txOf
+            "02000000011167db886c9b3a5684c47b5c8c8f05962dfd4b6e8d5624fba50e26\
+            \29504c5657000000006b47304402207574cc799e4fb6dd2fa4f12fb566abf877\
+            \7861ce44deaa804e649e1168beb6b002202384dd2ae1c07854407fbc0f866e57\
+            \33c3cfeb40c79bce978961b83cb0d04c8c014c21031b84c5567b126440995d3e\
+            \d5aaba0565d71e1834604819ff9c17f5e9d5dd078fffffffff01703a0f000000\
+            \000016001479b000887626b294a914501a4cd226b58b23598300000000"
+        scriptHashSpend =
+          txOf
+            "02000000011167db886c9b3a5684c47b5c8c8f05962dfd4b6e8d5624fba50e26\
+            \29504c5657010000009100473044022031e52014a10d4859e400d9931434a47c\
+            \d7964088348f79fd1ba55a57f84c12e502201b65c5e8d3a861b7f4e205d1e94e\
+            \eec9e3961eb2a98bc5bf441e9eb49597880601475121031b84c5567b12644099\
+            \5d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f21024d4b6cd1361032\
+            \ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076652aeffffffff01\
+            \703a0f000000000016001479b000887626b294a914501a4cd226b58b23598300\
+            \000000"
+        redeemByLongerPush =
+          txOf
+            "02000000011167db886c9b3a5684c47b5c8c8f05962dfd4b6e8d5624fba50e26\
+            \29504c5657010000009300473044022031e52014a10d4859e400d9931434a47c\
+            \d7964088348f79fd1ba55a57f84c12e502201b65c5e8d3a861b7f4e205d1e94e\
+            \eec9e3961eb2a98bc5bf441e9eb495978806014d47005121031b84c5567b1264\
+            \40995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f21024d4b6cd136\
+            \1032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076652aeffffff\
+            \ff01703a0f000000000016001479b000887626b294a914501a4cd226b58b2359\
+            \8300000000"
+        witnessKeyHashSpend =
+          txOf
+            "020000000001011167db886c9b3a5684c47b5c8c8f05962dfd4b6e8d5624fba5\
+            \0e2629504c56570200000000ffffffff01703a0f000000000016001479b00088\
+            \7626b294a914501a4cd226b58b2359830248304502210093609da44ddaf3757f\
+            \c14b431f54ad4fbfb5f32f1e7d0d34abbb410ad7d7e48002203eb623d51fad39\
+            \a530b8f681b10a1ac0b37efcc72167dc6d6e6e66968301fb160141041b84c556\
+            \7b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f70beaf8f\
+            \588b541507fed6a642c5ab42dfdf8120a7f639de5122d47a69a8e8d100000000"
+        nestedKeyHashSpend =
+          txOf
+            "020000000001011167db886c9b3a5684c47b5c8c8f05962dfd4b6e8d5624fba5\
+            \0e2629504c565703000000171600146ff3443c994fb2c821969dae53bd5b5052\
+            \d8394fffffffff01703a0f000000000016001479b000887626b294a914501a4c\
+            \d226b58b23598302483045022100b905c7bb775f5276373c64424208db35afa3\
+            \196666956710a2415706838aa10802202f535fcc6f9dbe5878f9b365dd7130d0\
+            \bf8d20d1b7b7ed362c63efb7bcdbdf110141041b84c5567b126440995d3ed5aa\
+            \ba0565d71e1834604819ff9c17f5e9d5dd078f70beaf8f588b541507fed6a642\
+            \c5ab42dfdf8120a7f639de5122d47a69a8e8d100000000"
+        witnessKeySpend =
+          txOf
+            "020000000001011167db886c9b3a5684c47b5c8c8f05962dfd4b6e8d5624fba5\
+            \0e2629504c56570400000000ffffffff01703a0f000000000016001479b00088\
+            \7626b294a914501a4cd226b58b23598302483045022100d77b5a74faaaffdd2b\
+            \7668b220ca7eb787a603ceeb3c74ec30873a43fdb8368d022000a04bc6344baa\
+            \34e071a3d6d51429f108b447a1cc860392aee2a020af6cb036014341041b84c5\
+            \567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f70beaf\
+            \8f588b541507fed6a642c5ab42dfdf8120a7f639de5122d47a69a8e8d1ac0000\
+            \0000"
+        witnessScriptKeyHashSpend =
+          txOf
+            "020000000001011167db886c9b3a5684c47b5c8c8f05962dfd4b6e8d5624fba5\
+            \0e2629504c56570500000000ffffffff01703a0f000000000016001479b00088\
+            \7626b294a914501a4cd226b58b23598303483045022100b1935dbe6ca24c14e9\
+            \2320e81580fbb7ef722e9b234f4e50377c07c38d2244c202205615266de48c84\
+            \d5071c98026dd96cb3491f500d2ce0d7f15e9b05f559c7a0370141041b84c556\
+            \7b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f70beaf8f\
+            \588b541507fed6a642c5ab42dfdf8120a7f639de5122d47a69a8e8d11976a914\
+            \6ff3443c994fb2c821969dae53bd5b5052d8394f88ac00000000"
+        firstSignedByUncompressed =
+          txOf
+            "020000000001011167db886c9b3a5684c47b5c8c8f05962dfd4b6e8d5624fba5\
+            \0e2629504c56570600000000ffffffff01703a0f000000000016001479b00088\
+            \7626b294a914501a4cd226b58b2359830300483045022100b3e607710b0554c7\
+            \7128b2837b9a80fbf59338ed84b6ac083fccdd8eede92d89022013978a0b0220\
+            \f58d02e968fb9beba93845e14ed45804add23ef52f1b104dca8801675141041b\
+            \84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f70\
+            \beaf8f588b541507fed6a642c5ab42dfdf8120a7f639de5122d47a69a8e8d121\
+            \024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d07\
+            \6652ae00000000"
+        firstSignedByCompressed =
+          txOf
+            "020000000001011167db886c9b3a5684c47b5c8c8f05962dfd4b6e8d5624fba5\
+            \0e2629504c56570600000000ffffffff01703a0f000000000016001479b00088\
+            \7626b294a914501a4cd226b58b235983030047304402207c5b2dc81d2897af64\
+            \b883563c708b37f1e42d8bedf63eed901e19dab3dc298f02203f003e9bc34b03\
+            \331868ad5297aca870c26c50f5d5dccce5c2ee87b40f2e328401675141041b84\
+            \c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f70be\
+            \af8f588b541507fed6a642c5ab42dfdf8120a7f639de5122d47a69a8e8d12102\
+            \4d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d0766\
+            \52ae00000000"
+        lastSignedByUncompressed =
+          txOf
+            "020000000001011167db886c9b3a5684c47b5c8c8f05962dfd4b6e8d5624fba5\
+            \0e2629504c56570700000000ffffffff01703a0f000000000016001479b00088\
+            \7626b294a914501a4cd226b58b2359830300483045022100c4b7fd0ba9d954d9\
+            \9bffa0068e7897948117b11cd54fce8cdc3a26b814bea29602204fd1cd8a2c2f\
+            \911edb61e66c97b25917d952f6f350614547692a63126b891d2e01675121024d\
+            \4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076641\
+            \041b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd07\
+            \8f70beaf8f588b541507fed6a642c5ab42dfdf8120a7f639de5122d47a69a8e8\
+            \d152ae00000000"
+        lastSignedByCompressed =
+          txOf
+            "020000000001011167db886c9b3a5684c47b5c8c8f05962dfd4b6e8d5624fba5\
+            \0e2629504c56570700000000ffffffff01703a0f000000000016001479b00088\
+            \7626b294a914501a4cd226b58b235983030047304402204fe1b7a84c5372695b\
+            \0bb43cd15f3ac5aec05ccdb6fc312f2eeee6dddb2d157102206e4266722d3c3e\
+            \5cb896ce99aff08937d1c83b98522ee19e111c91d12525388401675121024d4b\
+            \6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d07664104\
+            \1b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f\
+            \70beaf8f588b541507fed6a642c5ab42dfdf8120a7f639de5122d47a69a8e8d1\
+            \52ae00000000"
+        taprootKeySpend =
+          txOf
+            "020000000001011167db886c9b3a5684c47b5c8c8f05962dfd4b6e8d5624fba5\
+            \0e2629504c56570800000000ffffffff01703a0f000000000016001479b00088\
+            \7626b294a914501a4cd226b58b2359830140dc88ba8dbb9d4f93403ec77500f7\
+            \9b376d0cf9ffa730885e57ca3792ab5718aa76090837f3eb597598ea64de5f65\
+            \71046bc629cb7f7ca8a7ee361ce259f03dbe00000000"
+        taprootKeyAnnex =
+          txOf
+            "020000000001011167db886c9b3a5684c47b5c8c8f05962dfd4b6e8d5624fba5\
+            \0e2629504c56570800000000ffffffff01703a0f000000000016001479b00088\
+            \7626b294a914501a4cd226b58b2359830240d2b9c3795f370ec7a511a4c2ff43\
+            \bcde8754bee1af3f852ea982787f05c1f1e2f7c94f343bf46fe43b70280a498d\
+            \f3684ad3981f639ae4c66a4a9f4a0f22b208065068656c6c6f00000000"
+        taprootLeafSpend =
+          txOf
+            "020000000001011167db886c9b3a5684c47b5c8c8f05962dfd4b6e8d5624fba5\
+            \0e2629504c56570900000000ffffffff01703a0f000000000016001479b00088\
+            \7626b294a914501a4cd226b58b2359830340245d8213e2b622e5f6e4d70b0ac8\
+            \9fec15463c55a5ef40a0cb1e1accec2aec8562b61967842ec3b4c038f08a125a\
+            \2192efc5160bee13937cdb34f3767e6911bd22204d4b6cd1361032ca9bd2aeb9\
+            \d900aa4d45d9ead80ac9423374c451a7254d0766ac21c11b84c5567b12644099\
+            \5d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f00000000"
+        taprootLeafAnnex =
+          txOf
+            "020000000001011167db886c9b3a5684c47b5c8c8f05962dfd4b6e8d5624fba5\
+            \0e2629504c56570900000000ffffffff01703a0f000000000016001479b00088\
+            \7626b294a914501a4cd226b58b2359830440716789e28f3c4da087a129121a18\
+            \1e0728b3fa6d02f43882f3f6ef6afa9598771f24ede0c3682f703afaea551329\
+            \cfcd54c1a89f242d4f6f9bfaec2e3f47f85c22204d4b6cd1361032ca9bd2aeb9\
+            \d900aa4d45d9ead80ac9423374c451a7254d0766ac21c11b84c5567b12644099\
+            \5d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f065068656c6c6f0000\
+            \0000"
+    it "verify the spends that the node relayed" $ do
+      verdicts btcRegTest keyHashCoin keyHashSpend `shouldBe` (True, [InputVerified])
+      verdicts btcRegTest scriptHashCoin scriptHashSpend `shouldBe` (True, [InputVerified])
+      verdicts btcRegTest taprootKeyCoin taprootKeySpend `shouldBe` (True, [InputVerified])
+      verdicts btcRegTest taprootLeafCoin taprootLeafSpend `shouldBe` (True, [InputVerified])
+    -- The node: "Data push larger than necessary". The key is after
+    -- OP_PUSHDATA1 and its length, and the redeem script after OP_PUSHDATA2.
+    it "do not verify an input script with a longer push, which the node did not relay" $ do
+      verdicts btcRegTest keyHashCoin keyByLongerPush `shouldBe` (False, [InputUndecided])
+      verdicts btcRegTest scriptHashCoin redeemByLongerPush `shouldBe` (False, [InputUndecided])
+    -- The node: "Using non-compressed keys in segwit".
+    it "do not verify a SegWit input of an uncompressed key, which the node did not relay" $ do
+      verdicts btcRegTest witnessKeyHashCoin witnessKeyHashSpend `shouldBe` (False, [InputUndecided])
+      verdicts btcRegTest nestedKeyHashCoin nestedKeyHashSpend `shouldBe` (False, [InputUndecided])
+      verdicts btcRegTest witnessKeyCoin witnessKeySpend `shouldBe` (False, [InputUndecided])
+      verdicts btcRegTest witnessScriptKeyHashCoin witnessScriptKeyHashSpend `shouldBe` (False, [InputUndecided])
+    -- OP_CHECKMULTISIG tries the keys from the last one. With the
+    -- signature of the last key, it never looks at the key before it.
+    it "verify a witness multisig whose uncompressed key is before the key that signed, which the node relayed" $
+      verdicts btcRegTest uncompressedFirstCoin firstSignedByCompressed `shouldBe` (True, [InputVerified])
+    -- The node: "Using non-compressed keys in segwit", all three times.
+    it "do not verify a witness multisig whose uncompressed key signed, or is after the key that signed" $ do
+      verdicts btcRegTest uncompressedFirstCoin firstSignedByUncompressed `shouldBe` (False, [InputUndecided])
+      verdicts btcRegTest uncompressedLastCoin lastSignedByUncompressed `shouldBe` (False, [InputUndecided])
+      verdicts btcRegTest uncompressedLastCoin lastSignedByCompressed `shouldBe` (False, [InputUndecided])
+    -- The node: "bad-witness-nonstandard". Each signature covers its annex.
+    it "do not verify a Taproot input with an annex, which the node did not relay" $ do
+      verdicts btcRegTest taprootKeyCoin taprootKeyAnnex `shouldBe` (False, [InputUndecided])
+      verdicts btcRegTest taprootLeafCoin taprootLeafAnnex `shouldBe` (False, [InputUndecided])
+    -- The spend that the node relayed, with an annex added after its
+    -- signature. The digest of a Taproot signature covers the annex (BIP
+    -- 341), so no block holds this one.
+    it "do not verify a Taproot input with an annex that its signature does not cover" $ do
+      let withAnnex = taprootKeySpend {witness = [head taprootKeySpend.witness <> ["\x50hello"]]} :: Tx
+      verdicts btcRegTest taprootKeyCoin withAnnex `shouldBe` (False, [InputUndecided])
+    -- No node takes a signature that does not verify, in any form
+    it "say forged of a coin of one key spent in such a form with a signature that does not verify" $ do
+      verdicts btcRegTest keyHashCoin (tampered keyByLongerPush) `shouldBe` (False, [InputForged])
+      verdicts btcRegTest witnessKeyHashCoin (tampered witnessKeyHashSpend) `shouldBe` (False, [InputForged])
+      verdicts btcRegTest nestedKeyHashCoin (tampered nestedKeyHashSpend) `shouldBe` (False, [InputForged])
+
+  -- A spend can be written in other bytes with every signature still good:
+  -- see "Haskoin.Util.Arbitrary.Spelling". Each property below makes signed
+  -- transactions of one to four inputs with one input in such a spelling,
+  -- and states three answers: that of 'verifyStdTx', the verdict of
+  -- 'judgeInputs' on that input, and whether every other input is verified.
+  -- The signatures are good, so the verdict is never forged.
+  --
+  -- MINIMALDATA, LOW_S, STRICTENC and WITNESS_PUBKEYTYPE are rules of the
+  -- relay policy of Bitcoin Core: a block may hold an input that breaks
+  -- one. The verifiers leave such an input to a node.
+  describe "verifyStdTx and judgeInputs on a good spend written a way that Bitcoin does not relay" $ do
+    prop "do not verify an input script that pushes an item by a longer push" $
+      answersFor btc LongPush (False, InputUndecided, True)
+    prop "do not verify a SegWit input of an uncompressed key" $
+      answersFor btc UncompressedKey (False, InputUndecided, True)
+    prop "do not verify a signature with a high S" $
+      answersFor btc HighS (False, InputUndecided, True)
+    prop "do not verify a key in the hybrid form" $
+      answersFor btc HybridKey (False, InputUndecided, True)
+
+  -- BIP 141: the input script of a nested input is exactly the push of its
+  -- program, and the witness script hashes to the program. BIP 16: the
+  -- redeem script hashes to the coin. A signature covers the bytes of the
+  -- script of its coin.
+  describe "verifyStdTx and judgeInputs on a good spend written a way that no block of Bitcoin holds" $ do
+    prop "do not verify a nested witness program that is pushed by a longer push" $
+      answersFor btc LongProgramPush (False, InputUndecided, True)
+    prop "do not verify a redeem script or a witness script in other bytes than the coin commits to" $
+      answersFor btc UncommittedScript (False, InputUndecided, True)
+    prop "do not verify a coin locked to another spelling of the script that was signed" $
+      answersFor btc UnsignedScript (False, InputUndecided, True)
+
+  -- MINIMALDATA, LOW_S and STRICTENC are rules of every block of Bitcoin
+  -- Cash: they are among the MANDATORY_SCRIPT_VERIFY_FLAGS of Bitcoin Cash
+  -- Node.
+  describe "verifyStdTx and judgeInputs on a good spend written a way that no block of Bitcoin Cash holds" $ do
+    prop "do not verify an input script that pushes an item by a longer push" $
+      answersFor bch LongPush (False, InputUndecided, True)
+    prop "do not verify a signature with a high S" $
+      answersFor bch HighS (False, InputUndecided, True)
+    prop "do not verify a key in the hybrid form" $
+      answersFor bch HybridKey (False, InputUndecided, True)
+    prop "do not verify a redeem script in other bytes than the coin commits to" $
+      answersFor bch UncommittedScript (False, InputUndecided, True)
+    prop "do not verify a coin locked to another spelling of the script that was signed" $
+      answersFor bch UnsignedScript (False, InputUndecided, True)
 
   describe "judgeInputs on signed transactions" $
     prop "never says forged of an input that verifies" $
diff --git a/test/Haskoin/TransactionSpec.hs b/test/Haskoin/TransactionSpec.hs
--- a/test/Haskoin/TransactionSpec.hs
+++ b/test/Haskoin/TransactionSpec.hs
@@ -21,7 +21,9 @@
 import Data.Default (def)
 import Data.Either
 import Data.List (find, inits, isInfixOf, isPrefixOf)
+import Data.Map.Strict qualified as Map
 import Data.Maybe
+import Data.Set qualified as Set
 import Data.String (fromString)
 import Data.String.Conversions
 import Data.Text (Text)
@@ -35,6 +37,7 @@
 import Haskoin.Transaction
 import Haskoin.Util
 import Haskoin.Util.Arbitrary
+import System.Timeout (timeout)
 import Test.HUnit
 import Test.Hspec
 import Test.Hspec.QuickCheck
@@ -127,6 +130,7 @@
   taprootSigningSpec
   segwitSpec
   genesisSpec
+  sharedHashesCostSpec
 
 -- Txid Vectors
 
@@ -745,7 +749,7 @@
           h = fromJust (addressHash160 (pubKeyAddr p))
           op = OutPoint (fromJust (hexToTxHash genesisTxId)) 0
           witnessTx = buildTx [op] [(PayWitnessPKHash h, 90000)]
-          taprootOutput = taprootScriptOutput (TaprootOutput p.point Nothing)
+          taprootOutput = either error id (taprootScriptOutput (TaprootOutput p.point Nothing))
           taprootTx = buildTx [op] [(taprootOutput, 90000)]
       signedWitness <- either fail return (signTx btc witnessTx [SigInput (PayWitnessPKHash h) 100000 op sigHashAll Nothing] [k.key])
       signedTaproot <- either fail return (signTx btc taprootTx [SigInput taprootOutput 100000 op sigHashDefault Nothing] [k.key])
@@ -878,21 +882,38 @@
       -- The same coins hold less than the outputs spend
       verifyStdTx btc signed [(PayPKHash h, 70000, op) | op <- ops] `shouldBe` False
 
-    it "signs SIGHASH_SINGLE on a legacy input with an output at its index and on a SegWit input, but refuses it on a legacy input without one" $ do
+    -- Bitcoin Core signs no input with SIGHASH_SINGLE that has no output at
+    -- its index, whatever the coin (SignTransaction: "Only sign
+    -- SIGHASH_SINGLE if there's a corresponding output"). The transaction
+    -- has one output, so input 0 has one at its index and input 1 has none.
+    it "signs SIGHASH_SINGLE on an input with an output at its index, and refuses it on an input without one" $ do
       let (k, p) = fixedKey 1
       let h = fromJust (addressHash160 (pubKeyAddr p))
-          ops = [coinOf 0, coinOf 1]
-          -- one output, so input 1 has none at its index
-          tx = buildTx ops [(PayPKHash h, 150000)]
-          legacy op = SigInput (PayPKHash h) 100000 op sigHashSingle Nothing
-          segwit op = SigInput (PayWitnessPKHash h) 100000 op sigHashSingle Nothing
-      signedFirst <- either fail return (signTx btc tx [legacy (coinOf 0)] [k.key])
-      verifyStdInput btc signedFirst [(PayPKHash h, 100000, coinOf 0)] 0 `shouldBe` True
-      signTx btc tx [legacy (coinOf 1)] [k.key] `shouldBe` Left "makeSignature: SIGHASH_SINGLE without an output at the input index"
-      -- The BIP 143 digest commits to the coin even without an output
-      signedWitness <- either fail return (signTx btc tx [segwit (coinOf 1)] [k.key])
-      verifyStdInput btc signedWitness [(PayWitnessPKHash h, 100000, coinOf 1)] 1 `shouldBe` True
+          tx = buildTx [coinOf 0, coinOf 1] [(PayPKHash h, 150000)]
+          single coin op = SigInput coin 100000 op sigHashSingle Nothing
+          noOutput = Left "signInput: SIGHASH_SINGLE without an output at the input index"
+      forM_ [PayPKHash h, PayWitnessPKHash h] $ \coin -> do
+        signedFirst <- either fail return (signTx btc tx [single coin (coinOf 0)] [k.key])
+        verifyStdInput btc signedFirst [(coin, 100000, coinOf 0)] 0 `shouldBe` True
+        signTx btc tx [single coin (coinOf 1)] [k.key] `shouldBe` noOutput
+      -- A SegWit coin nested in P2SH, and a coin of Bitcoin Cash, whose
+      -- digest is the one of BIP 143 too
+      signNestedWitnessTx btc tx [single (PayWitnessPKHash h) (coinOf 1)] [k.key] `shouldBe` noOutput
+      signTx bch tx [single (PayPKHash h) (coinOf 1)] [k.key] `shouldBe` noOutput
 
+    -- makeSignature is the step below signInput, and signPsbt uses it. It
+    -- refuses the digest that commits to nothing: the constant 1 of a legacy
+    -- input. The BIP 143 digest commits to the coin, and the PSBT signer of
+    -- Bitcoin Core signs it.
+    it "makeSignature refuses SIGHASH_SINGLE without an output on a legacy input, and signs a SegWit input" $ do
+      let (k, p) = fixedKey 1
+      let h = fromJust (addressHash160 (pubKeyAddr p))
+          tx = buildTx [coinOf 0, coinOf 1] [(PayPKHash h, 150000)]
+          single coin = SigInput coin 100000 (coinOf 1) sigHashSingle Nothing
+      makeSignature btc tx 1 (single (PayPKHash h)) k
+        `shouldBe` Left "makeSignature: SIGHASH_SINGLE without an output at the input index"
+      ((.hash) <$> makeSignature btc tx 1 (single (PayWitnessPKHash h)) k) `shouldBe` Right sigHashSingle
+
     -- A node accepts the signature over the constant digest 1 that a
     -- legacy SIGHASH_SINGLE input without an output has, so the verifier
     -- must too, although the signer refuses to make one
@@ -971,8 +992,65 @@
           tx = buildTx [coinAt 0] []
           short = buildTx [] []
       mergeTxInput btc [tx] tx ((ms, 100000), 3) `shouldBe` Left "mergeTxInput: input index out of range"
+      mergeTxInput btc [tx] tx ((ms, 100000), -1) `shouldBe` Left "mergeTxInput: input index out of range"
       mergeTxInput btc [tx, short] tx ((ms, 100000), 0) `shouldBe` Left "mergeTxInput: input index out of range"
 
+    it "mergeTxInput merges the signatures of one input, and leaves the other inputs as they are" $ do
+      let (k1, p1) = fixedKey 1
+          (k2, p2) = fixedKey 2
+          ms = PayMulSig [p1, p2] 2
+          tx = buildTx [coinAt 0, coinAt 1] [(PayPKHash (keyHash p1), 150000)]
+          sigis = [SigInput ms 100000 (coinAt i) sigHashAll Nothing | i <- [0, 1]]
+          coins = [(ms, 100000, coinAt 0), (ms, 100000, coinAt 1)]
+      a <- either fail return (signTx btc tx sigis [k1.key])
+      b <- either fail return (signTx btc tx sigis [k2.key])
+      merged <- either fail return (mergeTxInput btc [a, b] a ((ms, 100000), 1))
+      verifyStdInput btc merged coins 1 `shouldBe` True
+      (head merged.inputs).script `shouldBe` (head a.inputs).script
+      verifyStdInput btc merged coins 0 `shouldBe` False
+
+    it "mergeTxInput leaves the transaction as it is when no transaction to merge has signed the input" $ do
+      let (k1, p1) = fixedKey 1
+          (_, p2) = fixedKey 2
+          ms = PayMulSig [p1, p2] 2
+          tx = buildTx [coinAt 0] [(PayPKHash (keyHash p1), 90000)]
+      a <- either fail return (signTx btc tx [SigInput ms 100000 (coinAt 0) sigHashAll Nothing] [k1.key])
+      mergeTxInput btc [tx, tx] a ((ms, 100000), 0) `shouldBe` Right a
+
+    it "finds the coin of each input by its outpoint, whatever the order of the coins" $ do
+      let (k1, p1) = fixedKey 1
+          (k2, p2) = fixedKey 2
+          (k3, p3) = fixedKey 3
+          -- Each input has a multisig of its own, so the coin of the other does not merge it
+          ms0 = PayMulSig [p1, p2] 2
+          ms1 = PayMulSig [p1, p3] 2
+          tx = buildTx [coinAt 0, coinAt 1] [(PayPKHash (keyHash p1), 150000)]
+          sigis = [SigInput ms 100000 (coinAt i) sigHashAll Nothing | (ms, i) <- [(ms0, 0), (ms1, 1)]]
+          coins = [(ms1, 100000, coinAt 1), (ms0, 100000, coinAt 0)]
+      a <- either fail return (signTx btc tx sigis [k1.key])
+      b <- either fail return (signTx btc tx sigis [k2.key, k3.key])
+      merged <- either fail return (mergeTxs btc [a, b] coins)
+      verifyStdTx btc merged coins `shouldBe` True
+
+    it "keeps the input script of an input that has no coin, and refuses transactions that differ in it" $ do
+      let (k1, p1) = fixedKey 1
+          (k2, p2) = fixedKey 2
+          (k3, p3) = fixedKey 3
+          ms = PayMulSig [p1, p2] 2
+          pkh = PayPKHash (keyHash p3)
+          tx = buildTx [coinAt 0, coinAt 1] [(PayPKHash (keyHash p1), 150000)]
+          msSigi = SigInput ms 100000 (coinAt 0) sigHashAll Nothing
+          coins = [(ms, 100000, coinAt 0), (pkh, 100000, coinAt 1)]
+      -- The second input is signed before the cosigners take their copies
+      withKey <- either fail return (signTx btc tx [SigInput pkh 100000 (coinAt 1) sigHashAll Nothing] [k3.key])
+      a <- either fail return (signTx btc withKey [msSigi] [k1.key])
+      b <- either fail return (signTx btc withKey [msSigi] [k2.key])
+      merged <- either fail return (mergeTxs btc [a, b] [(ms, 100000, coinAt 0)])
+      (merged.inputs !! 1).script `shouldBe` (withKey.inputs !! 1).script
+      verifyStdTx btc merged coins `shouldBe` True
+      -- A copy with another script in the second input
+      mergeTxs btc [a, withInputScript b 1 "\x51"] [(ms, 100000, coinAt 0)] `shouldBe` Left "Transactions do not match"
+
     it "refuses to merge inputs that carry different redeem scripts" $ do
       let (k1, p1) = fixedKey 1
           (k2, p2) = fixedKey 2
@@ -1018,7 +1096,7 @@
           sig = TxSignature (signHash k.key (sha256 ("digest" :: ByteString))) sigHashAll
           h = fromJust (addressHash160 (pubKeyAddr p))
       buildInput btc tx 1 (PayPKHash h) 1 Nothing sig p `shouldBe` Left "buildInput: Invalid input index"
-      buildInput btc tx 0 (taprootScriptOutput (TaprootOutput p.point Nothing)) 1 Nothing sig p `shouldBe` Left "buildInput: a Taproot input has no input script"
+      buildInput btc tx 0 (either error id (taprootScriptOutput (TaprootOutput p.point Nothing))) 1 Nothing sig p `shouldBe` Left "buildInput: a Taproot input has no input script"
       buildInput btc tx 0 (PayPKHash h) 1 (Just (PayPK p)) sig p `shouldBe` Left "buildInput: Invalid output/redeem script combination"
       buildInput btc tx 0 (PayPKHash h) 1 Nothing sig p `shouldBe` Right (RegularInput (SpendPKHash sig p))
 
@@ -1038,7 +1116,7 @@
     let op = OutPoint (fromJust (hexToTxHash genesisTxId)) 0
     it "signs with the internal key of an output without script tree, as BIP 86 spends, and with the output key itself" $ do
       let (k, p) = fixedKey 1
-      let so = taprootScriptOutput (TaprootOutput p.point Nothing)
+      let so = either error id (taprootScriptOutput (TaprootOutput p.point Nothing))
           tx = buildTx [op] [(so, 90000)]
           sigi = SigInput so 100000 op sigHashDefault Nothing
           tweaked = fromJust (taprootOutputSecKey k.key Nothing)
@@ -1058,7 +1136,7 @@
 
     it "needs the output every input spends, and refuses signInput" $ do
       let (k, p) = fixedKey 1
-      let so = taprootScriptOutput (TaprootOutput p.point Nothing)
+      let so = either error id (taprootScriptOutput (TaprootOutput p.point Nothing))
           other = OutPoint (fromJust (hexToTxHash genesisTxId)) 1
           tx = buildTx [op, other] [(so, 90000)]
           sigi = SigInput so 100000 op sigHashDefault Nothing
@@ -1067,6 +1145,21 @@
       signTaprootInput tx [TxOut 100000 (encodeSerial so)] 0 sigHashDefault k.key `shouldBe` Left "taprootSigHash: one spent output per input is required"
       signTaprootInput tx [TxOut 100000 (encodeSerial so), TxOut 1 ""] 0 (setForkIdFlag sigHashAll) k.key `shouldBe` Left "taprootSigHash: invalid hash type 65"
 
+    it "refuses to sign a Taproot input of a transaction whose witness list does not match its inputs" $ do
+      let (k, p) = fixedKey 1
+          so = either error id (taprootScriptOutput (TaprootOutput p.point Nothing))
+          tweaked = fromJust (taprootOutputSecKey k.key Nothing)
+          two = buildTx [op, coinAt 1] [(so, 190000)]
+          sigis = [SigInput so 100000 outpoint sigHashDefault Nothing | outpoint <- [op, coinAt 1]]
+          spent = replicate 2 (TxOut 100000 (encodeSerial so))
+          wrongCount = Left "signTaprootInput: Invalid number of witness stacks"
+      -- One stack for two inputs
+      signTx btc (withWitness two [[]]) sigis [k.key] `shouldBe` wrongCount
+      signTaprootInput (withWitness two [[]]) spent 1 sigHashDefault tweaked `shouldBe` wrongCount
+      -- A stack for each input, or none
+      fmap (map length . (.witness)) (signTx btc (withWitness two [[], []]) sigis [k.key]) `shouldBe` Right [1, 1]
+      fmap (map length . (.witness)) (signTaprootInput two spent 1 sigHashDefault tweaked) `shouldBe` Right [0, 1]
+
 {- SegWit helpers -}
 
 segwitSpec :: Spec
@@ -1110,6 +1203,24 @@
       decodeWitnessInput btc (P2WSH (WitnessProgramSH [sigBytes] multisigScript)) `shouldBe` Left "decodeWitnessInput: Non-standard script output"
       decodeWitnessInput btc EmptyWitnessProgram `shouldBe` Left "decodeWitnessInput: Empty witness program"
 
+    -- The same keys as the multisig above, in other bytes, which the coin
+    -- does not commit to. It is no standard output, so no witness script
+    -- that is read.
+    it "a multisig witness script whose key is not a direct push is refused" $ do
+      let keyAfterPushData1 = Script [OP_1, OP_PUSHDATA keyBytes OPDATA1, OP_1, OP_CHECKMULTISIG]
+      decodeOutput keyAfterPushData1 `shouldBe` Left "decodeOutput: Non-standard output"
+      decodeWitnessInput btc (P2WSH (WitnessProgramSH ["", sigBytes] keyAfterPushData1))
+        `shouldBe` Left "decodeOutput: Non-standard output"
+
+    -- A 'ScriptOutput' does not keep the form of a push, so the data
+    -- carrier below would be written back with its data after a direct
+    -- push: other bytes, which the coin does not commit to.
+    it "a witness script that would be written back as other bytes is refused" $ do
+      let dataAfterPushData1 = Script [OP_RETURN, OP_PUSHDATA "\x01\x02\x03\x04" OPDATA1]
+      decodeOutput dataAfterPushData1 `shouldBe` Right (DataCarrier ["\x01\x02\x03\x04"])
+      decodeWitnessInput btc (P2WSH (WitnessProgramSH [] dataAfterPushData1))
+        `shouldBe` Left "decodeWitnessInput: the witness script is not in the form that encodeOutput writes"
+
     it "a witness program is computed from a standard input, native or nested" $ do
       calcWitnessProgram btc (PayWitnessPKHash h) (RegularInput (SpendPKHash sig p)) `shouldBe` Right (P2WPKH (WitnessProgramPKH sig p))
       calcWitnessProgram btc (either error id (toP2SH =<< encodeOutput (PayWitnessPKHash h))) (RegularInput (SpendPKHash sig p)) `shouldBe` Right (P2WPKH (WitnessProgramPKH sig p))
@@ -1118,6 +1229,114 @@
 
 {- Genesis -}
 
+-- | The digest of BIP 143 holds three hashes over every input and every
+-- output of the transaction. It is the digest of a SegWit version 0 input
+-- on Bitcoin and of every input on Bitcoin Cash. When each input computes
+-- the three hashes again, the time grows with the number of inputs times
+-- the size of the transaction. The comment of a test is the time that it
+-- took before the hashes were computed once.
+sharedHashesCostSpec :: Spec
+sharedHashesCostSpec =
+  describe
+    "A transaction of 5000 inputs and 8000 outputs takes time by its size, \
+    \and not by the square of its size: in under three seconds"
+    $ do
+      let (key, public) = fixedKey 1
+          h = keyHash public
+          outpoints = map coinAt [1 .. 5000]
+          -- 5000 coins of 100,000 satoshi pay 8000 outputs of 50,000
+          unsigned = buildTx outpoints (replicate 8000 (PayPKHash h, 50000))
+          sigInputs coin = [SigInput coin 100000 outpoint sigHashAll Nothing | outpoint <- outpoints]
+          coins coin = [(coin, 100000, outpoint) | outpoint <- outpoints]
+          spent coin = replicate 5000 (Just (TxOut 100000 (encodeSerial coin)))
+          signedOn net coin = either error id (signTx net unsigned (sigInputs coin) [key.key])
+          -- On Bitcoin the coins are P2WPKH, on Bitcoin Cash P2PKH
+          witnessCoin = PayWitnessPKHash h
+          cashCoin = PayPKHash h
+          signed = signedOn btc witnessCoin
+          cashSigned = signedOn bch cashCoin
+          -- Two cosigners of Bitcoin Cash each sign a copy for coins of
+          -- the multisig 2 of 2
+          (key2, public2) = fixedKey 2
+          multisigCoin = PayMulSig [public, public2] 2
+          cosignedBy k = either error id (signTx bch unsigned (sigInputs multisigCoin) [k.key])
+          cosigned = [cosignedBy key, cosignedBy key2]
+          -- The PSBT of the transaction: each input has its coin
+          psbt =
+            let empty = psbtOf unsigned
+                input = insertWitnessUtxo (TxOut 100000 (encodeSerial witnessCoin)) Map.empty
+             in Psbt empty.version empty.unsignedTx empty.globals (replicate 5000 input) empty.outputs
+          signer = (keySigner key.key) {requirePreviousTx = False}
+          signedPsbt = either error id (signPsbt btc signer psbt)
+          -- Whether the work gives the answer, when it does within three
+          -- seconds. What the work starts from is built before the time
+          -- starts.
+          answers :: (Eq a) => Int -> a -> a -> IO (Maybe Bool)
+          answers built work answer = do
+            _ <- evaluate built
+            timeout 3000000 (evaluate (work == answer))
+          sizeOf = B.length . encodeSerial
+
+      it "txSigHashForkIdWith gives a digest of its own to each input, from the hashes that they share" $ do
+        let hashes = txSigHashes unsigned
+            digests = do
+              code <- encodeOutput cashCoin
+              mapM (\i -> txSigHashForkIdWith btc hashes code 100000 i sigHashAll) [0 .. 4999]
+        answers (sizeOf unsigned) (Set.size . Set.fromList <$> digests) (Right 5000) `shouldReturn` Just True
+
+      -- 18 seconds
+      it "signTx gives every SegWit input a signature that ends with the hash type 0x01, and the key of 33 bytes" $ do
+        let shape stack = (B.last <$> take 1 stack, B.length <$> drop 1 stack)
+            witnesses = map shape . (.witness) <$> signTx btc unsigned (sigInputs witnessCoin) [key.key]
+        answers (sizeOf unsigned) witnesses (Right (replicate 5000 ([0x01], [33]))) `shouldReturn` Just True
+
+      -- 17 seconds
+      it "verifyStdTx verifies the signed SegWit transaction" $
+        answers (sizeOf signed) (verifyStdTx btc signed (coins witnessCoin)) True `shouldReturn` Just True
+
+      -- 17 seconds
+      it "judgeInputs says of every input of the signed SegWit transaction that it is verified" $
+        answers (sizeOf signed) (judgeInputs btc signed (spent witnessCoin)) (replicate 5000 InputVerified)
+          `shouldReturn` Just True
+
+      -- 17 seconds
+      it "signPsbt adds one partial signature to every SegWit input" $ do
+        let signatureCounts = map (fmap length . partialSignatures) . (.inputs)
+            signedInputs = signatureCounts <$> signPsbt btc signer psbt
+        answers (B.length (encodePsbt psbt)) signedInputs (Right (replicate 5000 (Right 1)))
+          `shouldReturn` Just True
+
+      -- 17 seconds
+      it "finalizePsbt gives every SegWit input a final witness of two items" $ do
+        let witnessSizes = map (fmap (fmap length) . finalScriptWitness) . (.inputs)
+            finalInputs = witnessSizes <$> finalizePsbt btc signedPsbt
+        answers (B.length (encodePsbt signedPsbt)) finalInputs (Right (replicate 5000 (Right (Just 2))))
+          `shouldReturn` Just True
+
+      -- 17 seconds
+      it "signTx signs every input of Bitcoin Cash with the hash type 0x41" $ do
+        let hashType input = case unmarshal bch input.script of
+              Right (RegularInput (SpendPKHash (TxSignature _ sh) _)) -> Just sh
+              _ -> Nothing
+            hashTypes = map hashType . (.inputs) <$> signTx bch unsigned (sigInputs cashCoin) [key.key]
+        answers (sizeOf unsigned) hashTypes (Right (replicate 5000 (Just 0x41))) `shouldReturn` Just True
+
+      -- 17 seconds
+      it "verifyStdTx verifies the signed transaction of Bitcoin Cash" $
+        answers (sizeOf cashSigned) (verifyStdTx bch cashSigned (coins cashCoin)) True `shouldReturn` Just True
+
+      -- 17 seconds
+      it "judgeInputs says of every input of the signed transaction of Bitcoin Cash that it is verified" $
+        answers (sizeOf cashSigned) (judgeInputs bch cashSigned (spent cashCoin)) (replicate 5000 InputVerified)
+          `shouldReturn` Just True
+
+      it "mergeTxs gives every multisig input of Bitcoin Cash the signatures of its two cosigners" $ do
+        let signatureCount input = case unmarshal bch input.script of
+              Right (RegularInput (SpendMulSig sigs)) -> Just (length sigs)
+              _ -> Nothing
+            counts = map signatureCount . (.inputs) <$> mergeTxs bch cosigned (coins multisigCoin)
+        answers (sum (map sizeOf cosigned)) counts (Right (replicate 5000 (Just 2))) `shouldReturn` Just True
+
 genesisSpec :: Spec
 genesisSpec =
   describe "Genesis coinbases" $ do
@@ -1239,7 +1458,7 @@
       verifyStdInput btc (withInputScript signed 0 (B.pack [0x4c, 0x16] <> program)) [(coin, 100000, op)] 0 `shouldBe` False
 
     it "refuses a Taproot input that has an input script" $ do
-      let so = taprootScriptOutput (TaprootOutput p1.point Nothing)
+      let so = either error id (taprootScriptOutput (TaprootOutput p1.point Nothing))
       signed <- either fail return (signTx btc tx [SigInput so 100000 op sigHashDefault Nothing] [k1.key])
       verifyStdInput btc signed [(so, 100000, op)] 0 `shouldBe` True
       verifyStdInput btc (withInputScript signed 0 "\x51") [(so, 100000, op)] 0 `shouldBe` False
@@ -1418,16 +1637,22 @@
       signTx btc tx [SigInput (PayPKHash hu) 100000 op sigHashAll Nothing] [k1.key] `shouldSatisfy` isRight
 
     -- A block accepts such a spend, so one who knows what it does can still
-    -- make it, with the key in the form to use
+    -- make it, with the key in the form to use. Nodes do not relay it, so
+    -- it is not verified. Its signature is good: with another amount paid,
+    -- the same input is forged.
     it "signInput signs a SegWit coin with the uncompressed key it is given" $ do
       let hu = keyHash p1u
           sigi = SigInput (PayWitnessPKHash hu) 100000 op sigHashAll Nothing
-      signed <- either fail return (signInput btc tx 0 sigi k1u)
-      map (map B.length) signed.witness `shouldSatisfy` (\w -> map (drop 1) w == [[65]])
-      verifyStdInput btc signed [(PayWitnessPKHash hu, 100000, op)] 0 `shouldBe` True
+          coinOf = [Just (TxOut 100000 (encodeSerial (PayWitnessPKHash hu)))]
+          paysLess = signed' {outputs = [o {value = o.value - 1} | o <- signed'.outputs]} :: Tx
+          signed' = either error id (signInput btc tx 0 sigi k1u)
+      map (map B.length) signed'.witness `shouldSatisfy` (\w -> map (drop 1) w == [[65]])
+      verifyStdInput btc signed' [(PayWitnessPKHash hu, 100000, op)] 0 `shouldBe` False
+      judgeInputs btc signed' coinOf `shouldBe` [InputUndecided]
+      judgeInputs btc paysLess coinOf `shouldBe` [InputForged]
 
     it "refuses to sign a SegWit or a Taproot coin on a network without SegWit" $ do
-      let so = taprootScriptOutput (TaprootOutput p1.point Nothing)
+      let so = either error id (taprootScriptOutput (TaprootOutput p1.point Nothing))
       signWith bch (PayWitnessPKHash h1) sigHashAll `shouldBe` Left "makeSignature: this network has no SegWit"
       signTx bch tx [SigInput so 100000 op sigHashDefault Nothing] [k1.key] `shouldBe` Left "signTx: this network has no Taproot"
 
@@ -1438,7 +1663,7 @@
       signInput btc tx 0 (SigInput (PayPKHash h1) 100000 op sigHashAll Nothing) k1 `shouldSatisfy` isRight
 
     it "signTaprootInput refuses a key that is not the key of the output, and an output that is not Taproot" $ do
-      let so = taprootScriptOutput (TaprootOutput p1.point Nothing)
+      let so = either error id (taprootScriptOutput (TaprootOutput p1.point Nothing))
           spent = [TxOut 100000 (encodeSerial so)]
           tweaked = fromJust (taprootOutputSecKey k1.key Nothing)
       -- The internal key is not the key of the output: its tweak is
@@ -1446,6 +1671,16 @@
       signTaprootInput tx spent 0 sigHashDefault tweaked `shouldSatisfy` isRight
       signTaprootInput tx [TxOut 100000 (encodeSerial (PayWitnessPKHash h1))] 0 sigHashDefault tweaked
         `shouldBe` Left "signTaprootInput: the output spent is not a Taproot output"
+
+    it "signs a legacy input without a change of the witness list of the transaction" $ do
+      let two = buildTx [op, coinAt 1] [(PayPKHash h1, 90000)]
+          sigi = SigInput (PayPKHash h1) 100000 (coinAt 1) sigHashAll Nothing
+      -- A transaction without witness stays without
+      fmap (.witness) (signInput btc two 1 sigi k1) `shouldBe` Right []
+      fmap (.witness) (signTx btc two [sigi] [k1.key]) `shouldBe` Right []
+      -- A witness list is kept as it is, and its stacks are not counted
+      fmap (.witness) (signInput btc (withWitness two [[]]) 1 sigi k1) `shouldBe` Right [[]]
+      fmap (.witness) (signTx btc (withWitness two [[]]) [sigi] [k1.key]) `shouldBe` Right [[]]
 
     it "refuses to sign a SegWit input of a transaction whose witness list does not match its inputs" $ do
       let two = buildTx [op, coinAt 1] [(PayPKHash h1, 90000)]
diff --git a/test/Haskoin/Util/Arbitrary/UtilSpec.hs b/test/Haskoin/Util/Arbitrary/UtilSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Haskoin/Util/Arbitrary/UtilSpec.hs
@@ -0,0 +1,268 @@
+{-# LANGUAGE DerivingStrategies #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+
+-- | 'testIdentity' of "Haskoin.Util.Arbitrary.Util" and the five tests it
+-- makes. Every other spec, here and in the programs built on this library,
+-- trusts them to fail for a type whose written form does not come back as
+-- the value. Nothing else checks that they can fail: a helper that
+-- compared nothing would leave every identity test green.
+--
+-- So the helpers are run here on types made for them: one whose five forms
+-- are right, which must pass, and types with one fault each, which must
+-- fail in the example of that fault and in no other. The identity tests of
+-- such a type are run apart from the suite ('outcomes'), and each test
+-- states which of their examples passed and which failed.
+module Haskoin.Util.Arbitrary.UtilSpec (spec) where
+
+import Data.Aeson (FromJSON (..), ToJSON (..))
+import Data.Bytes.Get (getBytes, getWord8)
+import Data.Bytes.Put (putWord8)
+import Data.Bytes.Serial (Serial (..))
+import Data.Default (def)
+import Data.List (intercalate)
+import Data.Word (Word8)
+import Haskoin.Util
+import Haskoin.Util.Arbitrary
+import Test.Hspec
+import Test.Hspec.Runner
+import Test.QuickCheck (Gen, sized)
+
+spec :: Spec
+spec = do
+  describe "testIdentity" $ do
+    it "makes one group for each form, and names each example after the form and the type" $
+      def
+        { readTests = [ReadBox (pure (Sound 3))],
+          jsonTests = [JsonBox (pure (Sound 3))],
+          marshalJsonTests = [MarshalJsonBox (pure ((), Sound 3))],
+          serialTests = [SerialBox (pure (Sound 3))],
+          marshalTests = [MarshalBox (pure ((), Sound 3))]
+        }
+        `gives` [ Passed "Read/Show Encoding" "read/show identity for Sound",
+                  Passed "Data.Aeson Encoding" "Data.Aeson toJSON/fromJSON identity for Sound",
+                  Passed "Data.Aeson Encoding" "Data.Aeson toEncoding/fromJSON identity for Sound",
+                  Passed "MarshalJSON Encoding" "MarshalJSON marshalValue/unmarshalValue identity for Sound",
+                  Passed "MarshalJSON Encoding" "MarshalJSON marshalEncoding/unmarshalValue identity for Sound",
+                  Passed "Binary Encoding" "Binary encoding/decoding identity for Sound",
+                  Passed "Marshal Encoding" "Marshal marshalPut/marshalGet identity for Sound"
+                ]
+    it "sees in every form a fault that only the larger half of the sizes shows" $
+      def
+        { readTests = [ReadBox (WrongText <$> largeOnly)],
+          jsonTests = [JsonBox (WrongParse <$> largeOnly)],
+          marshalJsonTests = [MarshalJsonBox ((,) () . WrongParse <$> largeOnly)],
+          serialTests = [SerialBox (WrongRead <$> largeOnly)],
+          marshalTests = [MarshalBox ((,) () . WrongRead <$> largeOnly)]
+        }
+        `gives` [ Failed "Read/Show Encoding" "read/show identity for WrongText",
+                  Failed "Data.Aeson Encoding" "Data.Aeson toJSON/fromJSON identity for WrongParse",
+                  Failed "Data.Aeson Encoding" "Data.Aeson toEncoding/fromJSON identity for WrongParse",
+                  Failed "MarshalJSON Encoding" "MarshalJSON marshalValue/unmarshalValue identity for WrongParse",
+                  Failed "MarshalJSON Encoding" "MarshalJSON marshalEncoding/unmarshalValue identity for WrongParse",
+                  Failed "Binary Encoding" "Binary encoding/decoding identity for WrongRead",
+                  Failed "Marshal Encoding" "Marshal marshalPut/marshalGet identity for WrongRead"
+                ]
+
+  describe "a ReadBox" $ do
+    it "fails for a type whose text reads as another value" $
+      def {readTests = [ReadBox (pure (WrongText 3))]}
+        `gives` [Failed "Read/Show Encoding" "read/show identity for WrongText"]
+    it "fails for a type whose text does not read" $
+      def {readTests = [ReadBox (pure (NoText 3))]}
+        `gives` [Failed "Read/Show Encoding" "read/show identity for NoText"]
+
+  describe "a SerialBox" $ do
+    it "fails for a codec that reads another value than the one written" $
+      def {serialTests = [SerialBox (pure (WrongRead 3))]}
+        `gives` [Failed "Binary Encoding" "Binary encoding/decoding identity for WrongRead"]
+    it "fails for a codec that reads a byte more than it writes" $
+      def {serialTests = [SerialBox (pure (ByteShort 3))]}
+        `gives` [Failed "Binary Encoding" "Binary encoding/decoding identity for ByteShort"]
+    it "fails for a codec that writes a byte more than it reads" $
+      def {serialTests = [SerialBox (pure (ByteLeft 3))]}
+        `gives` [Failed "Binary Encoding" "Binary encoding/decoding identity for ByteLeft"]
+    it "fails for a codec that the strict reader alone refuses" $
+      def {serialTests = [SerialBox (pure (StrictRefuses 3))]}
+        `gives` [Failed "Binary Encoding" "Binary encoding/decoding identity for StrictRefuses"]
+
+  describe "a JsonBox" $ do
+    it "fails both examples for a type whose parser gives another value" $
+      def {jsonTests = [JsonBox (pure (WrongParse 3))]}
+        `gives` [ Failed "Data.Aeson Encoding" "Data.Aeson toJSON/fromJSON identity for WrongParse",
+                  Failed "Data.Aeson Encoding" "Data.Aeson toEncoding/fromJSON identity for WrongParse"
+                ]
+    it "fails the toEncoding example alone for a type whose toEncoding writes another value" $
+      def {jsonTests = [JsonBox (pure (WrongEncoding 3))]}
+        `gives` [ Passed "Data.Aeson Encoding" "Data.Aeson toJSON/fromJSON identity for WrongEncoding",
+                  Failed "Data.Aeson Encoding" "Data.Aeson toEncoding/fromJSON identity for WrongEncoding"
+                ]
+
+  describe "a MarshalBox" $ do
+    it "fails for a codec that reads another value than the one written" $
+      def {marshalTests = [MarshalBox (pure ((), WrongRead 3))]}
+        `gives` [Failed "Marshal Encoding" "Marshal marshalPut/marshalGet identity for WrongRead"]
+    it "fails for a codec that writes a byte more than it reads" $
+      def {marshalTests = [MarshalBox (pure ((), ByteLeft 3))]}
+        `gives` [Failed "Marshal Encoding" "Marshal marshalPut/marshalGet identity for ByteLeft"]
+
+  describe "a MarshalJsonBox" $ do
+    it "fails both examples for a type whose parser gives another value" $
+      def {marshalJsonTests = [MarshalJsonBox (pure ((), WrongParse 3))]}
+        `gives` [ Failed "MarshalJSON Encoding" "MarshalJSON marshalValue/unmarshalValue identity for WrongParse",
+                  Failed "MarshalJSON Encoding" "MarshalJSON marshalEncoding/unmarshalValue identity for WrongParse"
+                ]
+    it "fails the marshalEncoding example alone for a type whose marshalEncoding writes another value" $
+      def {marshalJsonTests = [MarshalJsonBox (pure ((), WrongEncoding 3))]}
+        `gives` [ Passed "MarshalJSON Encoding" "MarshalJSON marshalValue/unmarshalValue identity for WrongEncoding",
+                  Failed "MarshalJSON Encoding" "MarshalJSON marshalEncoding/unmarshalValue identity for WrongEncoding"
+                ]
+
+-- | What one example of the identity tests did: its group, its name, and
+-- whether it passed.
+data Outcome
+  = Passed String String
+  | Failed String String
+  deriving (Eq, Show)
+
+-- | The identity tests must give these outcomes, one for each example, in
+-- the order of the run.
+gives :: IdentityTests -> [Outcome] -> Expectation
+gives tests expected = outcomes tests `shouldReturn` expected
+
+-- | Run identity tests apart from the suite and give the outcome of each
+-- example. The run prints nothing, and takes nothing from the command line
+-- of the suite: a @--match@ given to the suite would leave it without an
+-- example.
+outcomes :: IdentityTests -> IO [Outcome]
+outcomes tests = do
+  (config, examples) <- evalSpec silent (testIdentity tests)
+  map outcome . specResultItems <$> runSpecForest examples config
+  where
+    silent = defaultConfig {configFormat = Just (\_ -> return (\_ -> return ()))}
+    outcome item = verdict item (intercalate "/" groups) name
+      where
+        (groups, name) = resultItemPath item
+    verdict item
+      | resultItemIsFailure item = Failed
+      | otherwise = Passed
+
+-- The types that the helpers are run on. Each holds one byte. A fault
+-- shows on the byte 3 only, unless the type says otherwise: a helper sees
+-- it only when it tests the value that it is given.
+
+-- | A byte with five right forms
+newtype Sound = Sound Word8
+  deriving stock (Eq, Show, Read)
+  deriving newtype (ToJSON, FromJSON)
+
+instance Serial Sound where
+  serialize (Sound byte) = putWord8 byte
+  deserialize = Sound <$> getWord8
+
+instance Marshal () Sound where
+  marshalPut () = serialize
+  marshalGet () = deserialize
+
+instance MarshalJSON () Sound where
+  marshalValue () = toJSON
+  unmarshalValue () = parseJSON
+
+-- | The fault of a form that gives another value: 4 where the byte is 3
+threeAsFour :: Word8 -> Word8
+threeAsFour 3 = 4
+threeAsFour byte = byte
+
+-- | The byte 3, which shows a fault, at the sizes of 50 and more, and the
+-- byte 0 below them. Of the 100 cases of a property, the first 50 are
+-- below: a helper that ran one case, or small values only, would pass.
+largeOnly :: Gen Word8
+largeOnly = sized $ \size -> pure (if size >= 50 then 3 else 0)
+
+-- | Its text for the byte 3 is the text of the byte 4
+newtype WrongText = WrongText Word8
+  deriving stock (Eq, Read)
+
+instance Show WrongText where
+  show (WrongText byte) = "WrongText " <> show (threeAsFour byte)
+
+-- | Its text for the byte 3 is no text that 'read' takes
+newtype NoText = NoText Word8
+  deriving stock (Eq, Read)
+
+instance Show NoText where
+  show (NoText 3) = "three"
+  show (NoText byte) = "NoText " <> show byte
+
+-- | Its binary readers give 4 where the byte 3 was written
+newtype WrongRead = WrongRead Word8
+  deriving stock (Eq, Show)
+
+instance Serial WrongRead where
+  serialize (WrongRead byte) = putWord8 byte
+  deserialize = WrongRead . threeAsFour <$> getWord8
+
+instance Marshal () WrongRead where
+  marshalPut () = serialize
+  marshalGet () = deserialize
+
+-- | Its binary readers read two bytes where one was written, for every
+-- value
+newtype ByteShort = ByteShort Word8
+  deriving stock (Eq, Show)
+
+instance Serial ByteShort where
+  serialize (ByteShort byte) = putWord8 byte
+  deserialize = ByteShort <$> getWord8 <* getWord8
+
+-- | Its binary writers write a zero byte after the value, which its
+-- readers leave unread, for every value
+newtype ByteLeft = ByteLeft Word8
+  deriving stock (Eq, Show)
+
+instance Serial ByteLeft where
+  serialize (ByteLeft byte) = putWord8 byte >> putWord8 0
+  deserialize = ByteLeft <$> getWord8
+
+instance Marshal () ByteLeft where
+  marshalPut () = serialize
+  marshalGet () = deserialize
+
+-- | Its binary readers ask for a negative number of bytes before the
+-- value, for every value. The strict reader, which is that of cereal,
+-- refuses that. The lazy reader, which is that of binary, reads nothing
+-- and goes on, so the value comes back.
+newtype StrictRefuses = StrictRefuses Word8
+  deriving stock (Eq, Show)
+
+instance Serial StrictRefuses where
+  serialize (StrictRefuses byte) = putWord8 byte
+  deserialize = getBytes (-1) >> StrictRefuses <$> getWord8
+
+-- | Its JSON parsers give 4 where the byte 3 was written
+newtype WrongParse = WrongParse Word8
+  deriving stock (Eq, Show)
+  deriving newtype (ToJSON)
+
+instance FromJSON WrongParse where
+  parseJSON = fmap (WrongParse . threeAsFour) . parseJSON
+
+instance MarshalJSON () WrongParse where
+  marshalValue () = toJSON
+  unmarshalValue () = parseJSON
+
+-- | Its JSON encodings write 4 for the byte 3. The JSON values that
+-- 'toJSON' and 'marshalValue' make are right.
+newtype WrongEncoding = WrongEncoding Word8
+  deriving stock (Eq, Show)
+  deriving newtype (FromJSON)
+
+instance ToJSON WrongEncoding where
+  toJSON (WrongEncoding byte) = toJSON byte
+  toEncoding (WrongEncoding byte) = toEncoding (threeAsFour byte)
+
+instance MarshalJSON () WrongEncoding where
+  marshalValue () = toJSON
+  marshalEncoding () = toEncoding
+  unmarshalValue () = parseJSON
