Return-Path: Received: from smtp4.osuosl.org (smtp4.osuosl.org [IPv6:2605:bc80:3010::137]) by lists.linuxfoundation.org (Postfix) with ESMTP id DDDF1C002A for ; Mon, 24 Apr 2023 19:37:35 +0000 (UTC) Received: from localhost (localhost [127.0.0.1]) by smtp4.osuosl.org (Postfix) with ESMTP id C5320414C4 for ; Mon, 24 Apr 2023 19:37:35 +0000 (UTC) DKIM-Filter: OpenDKIM Filter v2.11.0 smtp4.osuosl.org C5320414C4 Authentication-Results: smtp4.osuosl.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20221208 header.b=FGBCdtXR X-Virus-Scanned: amavisd-new at osuosl.org X-Spam-Flag: NO X-Spam-Score: -2.098 X-Spam-Level: X-Spam-Status: No, score=-2.098 tagged_above=-999 required=5 tests=[BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, FREEMAIL_FROM=0.001, HTML_MESSAGE=0.001, RCVD_IN_DNSWL_NONE=-0.0001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001] autolearn=ham autolearn_force=no Received: from smtp4.osuosl.org ([127.0.0.1]) by localhost (smtp4.osuosl.org [127.0.0.1]) (amavisd-new, port 10024) with ESMTP id 4ydjOeOQG5Uf for ; Mon, 24 Apr 2023 19:37:33 +0000 (UTC) X-Greylist: whitelisted by SQLgrey-1.8.0 DKIM-Filter: OpenDKIM Filter v2.11.0 smtp4.osuosl.org 71C574151A Received: from mail-ot1-x335.google.com (mail-ot1-x335.google.com [IPv6:2607:f8b0:4864:20::335]) by smtp4.osuosl.org (Postfix) with ESMTPS id 71C574151A for ; Mon, 24 Apr 2023 19:37:33 +0000 (UTC) Received: by mail-ot1-x335.google.com with SMTP id 46e09a7af769-6a5ec0d8d8aso3432831a34.2 for ; Mon, 24 Apr 2023 12:37:33 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20221208; t=1682365052; x=1684957052; h=to:subject:message-id:date:from:mime-version:from:to:cc:subject :date:message-id:reply-to; bh=SU8/TjzvkEw24wrbly8StySzcL3joRaxNTKxTz/Pq/I=; b=FGBCdtXRUIXZ/larGf2t3oNJo/3yaTnofQYEVWPdpRqPX20VMihooMcZVjyECEEzKd JAsDhUvhkYUI9GW8lKrgrmnEPX4oUf+EKww7CpbZ6ZkgfOi/0f6o2yNPLEYvkeGBy6S/ nZoi2ZK+jEHTKUS0Nt+WzkYLz27VXY7XZF+ixWPCeVLx0qVvbbqmPs/5wym1lv8BeMm3 wj7Oy4jrL3nSTwNtloeiGTvkS/rn1GZ6gnCVnG+3W+yctfalUZr9xg9QuUXYZT777WHt tboMn8af2cb/Jr0cDgfxmi4auslu5P4QBz7KVtRKkwfZJIy+b9njmi4HBb0LL4Rf4XmB 4TDA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20221208; t=1682365052; x=1684957052; h=to:subject:message-id:date:from:mime-version:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=SU8/TjzvkEw24wrbly8StySzcL3joRaxNTKxTz/Pq/I=; b=jIhDwVdwBYKKRUDE6TYsS8iA7QFAPKXI605gPvTzJn1aSq15OcElRQ5cbsfAjcloIW RMWPImsH2xe8RDcw+iQkhHOqETZsyuhpf+4dD67sYpYnpLBW7PJwswsM3nUTAb9bBKih wEFW1ujx+ko8yu/TwuCieXfpPp6cgz6TgBEy9mJZWDaJ0AWPxXAAUplP8157nDY1GmvU d7gXSSKaMrMI4oyUoT53rRcHkg7/gdG6zySGwCvt1sxVAp5IoG/4JZfs0Rta+FLUh+/P F/nFeg8teTZMpYLxhbPrkltkv0d2MK9LXH+aDR5E2vwTsBJR07oNMnADNlOMPp9jl/zp 4ejw== X-Gm-Message-State: AAQBX9dfu+FXTwe+zXn7/oOTg+s09Q5wljRrZbVADzIIgaLlLKb/3syW WT0SLYjaDnSnX2RgT4HWvOVD1jJfyk6rMieqMt/7nauN9w0= X-Google-Smtp-Source: AKy350YTfT8KkJ9UaL9lwNl3+svTBapVPR5Qzddm66DK+9xTIPVo+lUQam2u++LYhqeM1vaUpKHWM7cznkobusIySRo= X-Received: by 2002:a05:6830:1603:b0:6a5:f6f6:4ebf with SMTP id g3-20020a056830160300b006a5f6f64ebfmr8168077otr.37.1682365051952; Mon, 24 Apr 2023 12:37:31 -0700 (PDT) MIME-Version: 1.0 From: Salvatore Ingala Date: Mon, 24 Apr 2023 21:37:20 +0200 Message-ID: To: Bitcoin Protocol Discussion Content-Type: multipart/alternative; boundary="0000000000004de2e205fa1a2340" X-Mailman-Approved-At: Mon, 24 Apr 2023 20:36:30 +0000 Subject: [bitcoin-dev] Vaults in the MATT framework X-BeenThere: bitcoin-dev@lists.linuxfoundation.org X-Mailman-Version: 2.1.15 Precedence: list List-Id: Bitcoin Protocol Discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Mon, 24 Apr 2023 19:37:36 -0000 --0000000000004de2e205fa1a2340 Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: quoted-printable Hello list, TL;DR: the core opcodes of MATT can build vaults with a very similar design to OP_VAULT. Code example here: https://github.com/bitcoin-inquisition/bitcoin/compare/24.0...bigspider:bit= coin-inquisition:matt-vault In my previous emails about the MATT proposal for smart contracts in bitcoin [1], I mostly focused on proving its generality; that is, it allows arbitrary smart contracts thanks to fraud proofs. While I still find this "completeness" result compelling, I spent more time thinking about the framework itself; the construction is not very interesting if it turns simple things into complicated ones. Luckily, this is not the case. In particular, in this email we will not merkleize anything (other than taptrees). This post describes some progress into formalizing the semantics of the cor= e opcodes, and demonstrates how they could be used to create vaults that seem comparable to the ones built with OP_VAULT [2], despite using general purpose opcodes. An implementation and some minimal tests matching the content of this e-mail can be found in the link above, using the bitcoin-inquisition as the base branch. Note that the linked code is not well tested and is only intended for exploratory and demonstrative purposes; therefore, bugs are likely at this stage. ########################## # PART 1: MATT's core ########################## In this section, I will discuss plausible semantics for the core opcodes for MATT. The two core opcodes are defined below as OP_CHECKINPUTCONTRACTVERIFY and OP_CHECKOUTPUTCONTRACTVERIFY. (the initial posts named them OP_CHECK{INPUT,OUTPUT}COVENANTVERIFY) They enhance Script with the following capabilities: - decide the taptree of the output - embed some (dynamically computed) data in the output - access the embedded data in the current UTXO (if any) The opcodes below are incomplete, as they only control the output's Script and not the amounts; more on that below. Other than that, the semantics should be quite close to the "right" one for the MATT framework. ### The opcodes case OP_CHECKINPUTCONTRACTVERIFY: { // OP_CHECKINPUTCONTRACTVERIFY is only available in Tapscript if (sigversion =3D=3D SigVersion::BASE || sigversion =3D=3D SigVersion::WITNESS_V0) return set_error(serror, SCRIPT_ERR_BAD_OPCODE); // (x d -- ) if (stack.size() < 2) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); valtype& x =3D stacktop(-2); valtype& d =3D stacktop(-1); if (x.size() !=3D 32 || d.size() !=3D 32) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); const XOnlyPubKey nakedXOnlyKey{Span{x.data(), x.data() + 32}}; const uint256 data(d); if (!execdata.m_internal_key.has_value()) return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR); // TODO // Verify that tweak(lift_x(x), d) equals the internal pubkey if (!execdata.m_internal_key.value().CheckDoubleTweak(nakedXOnlyKey, &data, nullptr)) return set_error(serror, SCRIPT_ERR_WRONGCONTRACTDATA); popstack(stack); popstack(stack); } break; case OP_CHECKOUTPUTCONTRACTVERIFY: { // OP_CHECKOUTPUTCONTRACTVERIFY is only available in Tapscript if (sigversion =3D=3D SigVersion::BASE || sigversion =3D=3D SigVersion::WITNESS_V0) return set_error(serror, SCRIPT_ERR_BAD_OPCODE); // (out_i x taptree d -- ) if (stack.size() < 4) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); int out_i =3D CScriptNum(stacktop(-4), fRequireMinimal).getint(); valtype& x =3D stacktop(-3); valtype& taptree =3D stacktop(-2); valtype& d =3D stacktop(-1); auto outps =3D checker.GetTxvOut(); // Return error if the evaluation context is unavailable if (!outps) return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR); // TODO if (x.size() !=3D 32 || taptree.size() !=3D 32 || (d.size() !=3D 0 && d.size() !=3D 32)) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); if (out_i < 0 || out_i >=3D (int)outps->size()) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); const XOnlyPubKey nakedXOnlyKey{Span{x.data(), x.data() + 32}}; const uint256 data(d); const uint256 *data_ptr =3D (d.size() =3D=3D 0 ? nullptr : &data); const uint256 merkle_tree(taptree); CScript scriptPubKey =3D outps->at(out_i).scriptPubKey; if (scriptPubKey.size() !=3D 1 + 1 + 32 || scriptPubKey[0] !=3D OP_1 || scriptPubKey[1] !=3D 32) return set_error(serror, SCRIPT_ERR_WRONGCONTRACTDATA); const XOnlyPubKey outputXOnlyKey{Span{scriptPubKey.data() + 2, scriptPubKey.data() + 34}}; // Verify that taptweak(tweak(lift_x(x), d), taptree) equals the internal pubkey if (!outputXOnlyKey.CheckDoubleTweak(nakedXOnlyKey, data_ptr, &merkle_tree)) return set_error(serror, SCRIPT_ERR_WRONGCONTRACTDATA); popstack(stack); popstack(stack); popstack(stack); popstack(stack); } break; ### Commentary CheckDoubleTweak function (implemented in the branch) gets an x-only pubkey= , optionally some data, and optionally taptree's merkle root. It verifies that the x-only pubkey being tested equals the given naked pubkey, optionally tweaked with the embedded data, optionally tweaked with the tagged hash of the merkle tree per BIP-0341 [3]. Making both the tweaks optional allows to simplify the code, and also to obtain more compact scripts in some spending paths. In words: - OP_CHECKINPUTCONTRACTVERIFY: verify that the current input's internal key contains some embedded data (which would typically be passed through the witness stack) - OP_CHECKOUTPUTCONTRACTVERIFY: verify that a given output is a certain P2T= R output script containing the desired embedded data. TBD if the tweaking used for the embedded data tweak should use a tagged hash; omitted for simplicity in this demo implementation. ### Amount preservation In the code above and in the linked demo implementation, the opcodes only operate on the scriptPubkey; a complete implementation would want to make sure that amounts are correctly preserved. The most direct and general way to address this would be to allow direct introspection on the output amounts. This has the complication that output amounts require 64-bits arithmetics, as discussed in the context of other proposals, for example: [4]. One more limited approach that works well for many interesting contracts is that of the deferred checks, implemented in OP_VAULT [2]. The idea is that all the amounts of the inputs that commit to the same output script with OP_CHECKOUTPUTCONTRACTVERIFY are added together, and the script interpreter requires that the amount of that output is not smaller than the total amount of those inputs. This check is therefore transaction-wide rather than being tested during the input's script evaluation. This behaviour is adequate for vaults and likely suitable for many other applications; however, it's not the most general approach. I didn't try to implement it yet, and defer the decision on the best approach to a later time. ### Extensions The opcodes above are not enough for the full generality of MATT: one would need to add an opcode like OP_SHA256CAT to allow the data embedding to commit to multiple pieces of data. This is not used in today's post, therefore I left it out of these code examples. It would be easy to extend OP_CHECKOUTPUTCONTRACTVERIFY to also apply for an arbitrary input (typically, different from the currently executed one); there are likely use cases for that, allowing to define contracts with more complex cross-input semantics, but I preferred to keep things simple. Of course, one could also entirely replace CICV/COCV with generic full introspection on inputs/output's program, plus opcodes for elliptic curve math and tagged hashes. ########################## # PART 2: Vaults with MATT ########################## In the rest of this post, I will document the first attempt at creating a vault using the opcodes described. While not an attempt at cloning exactly the functionality of OP_VAULT [2], it borrows heavily from the excellent work that was done there. In particular, it also inherits the choice of using OP_CTV as a primitive, building on top of the bitcoin-inquisition's current branch that has alread= y merged OP_CTV. Reasonable vaults would be possible without CTV, but they would be less efficient, particularly in the case of sending to many addresses in a single unvaulting flow. ### Distilling OP_VAULT Abstracting from the implementation details, I mentally model a vault as a simple state machine with 2 states: [V] and [U]: [V]: the initial vault UTXO(s); [U]: the utxo produced by the "trigger transaction" during unvaulting. On the typical path: one or more [V] UTXOs are sent to the [U] state, and after a timelock set on [U] expires, [U] is spent to one or several destinations. Crucially, the destination outputs and amounts are already decided when [V] is spent into [U]. At any time before the funds are spent from [U], they can always be spent b= y sending them to some specified recovery path. There are two key elements that are part of OP_VAULT's semantics, and could be generalized: =E2=88=92 Forcing the script/amount of the next stepon =E2=88=92 Storing some data for future Script's access (in the vault's case= , a hash that commits to the final withdrawal transaction). CICV/COCV generalize both to arbitrary scripts (taptrees) and state machines, and to dynamical and witness-dependent data embedded in the pubkey of a P2T= R output. ### Vault parameters A contract that represents a vault has the following parameters (hardcoded in the script when the vault is created): - alternate_pk: a key that can be used any time. - spend_delay: the relative timelock before the withdrawal can be finalized= ; - recover_pk: a pubkey for a P2TR output where funds can be sent at any time. The alternate_pk is a pubkey that can optionally be used as the key-path spending condition for both states [V] and [U]. If such a spending condition is not desired, it can be replaced with a NUMS point, making the key-path unspendable. The spend_delay is the number of blocks that must be mined before the final withdrawal transaction In this example we also use an unvault_pk needed to authorize the unvaultin= g process (that is, spend [V] into [U]); this could be replaced with any miniscript or other conditions expressible in Script. ### P2TR structure for [V] (vault) internal key: alternate_pk Script 1: "trigger" # witness: { , , 2, OP_ROLL, OP_CHECKOUTPUTCONTRACTVERIFY, OP_CHECKSIG } Script 2: "recover" # witness: { recover_pk, OP_0, # no data tweak OP_0, # no taptweak OP_CHECKOUTPUTCONTRACTVERIFY, OP_TRUE } The "trigger" script requires in the witness an output index and the ctv-hash that describes the withdrawal transaction. COCV forces the output to contain the ctv-hash as embedded data. That's followed by the unvaulting condition =E2=88=92 in this example, a si= mple signature check. The "recover" script doesn't require any signature, and it simply forces the output specified in the witness to be a P2TR output with recover_pk as its pubkey. (Omitting the "recover" script in [V] would reduce the size of the witness by 32 bytes in the expected case, and might be preferred for some users) ### P2TR structure for [U] (unvaulting state) internal key: alternate_pk (tweaked with ctv_hash) Script 1: "withdrawal" # witness: { OP_DUP, # check that the top of the stack is the # embedded data in the current input , OP_SWAP, OP_CHECKINPUTCONTRACTVERIFY, # Check timelock , OP_CHECKSEQUENCEVERIFY, OP_DROP, # Check that the transaction output is as expected OP_CHECKTEMPLATEVERIFY } Script 2: "recover" # witness: { , OP_0, OP_0, OP_CHECKOUTPUTCONTRACTVERIFY, OP_TRUE } The "withdrawal" finalizes the transaction, by checking that the timelock expired and the outputs satisfy the CTV hash that was committed to in the previous transaction. The "recover" script is identical as before. ### Differences with OP_VAULT vaults Here I refer to the latest version of OP_VAULT at the time of writing. [5] It is not a thorough analysis. Unlike the implementation based on OP_VAULT, the [V] utxos don't have an option to add an additional output that is sent back to the same exact vault. Supporting this use case seems to require a more general way of handling th= e distribution of amounts than what I discussed in the section above: that would in fact need to be generalized to the case of multiple OP_CHECKOUTPUTCONTRACTVERIFY opcodes executed for the same input. By separating the ctv-hash (which is considered "data") from the scripts in the taptree, one entirely avoids the need to dynamically create taptrees and replace leaves in the covenant-encumbered UTXOs; in fact, the taptrees of [V] and [U] are already set in stone when [V] utxos are created, and only the "data" portion of [U]'s scriptPubKey is dynamically computed. In my opinion= , this makes it substantially easier to program "state machines" that control the behavior of coins, of which vaults are a special case. I hope you'll find this interesting, and look forward to your comments. Salvatore Ingala [1] - https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-November/02122= 3.html [2] - https://github.com/bitcoin/bips/pull/1421 [3] - https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki [4] - https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2021-September/0194= 20.html [5] - https://github.com/bitcoin/bips/blob/7112f308b356cdf0c51d917dbdc1b98e30621f= 80/bip-0345.mediawiki --0000000000004de2e205fa1a2340 Content-Type: text/html; charset="UTF-8" Content-Transfer-Encoding: quoted-printable
Hello list,

