This document specifies Miniscript, a language for writing (a subset of) Bitcoin Scripts in a
structured way, enabling analysis, composition, generic signing and more.
## Copyright
This document is licensed under the Creative Commons CC0 1.0 Universal license.
## Motivation
Bitcoin Script is an unusual stack-based language with many edge cases, designed for implementing
spending conditions consisting of various combinations of signatures, hash locks, and time locks.
Yet, despite being limited in functionality, it is still highly nontrivial to:
* Given a combination of spending conditions, finding the most economical script to implement it.
* Given two scripts, construct a script that implements a composition of their spending conditions (e.g. a multisig where one of the "keys" is another multisig).
* Given a script, find out what spending conditions it permits.
* Given a script and access to a sufficient set of private keys, construct a general satisfying witness for it.
* Given a script, be able to predict the cost of spending an output.
* Given a script, know whether particular resource limitations like the ops limit might be hit when spending.
Miniscript functions as a representation for scripts that makes this sort of operations possible.
It has a structure that allows composition. It is very easy to statically analyze for various
properties (spending conditions, correctness, security properties, malleability, ...). It can be
targeted by spending policy compilers. Finally, compatible scripts can easily be converted to
Miniscript form - avoiding the need for additional metadata for e.g. signing devices that support
it.
## Specification
These specifications apply to P2WSH ([BIP 141](bip-0141.mediawiki)) and Tapscript ([BIP 342](bip-0342.mediawiki)) scripts, with only minor
variations between the two. Differences are noted inline. Unless explicitly stated otherwise,
specifications apply to both. P2SH and bare scripts are excluded from this specification.
| `older(n)`, `after(n)` | 1 ≤ n < 2<sup>31</sup> | B | z
| `sha256(h)` | | B | o; n; d; u
| `ripemd160(h)` | | B | o; n; d; u
| `hash256(h)` | | B | o; n; d; u
| `hash160(h)` | | B | o; n; d; u
| `andor(X,Y,Z)` | X is Bdu; Y and Z are both B, K, or V | same as Y/Z | z=z<sub>X</sub>z<sub>Y</sub>z<sub>Z</sub>; o=z<sub>X</sub>o<sub>Y</sub>o<sub>Z</sub> or o<sub>X</sub>z<sub>Y</sub>z<sub>Z</sub>; u=u<sub>Y</sub>u<sub>Z</sub>; d=d<sub>Z</sub>
| `and_v(X,Y)` | X is V; Y is B, K, or V | same as Y | z=z<sub>X</sub>z<sub>Y</sub>; o=z<sub>X</sub>o<sub>Y</sub> or z<sub>Y</sub>o<sub>X</sub>; n=n<sub>X</sub> or z<sub>X</sub>n<sub>Y</sub>; u=u<sub>Y</sub>
| `and_b(X,Y)` | X is B; Y is W | B | z=z<sub>X</sub>z<sub>Y</sub>; o=z<sub>X</sub>o<sub>Y</sub> or z<sub>Y</sub>o<sub>X</sub>; n=n<sub>X</sub> or z<sub>X</sub>n<sub>Y</sub>; d=d<sub>X</sub>d<sub>Y</sub>; u
| `or_b(X,Z)` | X is Bd; Z is Wd | B | z=z<sub>X</sub>z<sub>Z</sub>; o=z<sub>X</sub>o<sub>Z</sub> or z<sub>Z</sub>o<sub>X</sub>; d; u
| `or_c(X,Z)` | X is Bdu; Z is V | V | z=z<sub>X</sub>z<sub>Z</sub>; o=o<sub>X</sub>z<sub>Z</sub>
| `or_d(X,Z)` | X is Bdu; Z is B | B | z=z<sub>X</sub>z<sub>Z</sub>; o=o<sub>X</sub>z<sub>Z</sub>; d=d<sub>Z</sub>; u=u<sub>Z</sub>
| `or_i(X,Z)` | both are B, K, or V | same as X/Z | o=z<sub>X</sub>z<sub>Z</sub>; u=u<sub>X</sub>u<sub>Z</sub>; d=d<sub>X</sub> or d<sub>Z</sub>
| `thresh(k,X_1,...,X_n)` | 1 ≤ k ≤ n; X<sub>1</sub> is Bdu; others are Wdu | B | z=all are z; o=all are z except one is o; d; u
| `multi(k,key_1,...,key_n)` | 1 ≤ k ≤ n ≤ 20 | B | n; d; u
| `multi_a(k,key_1,...,key_n)` | 1 ≤ k ≤ n | B | d; u
| `a:X` | X is B | W | d=d<sub>X</sub>; u=u<sub>X</sub>
| `s:X` | X is Bo | W | d=d<sub>X</sub>; u=u<sub>X</sub>
| `c:X` | X is K | B | o=o<sub>X</sub>; n=n<sub>X</sub>; d=d<sub>X</sub>; u
| `d:X` | X is Vz | B | o; n; d; *(Tapscript only)* u
| `v:X` | X is B | V | z=z<sub>X</sub>; o=o<sub>X</sub>; n=n<sub>X</sub>
| `j:X` | X is Bn | B | o=o<sub>X</sub>; n; d; u=u<sub>X</sub>
| `n:X` | X is B | B | z=z<sub>X</sub>; o=o<sub>X</sub>; n=n<sub>X</sub>; d=d<sub>X</sub>; u
| `andor(X,Y,Z)` | e<sub>X</sub> and (s<sub>X</sub> or s<sub>Y</sub> or s<sub>Z</sub>) | s=s<sub>Z</sub> and (s<sub>X</sub> or s<sub>Y</sub>); f=f<sub>Z</sub> and (s<sub>X</sub> or f<sub>Y</sub>); e=e<sub>Z</sub> and (s<sub>X</sub> or f<sub>Y</sub>)
| `and_v(X,Y)` | | s=s<sub>X</sub> or s<sub>Y</sub>; f=s<sub>X</sub> or f<sub>Y</sub>
| `and_b(X,Y)` | | s=s<sub>X</sub> or s<sub>Y</sub>; f=f<sub>X</sub>f<sub>Y</sub> or s<sub>X</sub>f<sub>X</sub> or s<sub>Y</sub>f<sub>Y</sub>; e=e<sub>X</sub>e<sub>Y</sub>s<sub>X</sub>s<sub>Y</sub>
| `or_b(X,Z)` | e<sub>X</sub> and e<sub>Z</sub> and (s<sub>X</sub> or s<sub>Z</sub>)| s=s<sub>X</sub>s<sub>Z</sub>; e
In order to produce non-malleable satisfactions we make use of a function that returns the optimal
satisfaction and dissatisfaction for a given expression (if any exist), or a special DONTUSE ("don't use") value,
together with an optional HASSIG ("has signature") marker that tracks whether the solution contains at least one
signature. To implement the function:
* Invoke the function recursively for all subexpressions, obtaining all their satisfactions/dissatisfactions.
* Iterate over all the valid satisfactions/dissatisfactions in the table above (including the non-canonical ones), taking into account:
* The dissatisfactions for `sha256`, `ripemd160`, `hash256`, and `hash160` are always malleable, so instead use DONTUSE there.
* The non-canonical options for `and_b`, `or_b`, and `thresh` are always overcomplete, so instead use DONTUSE there as well (with HASSIG flag if the original non-canonical solution had one).
* The satisfactions for `pk_k`, `pk_h`, and `multi` can be marked HASSIG.
* When constructing solutions by combining results for subexpressions, the result is DONTUSE if any of the constituent results is DONTUSE. Furthermore, the result gets the HASSIG tag if any of the constituents does.
* If among all valid solutions (including DONTUSE ones) more than one does not have the HASSIG marker, return DONTUSE.
* If instead exactly one does not have the HASSIG marker, return that solution.
* If all valid solutions have the HASSIG marker, but all of them are DONTUSE, return DONTUSE-HASSIG. The HASSIG marker is important because while this represents a choice between multiple options that would cause malleability if used, they are not available to the attacker, and we may be able to avoid them entirely still.
* Otherwise, all not-DONTUSE options are valid, so return the smallest one (in terms of witness size).
To produce an overall satisfaction, invoke the function on the toplevel expression. If no valid
satisfaction is returned, or it is DONTUSE, fail. Otherwise, if any timelocking is used in the
script but the result does not have the HASSIG flag, also fail. If the satisfaction is both not
DONTUSE and HASSIG, return it.
## Discussion
## Security
Miniscript primarily aims to provide guarantees on the correctness of a Bitcoin Script. That is, to
guarantee **consensus soundness** and **standardness completeness**. Consensus soundness means
it is not possible to construct a consensus-valid witness for a Bitcoin Script unless the Miniscript
spending conditions are met. Standardness completeness means a standardness-valid witness can be
created for all spending paths of a Miniscript, assuming the resource limits are respected and there
is no timelock mixing.
Additionally, Miniscript can guarantee the non-malleability and maximum size of a witness. These can
assist in assessing the soundness of protocols where transaction fees (and therefore transaction
size) are security-critical parameters.
Hash preimages are constrained to 32 bytes to disallow various forms of griefing, including making
non-standard (un-relayable) transactions, consensus-invalid swaps across blockchains, as well as
ensure that satisfaction cost can be accurately calculated.
In order for these properties to not just apply to script, but to an entire transaction, it's
important that the witness commits to all data relevant for verification. In practice this means
that scripts whose conditions can be met without any digital signature are insecure. Besides being
trivially insecure, note how a transaction lacking a signature check allows an attacker to change
its nLockTime and nSequence fields to meet additional timelock conditions.
### Type System
To statically verify the correctness and malleability guarantees discussed in the previous section,
we define a type system. See the specifications above for a reference of each fragment's
requirements and properties. Here we give more information about each type.
Every expression has one of four basic types:
* "**B**" Base expressions. These take their inputs from the top of the stack. When satisfied, they push a nonzero value of up to 4 bytes onto the stack. When dissatisfied, they push an exact 0 onto the stack (if dissatisfaction without aborting is possible at all). This type is used for most expressions, and required for the top level expression. An example is `older(n)` = `<n> CHECKSEQUENCEVERIFY`.
* "**V**" Verify expressions. Like "B", these take their inputs from the top of the stack. Upon satisfaction however, they continue without pushing anything. They cannot be dissatisfied (will abort instead). A "V" can be obtained using the `v:` wrapper on a "B" expression, or by combining other "V" expressions using `and_v`, `or_i`, `or_c`, or `andor`. An example is `v:pk(key)` = `<key> CHECKSIGVERIFY`.
* "**K**" Key expressions. They again take their inputs from the top of the stack, but instead of verifying a condition directly they always push a public key onto the stack, for which a signature is still required to satisfy the expression. A "K" can be converted into a "B" using the `c:` wrapper. An example is `pk_h(key)` = `DUP HASH160 <Hash160(key)> EQUALVERIFY`.
* "**W**" Wrapped expressions. They take their inputs from one below the top of the stack, and push a nonzero (in case of satisfaction) or zero (in case of dissatisfaction) either on top of the stack, or one below. So for example a 3-input "W" would take the stack "A B C D E F" and turn it into "A B F 0" or "A B 0 F" in case of dissatisfaction, and "A B F n" or "A B n F" in case of satisfaction (with n a nonzero value). Every "W" is either `s:B` (SWAP B) or `a:B` (TOALTSTACK B FROMALTSTACK). An example is `s:pk(key)` = `SWAP <key> CHECKSIG`.
Then there are 6 type modifiers, which guarantee additional properties:
* "**n**" Nonzero: this expression always consumes at least 1 stack element, no satisfaction for this expression requires the top input stack element to be zero.
* "**d**" Dissatisfiable: a dissatisfaction for this expression can unconditionally be constructed. This implies the dissatisfaction cannot include any signature or hash preimage, and cannot rely on timelocks being satisfied.
* "**u**" Unit: when satisfied, this expression will put an exact 1 on the stack (as opposed to any nonzero value).
* "**k**" No timelock mixing. This expression does not contain a mix of heightlock and timelock of the same type. If the miniscript does not have the "k" property, the miniscript template will not match the user expectation of the corresponding spending policy.
Finally to analyze malleability guarantees we introduce 3 new type modifiers:
* "**s**" Signed: satisfying this expression always requires a signature (predicting whether all satisfactions will be HASSIG).
* "**f**" Forced: dissatisfying this expression always requires a signature (predicting whether all dissatisfactions will be HASSIG).
* "**e**" Expressive: this requires a unique unconditional dissatisfaction to exist, and forces all conditional dissatisfactions (if any) to require a signature.
### Malleability
Since Segwit, malleating a transaction no longer breaks the validity of unconfirmed descendant
transactions. However, unintentional malleability may still have a number of much weaker undesirable
effects. If a witness can be stuffed with additional data, the transaction's feerate will go down,
potentially to the point where its ability to propagate and get confirmed is impacted. Additionally,
malleability can be exploited to add roundtrips to BIP152 block propagation, by trying to get
different miners to mine different versions of the same transaction. Finally, malleability may
interfere with the usage of hash locks as a mechanism for publishing preimages.
Using the malleability type properties it is possible to determine statically whether a script can
be non-malleably satisfied under all circumstances. In many cases it is reasonable to only accept
such guaranteed-non-malleable scripts, as unexpected behavior can occur when using other scripts.
For example, when running the non-malleable satisfaction algorithm above, adding available
preimages, or increasing the nLockTime/nSequence values actually may make it fail where it succeeded
before. This is because a larger set of met conditions may mean an existing satisfaction goes from
non-malleable to malleable. Restricting things to scripts that are guaranteed to be satisfiable in a
non-malleable way avoids this problem.
When analysing Miniscripts for resource limits, restricting yourself to just non-malleable solutions
(or even non-malleable scripts) also leads to tighter bounds, as all non-canonical satisfactions and
dissatisfactions can be left out of consideration.
The malleability analysis makes the following assumptions:
* The attacker does not have access to any of the private keys of public keys that participate in the Script. Participants with private keys inherently have the ability to produce different satisfactions by creating multiple signatures. While it is also interesting to study the impact rogue participants can have, we treat it as a distinct problem.
* The attacker only has access to hash preimages that honest users have access to as well. This is a reasonable assumption because hash preimages are revealed once globally, and then available to everyone. On the other hand, making the assumption that attackers may have access to more preimages than honest users makes a large portion of scripts impossible to satisfy in a non-malleable way.
* The attacker gets to see exactly one satisfying witness of any transaction. If he sees multiple, it becomes possible for the attacker to mix and match different satisfactions. This is very hard to reason about.
* We restrict this analysis to scripts where no public key is repeated. If signatures constructed for one part of the script can be bound to other checks in the same script, a variant of the mixing from the previous point becomes available that is equally hard to reason about. Furthermore this situation can be avoided by using separate keys.
* The attacker is constrained by common standardness rules. A miner may be able to malleate a witness considered non-malleable by Miniscript.
#### Non-Malleable Satisfaction
Malleable satisfactions or dissatisfactions appear whenever options are available to attackers distinct from the one taken by honest users. This can happen for multiple reasons:
1. Two or more options for a satisfaction or dissatisfaction are listed in the table above which are both available to attackers directly. Regardless of which option is used in the honest solution, the attacker can change the solution to the other one.
2. Two or more options for a satisfaction or dissatisfaction are listed in the table above, only one of which is available to attackers, but the honest solution uses another one. In that case, the attacker can modify the solution to pick the one available to him.
3. The honest users pick a solution that contains a satisfaction which can be turned into a dissatisfaction without invalidating the overall witness. Those are called overcomplete solutions.
Because we assume attackers never have access to private keys, we can treat any solution that
includes a signature as one that is unavailable to attackers. For others, the worst case is that the
attacker has access to every solution the honest users have, but no others: for preimages this is an
explicit assumption, while timelock availability is determined by the nLockTime and nSequence fields
in the transaction. As long as the overall satisfaction includes at least one signature, those
values are fixed, and timelock availability is identical for attackers and honest users.
The description of the non-malleable satisfaction algorithm can be used to show that no
non-canonical solutions listed in the satisfaction table can occur inside non-malleable
satisfaction:
* Some of the non-canonical options (the `or_b`, `and_b`, and `thresh` ones) are overcomplete, and thus can clearly not appear in non-malleable satisfactions.
* The fact that non-"d" expressions cannot be dissatisfied in valid witnesses rules out the usage of the non-canonical `and_v` dissatisfaction.
* "d" expressions are defined to be unconditionally dissatisfiable, which implies that for those a non-HASSIG dissatisfaction must exist. Non-HASSIG solutions must be preferred over HASSIG ones (reason 2), and when multiple non-HASSIG ones exist, none can be used (reason 1). This lets us rule out the other non-canonical options in the table:
*`j:X` is always "d", its non-HASSIG dissatisfaction "0" always exists, and thus rules out any usage of "dsat(X)".
* If `andor(X,Y,Z)` is "d", a non-HASSIG dissatisfaction "dsat(Z) dsat(X)" must exist, and thus rules out any usage of "dsat(Y) sat(X)".
* If `and_b(X,Y)` is "d", a non-HASSIG dissatisfaction "dsat(Y) dsat(X)" must exist, and thus rules out any usage of "dsat(Y) sat(X)" and "sat(Y) dsat(X)". Those are also overcomplete.
*`thresh(k,...)` is always "d", a non-HASSIG dissatisfaction with just dissatisfactions must exist due to typing rules, and thus rules out usage of the other dissatisfactions. They are also overcomplete.
### Resource Limits
Various types of Bitcoin Scripts have different resource limitations, either through consensus or standardness. Some of them affect otherwise valid Miniscripts:
* In P2WSH, scripts larger than 3600 bytes are invalid by standardness. In Tapscript, scripts are implicitly bounded by the maximum size of a block (1 million virtual bytes).
* In P2WSH, script satisfactions where the total number of non-push opcodes plus the number of keys participating in all executed `CHECKMULTISIG` is above 201 are invalid by consensus.
* In both Tapscript and P2WSH, script satisfactions which make the stack exceed 1000 elements before or during execution are invalid.
* In P2WSH, satisfactions with a witness consisting of over 100 stack elements (excluding the script itself) are invalid by standardness.
A static analysis can be performed on a Miniscript to verify if none, all or any of the spending
Text files have one vector per line, no comments. `*.txt` is space separated,
`*.tsv` tab separated. Expressions contain no whitespace. A key argument is a letter
`A`..`Z` standing for the public key of the secret key `0x00…01` … `0x00…1a`,
serialized compressed in P2WSH and x-only in Tapscript. The limit vectors need more
distinct keys than that and write `K` followed by the secret key in decimal instead
(`K1`, `K2`, …). Hash arguments are literal hex. A type string is the basic type
(`B`/`V`/`K`/`W`) plus its properties (`zondumsfe`) in arbitrary order, so compare
sorted. Files with a `_tap` suffix are Tapscript (`multi_a`, x-only, Schnorr), the
others P2WSH.
### Files
| File | Lines | Line format | Asserts |
|------|-------|-------------|---------|
| `valid_from_alloy.txt` | 5,896 | `<expr> <type>` | parses, is a valid top level, has that type |
| `valid_8f1e8_from_alloy.txt` | 3,492 | same | same, corpus of an earlier upstream revision |
| `malleable_from_alloy.txt` | 7,024 | same | parses, has that type, but has no `m` property, i.e. is not sane |
| `conflict_from_alloy.txt` | 1,773 | same | parses and has that type; combines height- and time-based `after()`, on one spending path in 1,586 lines (not sane) and on alternative `andor` branches in the other 187 (sane) |
| `edge_cases.txt` | 42 | `<expr>` | a hand-written file: `thresh` at `k=1`/`k=n`, `multi` with 1 and 20 keys, all four hash fragments, the timelock boundaries (`499999999`/`500000000`, `4194304`/`4194305`), and the sugar forms |
| `invalid.txt` | 5,574 | `<expr>` | must be rejected (mostly type-check failures) |
| `opcodes.txt` | 18,185 | `<expr> <type> <ops>` | as above, plus the op count of a satisfaction, see `op_count` below |
| `limits.txt`, `limits_tap.txt` | 8, 2 | `<expr> <limit> <verdict>` | hand-written files: each resource limit at its boundary, `limit` being one of `ops`, `script_size`, `witness_elements` and `stack`. A `within` expression is sane; an `over` expression exceeds that limit by one and must be rejected, by the parser or by the sanity checks |
| `props_from_rust[_tap].tsv` | 8,198 + header | `expr script_size op_count sat_witness_elements exec_stack mixed_timelocks non_malleable requires_sig sat_size` | the static analysis, with the columns described below. A two-field row ending in `PARSE_ERR` must be rejected (1,470 of them in the Tapscript file, from the `multi`→`multi_a` substitution) |
| `scripts_from_rust[_tap].tsv` | 8,198 | `<expr>\t<script hex>` | the translation table byte for byte, incl. `v:` collapsing into the `VERIFY` opcode and minimal number encoding. `ERR` = no encoding in that context |
| `redeem.json` | 46 cases | JSON | optional satisfaction vectors: `{miniscript, valid, can_sign_N, …}` plus an `identifiers` map of keys, preimages and hashes |
### Resource Columns
This document specifies the resource limits, but not how to count the quantities
they bound, and implementations count them differently. The resource columns of
`props_from_rust[_tap].tsv` and `opcodes.txt` count them as rust-miniscript does:
*`script_size`: the size of the script in bytes, which the translation table
determines, so it does not depend on the implementation.
*`op_count` (`<ops>` in `opcodes.txt`): the non-push opcodes of the script plus the
keys of every `CHECKMULTISIG` a satisfaction executes, i.e. the quantity the 201-op
limit bounds. Tapscript has no op limit, so there the column has no meaning; it
counts a `multi_a` as no ops at all.
*`sat_witness_elements`: the number of witness elements of a satisfaction, plus one
in both contexts. The 100-element limit of P2WSH applies to this column minus one.
*`sat_size`: the size in bytes of a satisfaction, each element including its length
prefix, without the element count. Signatures are assumed to be 73 bytes for ECDSA
and 66 bytes for Schnorr, each including its length prefix.
*`exec_stack`: rust-miniscript's estimate of how many elements the script pushes
above its witness. It is not the exact peak: for a `thresh` it depends on the
order of the sub expressions, and for `or_d` and `multi` it falls short.
`op_count`, `sat_witness_elements` and `sat_size` are the maximum over every
satisfaction the fragment rules allow, including malleable ones, such as the
dissatisfaction of a hash fragment with a 32-byte value that is not the preimage.
Bitcoin Core counts only non-malleable satisfactions, which never dissatisfy a hash
fragment, and does not count the witness script as a witness element. An
implementation that counts like Core reproduces every other column, but differs on
`sat_witness_elements` in every row that has a satisfaction, and on roughly one in
ten op counts and one in five `sat_size` values.
The limits themselves do not depend on how these quantities are counted, as this
document says what each of them includes: `limits[_tap].txt` puts each limit at its
boundary, with expressions that contain no hash fragment.
### Execution
There is a Golang based minimal harness available that executes all test vectors against
the [Go implementation](https://github.com/btcsuite/btcd/pull/2568). It compares every
column of every file except `exec_stack`, as the Go implementation computes the exact
peak instead, and the Tapscript `op_count`. The `mixed_timelocks`, `non_malleable` and
`requires_sig` columns are compared through the sanity checks, which must reject an
expression that any of them disqualifies.
With at least `Go 1.25.0` installed, they can be run with:
```shell
$ cd bip-0379
$ go run main.go
```
### Provenance
The `*.txt` corpora, except the limit vectors, come from rust-miniscript's
`src/miniscript/ms_tests.rs` at `698b97f`. The `*.tsv` tables were extracted from
the same, unmodified commit by a program that prints what the crate computes for
each expression, and cross-checked against an
[independent Go implementation](https://github.com/btcsuite/btcd/pull/2568).
`redeem.json` comes from the Go implementation's end-to-end spend tests.
`limits[_tap].txt` were written for this document, and their verdicts checked
against Bitcoin Core, rust-miniscript and the Go implementation. rust-miniscript
counts the witness script towards the 100-element limit, so it rejects the
`within` vector of that limit.
## Gaps
The generated static-analysis corpora are dominated by `multi`, `sha256`, `after`,
`andor` and `or_d`; `older()`, `ripemd160()`, `hash256()`, `hash160()` and `and_n()` occur
only in the 42 hand-written lines, never in composition.
The following cases are still missing from the static-analysis corpora:
1.`older()` alongside `after()` in the positions `after()` appears in, since
the two differ in the relative/absolute timelock analysis, and the generated
corpora only ever use `after()`.
2. The 1,000 stack element limit in P2WSH, and in Tapscript a `multi_a` at that
limit, which needs a script of 33 KB that not every implementation accepts.
3. The four timelock-mixing combinations of the BIP's own wording (absolute
height with absolute time, relative height with relative time, and the two
legal mixes), which `conflict_from_alloy.txt` covers only for `after()`.