{"number":114,"title":"Merkelized Abstract Syntax Tree","authors":["Johnson Lau"],"status":"Closed","type":"Specification","layer":"Consensus (soft fork)","created":"2016-04-02","license":"PD","requires":[],"replaces":[],"replacedBy":[],"discussion":[],"abstract":"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.","eli5":"Proposed MAST, which organizes a script's possible spending conditions into a tree so that only the condition actually used needs to be revealed. This saves space and improves privacy by hiding unused options, an idea later incorporated into Taproot.","categories":["lightning","transactions","smart-contracts"],"filename":"bip-0114.mediawiki","githubUrl":"https://github.com/bitcoin/bips/blob/master/bip-0114.mediawiki","format":"mediawiki","readingMinutes":13,"inbound":2,"revisions":15,"impact":67,"core":false,"references":[9,16,112,141],"lastModified":"2026-09-15","html":"<h2 id=\"abstract\">Abstract</h2>\n<p>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.</p>\n<h2 id=\"motivation\">Motivation</h2>\n<h3 id=\"evolution-of-bitcoin-script-system\">Evolution of Bitcoin script system</h3>\n<p>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:</p>\n<ol><li>\nIt could be difficult for the receiver to specify the conditions;\n</li></ol>\n<ol><li>\nLarge scripts take up more UTXO space;\n</li></ol>\n<ol><li>\nThe sender will pay for the additional block space;\n</li></ol>\n<ol><li>\nTo prevent DoS attack, scripts are limited to 10,000 bytes and 201 op codes;\n</li></ol>\n<ol><li>\nAny unexecuted branches and non-consensus enforced data in the script are visible to the public, consuming block space while damaging privacy.\n</li></ol>\n<p>The <a href=\"/bip/16\">BIP16</a> (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.</p>\n<p>The <a href=\"/bip/141\">BIP141</a> 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.</p>\n<h3 id=\"merkelized-abstract-syntax-tree\">Merkelized Abstract Syntax Tree</h3>\n<p>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.</p>\n<h2 id=\"specification\">Specification</h2>\n<p>In <a href=\"/bip/141\">BIP141</a>, 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.<sup class=\"footnote-ref\"><a href=\"#fn-1\" id=\"fnref-1\">[1]</a></sup> The witness program is the <code>MAST Root</code>.</p>\n<p>To redeem an output of this kind, the witness must consist of the following items:</p>\n<p>Script_stack_1   Script_stack_2   .   .   Script_stack_X (X ≥ 0)   Subscript_1   Subscript_2   .   .   Subscript_Y (1 ≤ Y ≤ 255)   Position   Path   Metadata (Y|MAST Version)</p>\n<p><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).</p>\n<p><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.</p>\n<p><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).</p>\n<p>Depends on the first byte of <code>Metadata</code>, there should be 1 to 255 <code>Subscript</code> witness item(s) before <code>Position</code>.</p>\n<p><code>Script Hash</code> is defined as:</p>\n<p>Script Hash = H(Y|H(Subscript_1)|H(Subscript_2)|...|H(Subscript_Y))   H() = SHA256(SHA256())</p>\n<p>where <code>Y</code> is a 1-byte value denoting number of <code>Subscript</code>, followed by the hash of each <code>Subscript</code></p>\n<p><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>.</p>\n<p><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>.</p>\n<p>The script evaluation fails if <code>MAST Root</code> does not match the witness program.</p>\n<p>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.</p>\n<p>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)</p>\n<p>The script fails with one of the following conditions:</p>\n<ul><li>\n<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>\n</li></ul>\n<ul><li>\nSize of <code>MAST Script</code> is larger than 10,000 bytes\n</li></ul>\n<ul><li>\nSize of any one of the <code>Input Stack</code> item is larger than 520 bytes\n</li></ul>\n<ul><li>\nNumber 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.\n</li></ul>\n<p>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.</p>\n<p>Counting of <code>SigOpsCost</code> is based on the <code>MAST Script</code>, described in BIPYYY.</p>\n<h2 id=\"rationale\">Rationale</h2>\n<h3 id=\"mast-structure\">MAST Structure</h3>\n<p>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:</p>\n<p>(A or B) and (C or D or E) and (F or G)</p>\n<p>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.</p>\n<p>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:</p>\n<p>A and C and F   B and C and F   A and D and F   .   .   B and E and G</p>\n<p>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.</p>\n<p>The advantages of the current proposal are:</p>\n<ul><li>\n<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.\n</li></ul>\n<ul><li>\nIf 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.\n</li></ul>\n<ul><li>\nIf 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.\n</li></ul>\n<p>There are some disadvantages, but only when the redemption condition is very complicated:</p>\n<ul><li>\nIt may require more branches than a general MAST design (as shown in the previous example) and take more witness space in redemption\n</li></ul>\n<ul><li>\nCreation 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.\n</li></ul>\n<h3 id=\"mast-version\">MAST Version</h3>\n<p>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.</p>\n<h3 id=\"nopcount-limit\">nOpCount limit</h3>\n<p>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.</p>\n<h3 id=\"script-evaluation\">Script evaluation</h3>\n<p>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.</p>\n<h2 id=\"examples\">Examples</h2>\n<h3 id=\"calculation-of-mast-root\">Calculation of MAST Root</h3>\n<img src=\"https://raw.githubusercontent.com/bitcoin/bips/master/bip-0114/mastexample.png\"></img>\n<p>Subscript:     SA = 1 EQUALVERIFY (0x5188)     SB = 2 EQUALVERIFY (0x5288)     SC = 3 EQUALVERIFY (0x5388)     SD = 4 EQUALVERIFY (0x5488)     SE = 5 EQUALVERIFY (0x5588)     SF = 6 EQUALVERIFY (0x5688)     SG = 7 EQUALVERIFY (0x5788)     SH = 8 EQUALVERIFY (0x5888)     M = RETURN \"Hello\" (0x6a0548656c6c6f)   Hash:     HA = H(0x01|H(SA)) = H(0x015acb54166e0db370cd1b05a29120373568dacea2abc3748459ec3da2106e4b4e) = 0xd385d7268ad7e1ec51660f833d54787d2d8d79b6b1809d9c1d06c9e71f7be204     HB = H(0x02|H(SB)|H(SC)) = 0x7cbfa08e44ea9f4f996873be95d9bffd97d4b91a5af32cc5f64efb8461727cdd     HF = H(0x03|H(SD)|H(SE)|H(SF)) = 0x4611414355945a7c2fcc62a53a0004821b87e68f93048ffba7a55a3cb1e9783b     HG = H(0x01|H(SG)) = 0xaa5fbdf58264650eadec33691ba1e7606d0a62f570eea348a465c55bc86ffc10     HC = H(0x01|H(M)) = 0x70426d480d5b28d93c5be54803681f99abf4e8df4eab4dc87aaa543f0d138159     HD = H(0x0x|H(SH)) = 0x8482f6c9c3fe90dd4d533b4efedb6a241b95ec9267d1bd5aaaee36d2ce2dd6da     HE = H(HA|HB) = 0x049b9f2f94f0a9bdea624e39cd7d6b27a365c6a0545bf0e9d88d86eff4894210     HH = H(HC|HD) = 0xc709fdc632f370f3367da45378d1cf430c5fda6805e731ad5761c213cf2d276e     HI = H(HE|HF) = 0xead5e1a1e7e41b77b794f091df9be3f0e9f41d47304eb43dece90688f69843b7     HJ = H(HG|HH) = 0xd00fc690c4700d0f983f9700740066531ea826b21a4cbc62f80317261723d477     Script Root = H(HI|HJ) = 0x26d5235d20daf1440a15a248f5b5b4f201392128072c55afa64a26ccc6f56bd9     MAST Root = H(MAST Version|Script Root) = H(0x0000000026d5235d20daf1440a15a248f5b5b4f201392128072c55afa64a26ccc6f56bd9) = 0xb4b706e0c02eab9aba58419eb7ea2a286fb1c01d7406105fc12742bf8a3f97c9</p>\n<p>The scriptPubKey with native witness program is:</p>\n<p>1 <0xb4b706e0c02eab9aba58419eb7ea2a286fb1c01d7406105fc12742bf8a3f97c9>   (0x5120b4b706e0c02eab9aba58419eb7ea2a286fb1c01d7406105fc12742bf8a3f97c9)</p>\n<p>To redeem with the <code>SD|SE|SF</code> branch, the witness is</p>\n<p>Script_stack_1: 0x06   Script_stack_2: 0x05   Script_stack_3: 0x04   Subscript_1:    0x5488   Subscript_2:    0x5588   Subscript_3:    0x5688   Position:       0x01 (HF is the second hash in its level)   Path (HE|HJ):   0x049b9f2f94f0a9bdea624e39cd7d6b27a365c6a0545bf0e9d88d86eff4894210d00fc690c4700d0f983f9700740066531ea826b21a4cbc62f80317261723d477   Metadata:       0x03 (3 Subscript)</p>\n<h3 id=\"imbalance-mast\">Imbalance MAST</h3>\n<p>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.</p>\n<h3 id=\"escrow-with-timeout\">Escrow with Timeout</h3>\n<p>The following is the \"Escrow with Timeout\" example in <a href=\"/bip/112\">BIP112</a>:     IF         2 <Alice's pubkey> <Bob's pubkey> <Escrow's pubkey> 3 CHECKMULTISIG     ELSE         \"30d\" CHECKSEQUENCEVERIFY DROP         <Alice's pubkey> CHECKSIG     ENDIF</p>\n<p>Using compressed public key, the size of this script is 150 bytes.</p>\n<p>With MAST, this script could be broken down into 2 mutually exclusive branches:<sup class=\"footnote-ref\"><a href=\"#fn-2\" id=\"fnref-2\">[2]</a></sup>     2 <Alice's pubkey> <Bob's pubkey> <Escrow's pubkey> 3 CHECKMULTISIGVERIFY (105 bytes)     \"30d\" CHECKSEQUENCEVERIFY <Alice's pubkey> CHECKSIGVERIFY (42 bytes)</p>\n<p>Since only one branch will be published, it is more difficult for a blockchain analyst to determine the details of the escrow.</p>\n<h3 id=\"hashed-time-lock-contract\">Hashed Time-Lock Contract</h3>\n<p>The following is the \"Hashed TIme-Lock Contract\" example in <a href=\"/bip/112\">BIP112</a>:     HASH160 DUP <R-HASH> EQUAL     IF         \"24h\" CHECKSEQUENCEVERIFY         2DROP         <Alice's pubkey>     ELSE         <Commit-Revocation-Hash> EQUAL         NOTIF             \"Timestamp\" CHECKLOCKTIMEVERIFY DROP         ENDIF         <Bob's pubkey>     ENDIF     CHECKSIG</p>\n<p>To create a MAST Root, it is flattened to 3 mutually exclusive branches:     HASH160 <R-HASH> EQUALVERIFY \"24h\" CHECKSEQUENCEVERIFY <Alice's pubkey> CHECKSIGVERIFY     HASH160 <Commit-Revocation-Hash> EQUALVERIFY <Bob's pubkey> CHECKSIGVERIFY     \"Timestamp\" CHECKLOCKTIMEVERIFY <Bob's pubkey> CHECKSIGVERIFY</p>\n<p>which significantly improves readability and reduces the witness size when it is redeemed.</p>\n<h3 id=\"large-multi-signature-constructs\">Large multi-signature constructs</h3>\n<p>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.</p>\n<p>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.</p>\n<h3 id=\"commitment-of-non-consensus-enforced-data\">Commitment of non-consensus enforced data</h3>\n<p>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.</p>\n<p>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\".</p>\n<h2 id=\"backward-compatibility\">Backward compatibility</h2>\n<p>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.</p>\n<h2 id=\"deployment\">Deployment</h2>\n<p>This BIP depends on <a href=\"/bip/141\">BIP141</a> and will be deployed by version-bits <a href=\"/bip/9\">BIP9</a> after BIP141 is enforced. Exact details TBD.</p>\n<h2 id=\"credits\">Credits</h2>\n<p>The idea of MAST originates from Russell O’Connor, Pieter Wuille, and <a href=\"https://bitcointalk.org/index.php?topic=255145.msg2757327#msg2757327\">Peter Todd</a>.</p>\n<h2 id=\"reference-implementation\">Reference Implementation</h2>\n<p><a href=\"https://github.com/jl2012/bitcoin/tree/bip114v2\">https://github.com/jl2012/bitcoin/tree/bip114v2</a> (WIP)</p>\n<pre><code class=\"language-cpp\">//New rules apply if version byte is 1 and witness program size is 32 bytes\nif (witversion == 1 && program.size() == 32 && (flags & SCRIPT_VERIFY_MAST)) {\n    CHashWriter sRoot(SER_GETHASH, 0);\n    CHashWriter sScriptHash(SER_GETHASH, 0);\n    uint32_t nMASTVersion = 0;\n    size_t stacksize = witness.stack.size();\n    if (stacksize &lt; 4)\n        return set_error(serror, SCRIPT_ERR_INVALID_MAST_STACK);\n    std::vector&lt;unsigned char&gt; metadata = witness.stack.back(); // The last witness stack item is metadata\n    if (metadata.size() &lt; 1 || metadata.size() &gt; 5)\n        return set_error(serror, SCRIPT_ERR_INVALID_MAST_STACK);\n\n    // The first byte of metadata is the number of subscripts (1 to 255)\n    uint32_t nSubscript = static_cast&lt;uint32_t&gt;(metadata[0]);\n    if (nSubscript == 0 || stacksize &lt; nSubscript + 3)\n        return set_error(serror, SCRIPT_ERR_INVALID_MAST_STACK);\n    int nOpCount = nSubscript; // Each condition consumes a nOpCount\n    sScriptHash &lt;&lt; metadata[0];\n\n    // The rest of metadata is MAST version in minimally-coded unsigned little endian int\n    if (metadata.back() == 0)\n        return set_error(serror, SCRIPT_ERR_INVALID_MAST_STACK);\n    if (metadata.size() &gt; 1) {\n        for (size_t i = 1; i != metadata.size(); ++i)\n            nMASTVersion |= static_cast&lt;uint32_t&gt;(metadata[i]) &lt;&lt; 8 * (i - 1);\n    }\n\n    // Unknown MAST version is non-standard\n    if (nMASTVersion &gt; 0 && flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM)\n        return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);\n\n    sRoot &lt;&lt; nMASTVersion;\n\n    // The second last witness stack item is the pathdata\n    // Size of pathdata must be divisible by 32 (0 is allowed)\n    // Depth of the Merkle tree is implied by the size of pathdata, and must not be greater than 32\n    std::vector&lt;unsigned char&gt; pathdata = witness.stack.at(stacksize - 2);\n    if (pathdata.size() & 0x1F)\n        return set_error(serror, SCRIPT_ERR_INVALID_MAST_STACK);\n    unsigned int depth = pathdata.size() &gt;&gt; 5;\n    if (depth &gt; 32)\n        return set_error(serror, SCRIPT_ERR_INVALID_MAST_STACK);\n\n    // Each level of Merkle tree consumes a nOpCount\n    // Evaluation of version 0 MAST terminates early if there are too many nOpCount\n    // Not enforced in unknown MAST version for upgrade flexibility\n    nOpCount = nOpCount + depth;\n    if (nMASTVersion == 0 && nOpCount &gt; MAX_OPS_PER_SCRIPT)\n        return set_error(serror, SCRIPT_ERR_OP_COUNT);\n\n    // path is a vector of 32-byte hashes\n    std::vector &lt;uint256&gt; path;\n    path.resize(depth);\n    for (unsigned int j = 0; j &lt; depth; j++)\n        memcpy(path[j].begin(), &pathdata[32 * j], 32);\n\n    // The third last witness stack item is the positiondata\n    // Position is in minimally-coded unsigned little endian int\n    std::vector&lt;unsigned char&gt; positiondata = witness.stack.at(stacksize - 3);\n    if (positiondata.size() &gt; 4)\n        return set_error(serror, SCRIPT_ERR_INVALID_MAST_STACK);\n    uint32_t position = 0;\n    if (positiondata.size() &gt; 0) {\n        if (positiondata.back() == 0)\n            return set_error(serror, SCRIPT_ERR_INVALID_MAST_STACK);\n        for (size_t k = 0; k != positiondata.size(); ++k)\n            position |= static_cast&lt;uint32_t&gt;(positiondata[k]) &lt;&lt; 8 * k;\n    }\n\n    // Position value must not exceed the number of leaves at the depth\n    if (depth &lt; 32) {\n        if (position &gt;= (1U &lt;&lt; depth))\n            return set_error(serror, SCRIPT_ERR_INVALID_MAST_STACK);\n    }\n\n    // Sub-scripts are located before positiondata\n    for (size_t i = stacksize - nSubscript - 3; i &lt;= stacksize - 4; i++) {\n        CScript subscript(witness.stack.at(i).begin(), witness.stack.at(i).end());\n\n        // Evaluation of version 0 MAST terminates early if script is oversize\n        // Not enforced in unknown MAST version for upgrade flexibility\n        if (nMASTVersion == 0 && (scriptPubKey.size() + subscript.size()) &gt; MAX_SCRIPT_SIZE)\n            return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);\n        uint256 hashSubScript;\n        CHash256().Write(&subscript[0], subscript.size()).Finalize(hashSubScript.begin());\n        sScriptHash &lt;&lt; hashSubScript;\n        scriptPubKey = scriptPubKey + subscript; // Final scriptPubKey is a serialization of subscripts\n    }\n    uint256 hashScript = sScriptHash.GetHash();\n\n    // Calculate MAST Root and compare against witness program\n    uint256 rootScript = ComputeMerkleRootFromBranch(hashScript, path, position);\n    sRoot &lt;&lt; rootScript;\n    uint256 rootMAST = sRoot.GetHash();\n    if (memcmp(rootMAST.begin(), &program[0], 32))\n        return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);\n\n    if (nMASTVersion == 0) {\n        stack = std::vector&lt;std::vector&lt;unsigned char&gt; &gt;(witness.stack.begin(), witness.stack.end() - 3 - nSubscript);\n        for (unsigned int i = 0; i &lt; stack.size(); i++) {\n            if (stack.at(i).size() &gt; MAX_SCRIPT_ELEMENT_SIZE)\n                return set_error(serror, SCRIPT_ERR_PUSH_SIZE);\n        }\n\n        // Script evaluation must not fail, and return an empty stack\n        if (!EvalScript(stack, scriptPubKey, flags, checker, SIGVERSION_WITNESS_V1, nOpCount, serror))\n            return false;\n        if (stack.size() != 0)\n            return set_error(serror, SCRIPT_ERR_EVAL_FALSE);\n    }\n\n    return set_success(serror);\n}</code></pre>\n<p>Copying from <code>src/consensus/merkle.cpp</code>:</p>\n<pre><code class=\"language-cpp\">uint256 ComputeMerkleRootFromBranch(const uint256& leaf, const std::vector&lt;uint256&gt;& vMerkleBranch, uint32_t nIndex) {\n    uint256 hash = leaf;\n    for (std::vector&lt;uint256&gt;::const_iterator it = vMerkleBranch.begin(); it != vMerkleBranch.end(); ++it) {\n        if (nIndex & 1) {\n            hash = Hash(BEGIN(*it), END(*it), BEGIN(hash), END(hash));\n        } else {\n            hash = Hash(BEGIN(hash), END(hash), BEGIN(*it), END(*it));\n        }\n        nIndex &gt;&gt;= 1;\n    }\n    return hash;\n}</code></pre>\n<h2 id=\"references\">References</h2>\n<ul><li>\n<a href=\"/bip/141\">BIP141 Segregated Witness (Consensus layer)</a>\n</li></ul>\n<h2 id=\"footnotes\">Footnotes</h2>\n<ol class=\"footnotes\"><li id=\"fn-1\">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. <a href=\"#fnref-1\" class=\"footnote-back\" aria-label=\"Back to text\">↩</a></li><li id=\"fn-2\">In BIPXXX, it is proposed that CHECKLOCKTIMEVERIFY and CHECKSEQUENCEVERIFY will pop the top stack item <a href=\"#fnref-2\" class=\"footnote-back\" aria-label=\"Back to text\">↩</a></li></ol>\n<h2 id=\"copyright\">Copyright</h2>\n<p>This document is placed in the public domain.</p>","toc":[{"id":"abstract","title":"Abstract","level":2},{"id":"motivation","title":"Motivation","level":2},{"id":"evolution-of-bitcoin-script-system","title":"Evolution of Bitcoin script system","level":3},{"id":"merkelized-abstract-syntax-tree","title":"Merkelized Abstract Syntax Tree","level":3},{"id":"specification","title":"Specification","level":2},{"id":"rationale","title":"Rationale","level":2},{"id":"mast-structure","title":"MAST Structure","level":3},{"id":"mast-version","title":"MAST Version","level":3},{"id":"nopcount-limit","title":"nOpCount limit","level":3},{"id":"script-evaluation","title":"Script evaluation","level":3},{"id":"examples","title":"Examples","level":2},{"id":"calculation-of-mast-root","title":"Calculation of MAST Root","level":3},{"id":"imbalance-mast","title":"Imbalance MAST","level":3},{"id":"escrow-with-timeout","title":"Escrow with Timeout","level":3},{"id":"hashed-time-lock-contract","title":"Hashed Time-Lock Contract","level":3},{"id":"large-multi-signature-constructs","title":"Large multi-signature constructs","level":3},{"id":"commitment-of-non-consensus-enforced-data","title":"Commitment of non-consensus enforced data","level":3},{"id":"backward-compatibility","title":"Backward compatibility","level":2},{"id":"deployment","title":"Deployment","level":2},{"id":"credits","title":"Credits","level":2},{"id":"reference-implementation","title":"Reference Implementation","level":2},{"id":"references","title":"References","level":2},{"id":"footnotes","title":"Footnotes","level":2},{"id":"copyright","title":"Copyright","level":2}],"history":{"totalCommits":15,"firstCommit":"2016-04-12T20:20:06+00:00","lastUpdated":"2026-09-15T02:56:36+04:00","events":[{"sha":"3a13d60ff202b94b9e02e7c58d6a7e87a94f3899","date":"2026-09-15T02:56:36+04:00","author":"Kanan","message":"bips 89/114/441: add missing Footnotes and references tag (#2289)","url":"https://github.com/bitcoin/bips/commit/3a13d60ff202b94b9e02e7c58d6a7e87a94f3899","kind":"edit"},{"sha":"24e96e870fffaa257b465ce1f0370c14aac588e8","date":"2025-10-08T14:59:36-07:00","author":"Murch","message":"process: Created ↦ Assigned","url":"https://github.com/bitcoin/bips/commit/24e96e870fffaa257b465ce1f0370c14aac588e8","kind":"edit"},{"sha":"5207ef92a52d0b8902895b0dbb40823a4d698ec9","date":"2025-04-11T20:08:17-07:00","author":"Murch","message":"process: Author ↦ Authors","url":"https://github.com/bitcoin/bips/commit/5207ef92a52d0b8902895b0dbb40823a4d698ec9","kind":"edit"},{"sha":"59730dec4fb641a41589aa1b91d3c452f13e0e36","date":"2025-04-11T20:05:13-07:00","author":"Murch","message":"process: Remove Comments-URI and -Summary","url":"https://github.com/bitcoin/bips/commit/59730dec4fb641a41589aa1b91d3c452f13e0e36","kind":"edit"},{"sha":"a233bde4af52c6a11269e2e6dd9707abce441ffe","date":"2025-04-11T18:19:21-07:00","author":"Murch","message":"process: Standards Track ↦ Specification","url":"https://github.com/bitcoin/bips/commit/a233bde4af52c6a11269e2e6dd9707abce441ffe","kind":"edit"},{"sha":"66defbdc03ad64ccddfd373e1c59af9a41ab990f","date":"2025-04-11T18:11:55-07:00","author":"Murch","message":"process: Deferred/Obsolete/Rejected/Replaced/Withdrawn ↦ Closed","url":"https://github.com/bitcoin/bips/commit/66defbdc03ad64ccddfd373e1c59af9a41ab990f","kind":"status"},{"sha":"2157872faa749e02e54d3a47ba9d17ebbefa5c21","date":"2024-05-13T10:25:31+08:00","author":"Afanti","message":"bip-0114: fix typo","url":"https://github.com/bitcoin/bips/commit/2157872faa749e02e54d3a47ba9d17ebbefa5c21","kind":"edit"},{"sha":"3711a828afced7c3ee20a7ef420892988b505216","date":"2020-08-21T08:08:17+02:00","author":"Janus","message":"Reject 114 (expired)","url":"https://github.com/bitcoin/bips/commit/3711a828afced7c3ee20a7ef420892988b505216","kind":"edit"},{"sha":"959fecc15bdad070afa63455468b1dba54655fa6","date":"2016-11-30T09:47:31+00:00","author":"Luke Dashjr","message":"Promote BIP 2 Draft->Active, and implement it","url":"https://github.com/bitcoin/bips/commit/959fecc15bdad070afa63455468b1dba54655fa6","kind":"status"},{"sha":"72f18918a8ae655212ea2700b30f0dc4d758b843","date":"2016-11-30T09:45:33+00:00","author":"Luke Dashjr","message":"Promote BIP 123 Draft->Active, and implement it","url":"https://github.com/bitcoin/bips/commit/72f18918a8ae655212ea2700b30f0dc4d758b843","kind":"status"},{"sha":"9da1f65e390ca18c1d63abea8c4a112a6c95049d","date":"2016-07-29T00:59:06+08:00","author":"Johnson Lau","message":"BIP114: MAST proposal v2","url":"https://github.com/bitcoin/bips/commit/9da1f65e390ca18c1d63abea8c4a112a6c95049d","kind":"edit"},{"sha":"7478ee3260c0d3c0cef39233931b307691764edc","date":"2016-06-24T01:59:25+08:00","author":"jl2012","message":"BIP112/114 example fix","url":"https://github.com/bitcoin/bips/commit/7478ee3260c0d3c0cef39233931b307691764edc","kind":"edit"},{"sha":"3ef07340b42f3abee4b01d30d7a53315d0b30fa1","date":"2016-04-14T00:43:16+08:00","author":"jl2012","message":"BIP114: Clarifying reference implementation","url":"https://github.com/bitcoin/bips/commit/3ef07340b42f3abee4b01d30d7a53315d0b30fa1","kind":"edit"},{"sha":"58409dd0e8b487bd3a4a42d6de41bc0631fe95ed","date":"2016-04-13T11:46:17-04:00","author":"instagibbs","message":"Some clarification on path meaning and structure","url":"https://github.com/bitcoin/bips/commit/58409dd0e8b487bd3a4a42d6de41bc0631fe95ed","kind":"edit"},{"sha":"952ba4ad16fe567995c54f44f1e6f1690bfff0db","date":"2016-04-12T20:20:06+00:00","author":"Luke Dashjr","message":"Assign BIP 114: Merkelized Abstract Syntax Tree","url":"https://github.com/bitcoin/bips/commit/952ba4ad16fe567995c54f44f1e6f1690bfff0db","kind":"edit"}]}}