TL;DR: the core opcodes of MATT can bui= ld vaults with a very similar design
to OP_VAULT. Code example here:
=
=C2=A0 https://github.com/bitco= in-inquisition/bitcoin/compare/24.0...bigspider:bitcoin-inquisition:matt-va= ult


In my previous emails about the MATT proposal for smart = contracts in
bitcoin [1], I mostly focused on proving its generality; th= at is, it
allows arbitrary smart contracts thanks to fraud proofs.
While I still find this "completeness" result compelling, I spe= nt more time
thinking about the framework itself; the construction is no= t very interesting
if it turns simple things into complicated ones. Luck= ily, this is not the case.
In particular, in this email we will not merk= leize anything (other than taptrees).

This post describes some progr= ess into formalizing the semantics of the core
opcodes, and demonstrates= how they could be used to create vaults that seem
comparable to the one= s built with OP_VAULT [2], despite using general purpose
opcodes.
An implementation and some minimal tests matching the content of this
e= -mail can be found in the link above, using the bitcoin-inquisition as the<= br>base branch.

Note that the linked code is not well tested and is = only intended for
exploratory and demonstrative purposes; therefore, bug= s are likely at this
stage.


##########################
#= =C2=A0 =C2=A0 PART 1: MATT's core
##########################

= In this section, I will discuss plausible semantics for the core opcodes fo= r MATT.

