This BIP defines a new witness program type that uses a Merkle tree to encode mutually exclusive branches in a script. This enables complicated redemption conditions that are currently not possible, improves privacy by hiding unexecuted scripts, and allows inclusion of non-consensus enforced data with very low or no additional cost.
==Motivation==
===Evolution of Bitcoin script system===
Bitcoin uses a script system to specify the conditions for redemption of transaction outputs. In its original design, the conditions for redemption are directly recorded in the scriptPubKey by the sender of the funds. This model has several drawbacks, particularly for complicated scripts:
# It could be difficult for the receiver to specify the conditions;
# Large scripts take up more UTXO space;
# The sender will pay for the additional block space;
# To prevent DoS attack, scripts are limited to 10,000 bytes and 201 op codes;
# Any unexecuted branches and non-consensus enforced data in the script are visible to the public, consuming block space while damaging privacy.
The [[bip-0016.mediawiki|BIP16]] (Pay-to-script-hash, "P2SH") fixes the first 3 problems by using a fixed-length 20-byte script hash in the scriptPubKey, and moving the responsibility for supplying the script to the redeemer. However, due to the data push size limit in script, a P2SH script may not be bigger than 520 bytes. Also, P2SH still requires the redeemer to publish all unexecuted branches of the script.
The [[bip-0141.mediawiki|BIP141]] defines 2 new types of scripts that support segregated witness. The pay-to-witness-script-hash (P2WSH) is similar to P2SH is many ways. By supplying the script in witness, P2WSH restores the original 10,000 byte script limit. However, it still requires publishing of unexecuted branches.
The idea of Merkelized Abstract Syntax Tree (MAST) is to use a Merkle tree to encode branches in a script. When spending, users may provide only the branches they are executing, and hashes that connect the branches to the fixed size Merkel root. This reduces the size of redemption stack from O(n) to O(log n) (n as the number of branches). This enables complicated redemption conditions that is currently not possible due to the script size and opcode limit, improves privacy by hiding unexecuted branches, and allows inclusion of non-consensus enforced data with very low or no additional cost.
In [[bip-0141.mediawiki|BIP141]], witness programs with a version byte of 1 or larger are considered to be anyone-can-spend scripts. The following new validation rules are applied if the witness program version byte is 1 and the program size is 32 bytes.<ref>If the version byte is 1, but the witness program is not 32 bytes, no further interpretation of the witness program or witness stack happens. This is reserved for future extensions.</ref> The witness program is the <code>MAST Root</code>.
<code>Metadata</code> is the last witness item. It is a vector of 1 to 5 bytes. The first byte is an unsigned integer between 1 to 255 denoting the number of <code>Subscript</code> (defined hereinafter). The following 0 to 4 byte(s) is an unsigned little-endian integer denoting the <code>MAST version</code>. <code>MAST Version</code> must be minimally encoded (the most significant byte must not be 0).
<code>Path</code> is the second last witness item. It is a serialized Merkle path of the <code>Script Hash</code> (defined hereinafter). Size of <code>Path</code> must be a multiple of 32 bytes, and not more than 1024 bytes. Each 32 byte word is a double-SHA256 merkle node in the merkle branch connecting to the <code>Script Root</code> (defined hereinafter). <code>Depth</code> of the tree (0 to 32) is the size of <code>Path</code> divided by 32.
<code>Position</code> is the third last witness item. It indicates the location of the <code>Script Hash</code> in the Merkle tree, with zero indicating the leftmost position. It is an unsigned little-endian integer with not more than 4 bytes. It must be minimally encoded: the value must not be larger than the maximum number of items allowed by the <code>Depth</code> of the tree, and the most significant byte must not be 0. For example, if <code>Depth</code> is 4, the valid range of <code>Position</code> is 0 to 15 (2<sup>4</sup>-1).
where <code>Y</code> is a 1-byte value denoting number of <code>Subscript</code>, followed by the hash of each <code>Subscript</code>
<code>Script Root</code> is the Merkle root calculated by the <code>ComputeMerkleRootFromBranch</code> function, using <code>Script Hash</code>, <code>Path</code> and <code>Position</code>.
<code>MAST Root</code> is <code>H(MAST Version|Script Root)</code>. The pre-image has a fixed size of 36 bytes: 4 bytes for <code>MAST Version</code> (unsigned little-endian integer) and 32 bytes for <code>Script Root</code>.
The script evaluation fails if <code>MAST Root</code> does not match the witness program.
If the <code>MAST Root</code> matches the witness program and <code>MAST Version</code> is greater than 0, the script returns a success without further evaluation. <code>SigOpsCost</code> is counted as 0. This is reserved for future script upgrades.
If the <code>MAST Version</code> is 0, the <code>Subscript</code>(s) are serialized to form the final <code>MAST Script</code>, beginning with </code>Subscript_1</code>. The unused witness item(s) before the </code>Subscript_1</code> are used as <code>Input Stack</code> to feed to the <code>MASTScript</code>. (Similar to P2WSH in BIP141)
The script fails with one of the following conditions:
* <code>MAST Script</code> is malformed (i.e. not enough data provided for the last push operation). Individual <code>Subscript</code> might be malformed, as long as they are serialized into a valid <code>MAST Script</code>
* Size of <code>MAST Script</code> is larger than 10,000 bytes
* Size of any one of the <code>Input Stack</code> item is larger than 520 bytes
* Number of non-push operations (<code>nOpCount</code>) is more than 201. <code>nOpCount</code> is the sum of the number of non-push operations in <code>MAST Script</code> (counted in the same way as P2WSH <code>witnessScript</code>), number of <code>Subscript</code> (Y), and <code>Depth</code> of the Merkle tree.
The <code>MAST Script</code> is then evaluated with the <code>Input Stack</code> (with some new or redefined opcodes described in BIPXXX). The evaluation must not fail, and result in an exactly empty stack.
Counting of <code>SigOpsCost</code> is based on the <code>MAST Script</code>, described in BIPYYY.
== Rationale ==
=== MAST Structure ===
This proposal is a restricted case of more general MAST. In a general MAST design, users may freely assign one or more script branches for execution. In this proposal, only one branch is allowed for execution, and users are required to transform a complicated condition into several mutually exclusive branches. For example, if the desired redeem condition is:
(A or B) and (C or D or E) and (F or G)
In a general MAST design, the 7 branches (A to G) will form a 3-level Merkle tree, plus an "overall condition" describing the relationship of different branches. In redemption, the "overall condition", executed branches (e.g. B, D, F), and Merkle path data will be provided for validation.
In the current proposal, the user has to transform the redeem condition into 12 mutually exclusive branches and form a 4-level Merkle tree, and present only one branch in redemption:
A and C and F
B and C and F
A and D and F
.
.
B and E and G
One way to implement the general MAST design is using a combination of <code>OP_EVAL</code>, <code>OP_CAT</code>, and <code>OP_HASH256</code>. However, that will suffer from the problems of <code>OP_EVAL</code>, including risks of indefinite program loop and inability to do static program analysis. A complicated implementation is required to fix these problems and is difficult to review.
The advantages of the current proposal are:
* <code>Subscript</code> are located at a fixed position in the witness stack. This allows static program analysis, such as static <code>SigOpsCost</code> counting and early termination of scripts with disabled opcodes.
* If different parties in a contract do not want to expose their scripts to each other, they may provide only <code>H(Subscript)</code> and keep the <code>Subscript</code> private until redemption.
* If they are willing to share the actual scripts, they may combine them into one <code>Subscript</code> for each branch, saving some <code>nOpCount</code> and a few bytes of witness space.
The are some disadvantages, but only when the redemption condition is very complicated:
* It may require more branches than a general MAST design (as shown in the previous example) and take more witness space in redemption
* Creation and storage of the MAST structure may take more time and space. However, such additional costs affect only the related parties in the contract but not any other Bitcoin users.
=== MAST Version ===
This proposal allows users to indicate the version of scripting language in the witness, which is cheaper than doing that in <code>scriptPubKey</code> or <code>scriptSig</code>. Undefined versions remain anyone-can-spend and are reserved for future expansions. A new version could be used for relaxing constraints (e.g. the 10,000 bytes size limit of <code>MAST Script</code>), adding or redefining opcodes, or even introducing a completely novel scripting system.
=== nOpCount limit ===
In version 0 MAST, the extra hashing operations in calculating the <code>MAST Root</code> are counted towards the 201 <code>nOpCount</code> limit to prevent abusive use. This limitation is not applied to undefined <code>MAST Version</code> for flexibility, but it is constrained by the 255 <code>Subscript</code> and 32 <code>Depth</code> limits.
=== Script evaluation ===
This proposal requires script evaluation resulting in an empty stack, instead of a single <code>TRUE</code> value as in P2WSH. This allows each party in a contract to provide its own <code>Subscript</code>, and demonstrate the required <code>Input Stack</code> to clean up its own <code>Subscript</code>. In this case, order of the <code>Subscript</code> is not important since the overall objective is to clean up the stack after evaluation.
When constructing a MAST, if the user believes that some of the branches are more likely to be executed, they may put them closer to the <code>Script Root</code>. It will save some witness space when the preferred branches are actually executed.
With MAST, this script could be broken down into 2 mutually exclusive branches:<ref>In BIPXXX, it is proposed that CHECKLOCKTIMEVERIFY and CHECKSEQUENCEVERIFY will pop the top stack item</ref>
The current CHECKMULTISIG supports up to 20 public keys. Although it is possible to extend it beyond 20 keys by using multiple CHECKSIGs and IF/ELSE conditions, the construction could be very complicated and soon use up the 10,000 bytes and 201 <code>nOpCount</code> limit.
With MAST, large and complex multi-signature constructs could be flattened to many simple CHECKMULTISIGVERIFY conditions. For example, a 3-of-2000 multi-signature scheme could be expressed as 1,331,334,000 3-of-3 CHECKMULTISIGVERIFY, which forms a 31-level MAST. The scriptPubKey still maintains a fixed size of 34 bytes, and the redemption witness will be very compact, with less than 1,500 bytes.
Currently, committing non-consensus enforced data in the scriptPubKey requires the use of OP_RETURN which occupies additional block space. With MAST, users may commit such data as a branch. Depends on the number of executable branches, inclusion of such a commitment may incur no extra witness space, or 32 bytes at most.
An useful case would be specifying "message-signing keys", which are not valid for spending, but allow users to sign any message without touching the cold storage "funding key".
== Backward compatibility ==
As a soft fork, older software will continue to operate without modification. Non-upgraded nodes, however, will consider MAST programs as anyone-can-spend scripts. Wallets should always be wary of anyone-can-spend scripts and treat them with suspicion.
== Deployment ==
This BIP depends on [[bip-0141.mediawiki|BIP141]] and will be deployed by version-bits [[bip-0009.mediawiki|BIP9]] after BIP141 is enforced. Exact details TBD.
== Credits ==
The idea of MAST originates from Russell O’Connor, Pieter Wuille, and [https://bitcointalk.org/index.php?topic=255145.msg2757327#msg2757327 Peter Todd].