The two core opcodes are defined below as OP_CHECKINPUTCONTR= ACTVERIFY and
OP_CHECKOUTPUTCONTRACTVERIFY.

(the initial posts na= med them OP_CHECK{INPUT,OUTPUT}COVENANTVERIFY)

They enhance Script w= ith the following capabilities:
=C2=A0 - decide the taptree of the outpu= t
=C2=A0 - embed some (dynamically computed) data in the output
=C2= =A0 - access the embedded data in the current UTXO (if any)

The opco= des below are incomplete, as they only control the output's Script and<= br>not the amounts; more on that below.

Other than that, the semanti= cs should be quite close to the "right" one for
the MATT frame= work.


### The opcodes

case OP_CH= ECKINPUTCONTRACTVERIFY:
{
=C2=A0 =C2=A0 // OP_CHECKINPUTCONTRACTVERIF= Y is only available in Tapscript
=C2=A0 =C2=A0 if (sigversion =3D=3D Sig= Version::BASE || sigversion =3D=3D SigVersion::WITNESS_V0) return set_error= (serror, SCRIPT_ERR_BAD_OPCODE);
=C2=A0 =C2=A0 // (x d -- )
=C2=A0 = =C2=A0 if (stack.size() < 2)
=C2=A0 =C2=A0 =C2=A0 =C2=A0 return set_e= rror(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
=C2=A0 =C2=A0 valtype&= amp; x =3D stacktop(-2);
=C2=A0 =C2=A0 valtype& d =3D stacktop(-1);<= br>=C2=A0 =C2=A0 if (x.size() !=3D 32 || d.size() !=3D 32)
=C2=A0 =C2=A0= =C2=A0 =C2=A0 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION)= ;
=C2=A0 =C2=A0 const XOnlyPubKey nakedXOnlyKey{Span<const unsigned c= har>{x.data(), x.data() + 32}};
=C2=A0 =C2=A0 const uint256 data(d);<= br>=C2=A0 =C2=A0 if (!execdata.m_internal_key.has_value())
=C2=A0 =C2=A0= =C2=A0 =C2=A0 return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR); =C2=A0//= TODO
=C2=A0 =C2=A0 // Verify that tweak(lift_x(x), d) equals the intern= al pubkey
=C2=A0 =C2=A0 if (!execdata.m_internal_key.value().CheckDouble= Tweak(nakedXOnlyKey, &data, nullptr))
=C2=A0 =C2=A0 =C2=A0 =C2=A0 re= turn set_error(serror, SCRIPT_ERR_WRONGCONTRACTDATA);
=C2=A0 =C2=A0 pops= tack(stack);
=C2=A0 =C2=A0 popstack(stack);
}
break;
case OP_CH= ECKOUTPUTCONTRACTVERIFY:
{
=C2=A0 =C2=A0 // OP_CHECKOUTPUTCONTRACTVER= IFY is only available in Tapscript
=C2=A0 =C2=A0 if (sigversion =3D=3D S= igVersion::BASE || sigversion =3D=3D SigVersion::WITNESS_V0) return set_err= or(serror, SCRIPT_ERR_BAD_OPCODE);
=C2=A0 =C2=A0 // (out_i x taptree d -= - )
=C2=A0 =C2=A0 if (stack.size() < 4)
=C2=A0 =C2=A0 =C2=A0 =C2= =A0 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
=C2=A0= =C2=A0 int out_i =3D CScriptNum(stacktop(-4), fRequireMinimal).getint();=C2=A0 =C2=A0 valtype& x =3D stacktop(-3);
=C2=A0 =C2=A0 valtype&a= mp; taptree =3D stacktop(-2);
=C2=A0 =C2=A0 valtype& d =3D stacktop(= -1);
=C2=A0 =C2=A0 auto outps =3D checker.GetTxvOut();
=C2=A0 =C2=A0 = // Return error if the evaluation context is unavailable
=C2=A0 =C2=A0 i= f (!outps)
=C2=A0 =C2=A0 =C2=A0 =C2=A0 return set_error(serror, SCRIPT_E= RR_UNKNOWN_ERROR); // TODO
=C2=A0 =C2=A0 if (x.size() !=3D 32 || taptree= .size() !=3D 32 || (d.size() !=3D 0 && d.size() !=3D 32))
=C2=A0= =C2=A0 =C2=A0 =C2=A0 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPE= RATION);
=C2=A0 =C2=A0 if (out_i < 0 || out_i >=3D (int)outps->= size())
=C2=A0 =C2=A0 =C2=A0 =C2=A0 return set_error(serror, SCRIPT_ERR_= INVALID_STACK_OPERATION);
=C2=A0 =C2=A0 const XOnlyPubKey nakedXOnlyKey{= Span<const unsigned char>{x.data(), x.data() + 32}};
=C2=A0 =C2=A0= const uint256 data(d);
=C2=A0 =C2=A0 const uint256 *data_ptr =3D (d.siz= e() =3D=3D 0 ? nullptr : &data);
=C2=A0 =C2=A0 const uint256 merkle_= tree(taptree);
=C2=A0 =C2=A0 CScript scriptPubKey =3D outps->at(out_i= ).scriptPubKey;
=C2=A0 =C2=A0 if (scriptPubKey.size() !=3D 1 + 1 + 32 ||= scriptPubKey[0] !=3D OP_1 || scriptPubKey[1] !=3D 32)
=C2=A0 =C2=A0 =C2= =A0 =C2=A0 return set_error(serror, SCRIPT_ERR_WRONGCONTRACTDATA);
=C2= =A0 =C2=A0 const XOnlyPubKey outputXOnlyKey{Span<const unsigned char>= {scriptPubKey.data() + 2, scriptPubKey.data() + 34}};
=C2=A0 =C2=A0 // V= erify that taptweak(tweak(lift_x(x), d), taptree) equals the internal pubke= y
=C2=A0 =C2=A0 if (!outputXOnlyKey.CheckDoubleTweak(nakedXOnlyKey, data= _ptr, &merkle_tree))
=C2=A0 =C2=A0 =C2=A0 =C2=A0 return set_error(se= rror, SCRIPT_ERR_WRONGCONTRACTDATA);
=C2=A0 =C2=A0 popstack(stack);
= =C2=A0 =C2=A0 popstack(stack);
=C2=A0 =C2=A0 popstack(stack);
=C2=A0 = =C2=A0 popstack(stack);
}
break;


### Commentary

= CheckDoubleTweak function (implemented in the branch) gets an x-only pubkey= ,
optionally some data, and optionally taptree's merkle root.
It = verifies that the x-only pubkey being tested equals the given naked pubkey,=
optionally tweaked with the embedded data, optionally tweaked with the = tagged
hash of the merkle tree per BIP-0341 [3].
Making both the twe= aks optional allows to simplify=C2=A0the code, and also to obtain
more compact scripts in some spending paths.

In words:

- OP_= CHECKINPUTCONTRACTVERIFY: verify that the current input's internal key<= br>=C2=A0 contains some embedded data (which would typically be passed thro= ugh the
=C2=A0 witness stack)
- OP_CHECKOUTPUTCONTRACTVERIFY: verify = that a given output=C2=A0is a certain P2TR
=C2=A0 output script containi= ng the desired embedded data.

TBD if the tweaking used for the embed= ded data tweak should use a tagged hash;
omitted for simplicity in this = demo implementation.

### Amount preservation

In the code abov= e and in the linked demo implementation, the opcodes only
operate on the= scriptPubkey; a complete implementation would want to make sure
that am= ounts are correctly preserved.

The most direct and general way to ad= dress this would be to allow direct
introspection on the output amounts.= This has the complication that output
amounts require 64-bits arithmeti= cs, as discussed in the context of other
proposals, for example: [4].
One more limited approach that works well for many interesting=C2=A0co= ntracts
is that of the deferred checks, implemented in OP_VAULT [2].
= The idea is that all the amounts of the inputs that commit to the same outp= ut
script with OP_CHECKOUTPUTCONTRACTVERIFY are added together, and the = script
interpreter requires that the amount of that output is not smalle= r than the
total amount of those inputs. This check is therefore transac= tion-wide rather
than being tested during the input's script evaluat= ion.

This behaviour is adequate for vaults and likely suitable for m= any other
applications; however, it's not the most general approach.= I didn't try to
implement it yet, and defer the decision on the bes= t approach to a later time.

### Extensions

The opcodes above = are not enough for the full generality of MATT: one would
need to add an= opcode like OP_SHA256CAT to allow the data embedding to commit
to multi= ple pieces of data.
This is not used in today's post, therefore I le= ft it out of these code examples.

It would be easy to extend OP_CHEC= KOUTPUTCONTRACTVERIFY to also apply for
an arbitrary input (typically, d= ifferent from the currently executed one); there
are likely use cases fo= r that, allowing to define contracts with more complex
cross-input seman= tics, but I preferred to keep things simple.

Of course, one could al= so entirely replace CICV/COCV with generic full
introspection on inputs/= output's program, plus opcodes for elliptic curve math
and tagged ha= shes.


##########################
#=C2=A0 =C2=A0 PART 2: Vault= s with MATT
##########################

In the rest of this post, = I will document the first attempt at creating a vault
using the opcodes = described.

While not an attempt at cloning exactly the functionality= of OP_VAULT [2],
it borrows heavily from the excellent work that was do= ne there.

In particular, it also inherits the choice of using OP_CTV= as a primitive,
building on top of the bitcoin-inquisition's curren= t branch that has already
merged OP_CTV. Reasonable vaults would be poss= ible without CTV, but they
would be less efficient, particularly in the = case of sending to many addresses
in a single unvaulting flow.

##= # Distilling OP_VAULT

Abstracting from the implementation details, I= mentally model a vault as a
simple state machine with 2 states: [V] and= [U]:

[V]: the initial vault UTXO(s);
[U]: the utxo produced by t= he "trigger transaction" during unvaulting.

On the typical= path: one or more [V] UTXOs are sent to the [U] state, and after
a time= lock set on [U] expires, [U] is spent to one or several destinations.
Cr= ucially, the destination outputs and amounts are already decided when [V] i= s
spent into [U].

At any time before the funds are spent from [U]= , they can always be spent by
sending them to some specified recovery pa= th.

There are two key elements that are part of OP_VAULT's seman= tics, and could be
generalized:

=E2=88=92 Forcing the script/amou= nt of the next stepon
=E2=88=92 Storing some data for future Script'= s access (in the vault's case, a hash
=C2=A0 =C2=A0that commits to t= he final withdrawal transaction).

CICV/COCV generalize both to arbit= rary scripts (taptrees) and state machines,
and to dynamical and witness= -dependent data embedded in the pubkey of a P2TR
output.

### Vaul= t parameters

A contract that represents a vault has the following pa= rameters (hardcoded in
the script when the vault is created):

- a= lternate_pk: a key that can be used any time.
- spend_delay: the relativ= e timelock before the withdrawal can be finalized;
- recover_pk: a pubke= y for a P2TR output where funds can be sent at any time.

The alterna= te_pk is a pubkey that can optionally be used as the key-path
spending c= ondition for both states [V] and [U]. If such a spending condition is notdesired, it can be replaced with a NUMS point, making the key-path unspe= ndable.

The spend_delay is the number of blocks that must be mined b= efore the final
withdrawal transaction

In this example we also us= e an unvault_pk needed to authorize the unvaulting
process (that is, spe= nd [V] into [U]); this could be replaced with any miniscript
or other co= nditions expressible in Script.

### P2TR structure for [V] (vault)
internal key: alternate_pk

Script 1: "trigger"
= =C2=A0 =C2=A0 =C2=A0 =C2=A0 # witness: <out_i> <ctv-hash>
{
=C2=A0 =C2=A0 <alternate_pk>,
=C2=A0 = =C2=A0 <merkle root of U's taptree>,
=C2=A0 =C2=A0 2, OP_ROLL,=
=C2=A0 =C2=A0 OP_CHECKOUTPUTCONTRACTVERIFY,

=C2=A0 =C2=A0 <un= vault_pk>
=C2=A0 =C2=A0 OP_CHECKSIG
}

Script 2: &quo= t;recover"
=C2=A0 =C2=A0 =C2=A0 =C2=A0 # witness: <out_i>
= {
=C2=A0 =C2=A0 recover_pk,
=C2=A0 =C2=A0 OP= _0, =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 = =C2=A0 =C2=A0 =C2=A0# no data tweak
=C2=A0 =C2=A0 OP_0, =C2=A0 =C2=A0 = =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2= =A0# no taptweak
=C2=A0 =C2=A0 OP_CHECKOUTPUTCONTRACTVERIFY,
=C2=A0 = =C2=A0 OP_TRUE
}


The "trigger" script requires i= n the witness an output index and the ctv-hash
that describes the withdr= awal transaction.
COCV forces the output to contain the ctv-hash as embe= dded data.
That's followed by the unvaulting condition =E2=88=92 in = this example, a simple
signature check.

The "recover" s= cript doesn't require any signature, and it simply forces
the output= specified in the witness to be a P2TR output with recover_pk as its
pub= key.

(Omitting the "recover" script in [V] would reduce th= e size of the witness by
32 bytes in the expected case, and might be pre= ferred for some users)

### P2TR structure for [U] (unvaulting state)=

internal key: alternate_pk (tweaked with ctv_hash)

Script 1:= "withdrawal"
=C2=A0 =C2=A0 =C2=A0 =C2=A0 # witness: <ctv_h= ash>
{
=C2=A0 =C2=A0 OP_DUP,

=C2= =A0 =C2=A0 # check that the top of the stack is the
=C2=A0 =C2=A0 # embe= dded data in the current input
=C2=A0 =C2=A0 <alternate_pk>, OP_SW= AP,
=C2=A0 =C2=A0 OP_CHECKINPUTCONTRACTVERIFY,

=C2=A0 =C2=A0 # Ch= eck timelock
=C2=A0 =C2=A0 <spend_delay>,
=C2=A0 =C2=A0 OP_CHEC= KSEQUENCEVERIFY,
=C2=A0 =C2=A0 OP_DROP,

=C2=A0 =C2=A0 # Check tha= t the transaction output is as expected
=C2=A0 =C2=A0 OP_CHECKTEMPLATEVE= RIFY
}


Script 2: "recover"
=C2=A0 =C2=A0 =C2= =A0 =C2=A0 # witness: <out_i>
{
=C2=A0= =C2=A0 <recover_pk>,
=C2=A0 =C2=A0 OP_0,
=C2=A0 =C2=A0 OP_0,=C2=A0 =C2=A0 OP_CHECKOUTPUTCONTRACTVERIFY,
=C2=A0 =C2=A0 OP_TRUE
}=


The "withdrawal" finalizes the transaction, by che= cking that the timelock expired and
the outputs satisfy the CTV h= ash that was committed to in the previous transaction.

The "rec= over" script is identical as before.


### Differences with O= P_VAULT vaults

Here I refer to the latest version of OP_VAULT at the= time of writing. [5]
It is not a thorough analysis.

Unlike the i= mplementation based on OP_VAULT, the [V] utxos don't have an option
= to add an additional output that is sent back to the same exact vault.
S= upporting this use case seems to require a more general way of handling the=
distribution of amounts than what I discussed in the section above: tha= t would
in fact need to be generalized to the case of multiple
OP_CHE= CKOUTPUTCONTRACTVERIFY opcodes executed for the same input.

By separ= ating the ctv-hash (which is considered "data") from the scripts = in the
taptree, one entirely avoids the need to dynamically create taptr= ees and
replace leaves in the covenant-encumbered UTXOs; in fact, the ta= ptrees of [V]
and [U] are already set in stone when [V] utxos are create= d, and only the
"data" portion of [U]'s scriptPubKey is dy= namically computed. In my opinion,
this makes it substantially easier to= program "state machines" that control the
behavior of coins, = of which vaults are a special case.

I hope you'll find this inte= resting, and look forward to your comments.

--0000000000004de2e205fa1a2340--