summaryrefslogtreecommitdiff
path: root/31/fc772a8dbf2fe4a8b64bea3d428f5a4ac09f89
blob: 1416ac99b5f429c7200a1727cb10e4acacf3dc51 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
Return-Path: <salvatore.ingala@gmail.com>
Received: from smtp4.osuosl.org (smtp4.osuosl.org [IPv6:2605:bc80:3010::137])
 by lists.linuxfoundation.org (Postfix) with ESMTP id DDDF1C002A
 for <bitcoin-dev@lists.linuxfoundation.org>;
 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 <bitcoin-dev@lists.linuxfoundation.org>;
 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 <bitcoin-dev@lists.linuxfoundation.org>;
 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 <bitcoin-dev@lists.linuxfoundation.org>;
 Mon, 24 Apr 2023 19:37:33 +0000 (UTC)
Received: by mail-ot1-x335.google.com with SMTP id
 46e09a7af769-6a5ec0d8d8aso3432831a34.2
 for <bitcoin-dev@lists.linuxfoundation.org>;
 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 <salvatore.ingala@gmail.com>
Date: Mon, 24 Apr 2023 21:37:20 +0200
Message-ID: <CAMhCMoHEa8vYqm7U9MKFC30_cbCoAJBgoGaP0SCvCXVTyA6TmQ@mail.gmail.com>
To: Bitcoin Protocol Discussion <bitcoin-dev@lists.linuxfoundation.org>
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 <bitcoin-dev.lists.linuxfoundation.org>
List-Unsubscribe: <https://lists.linuxfoundation.org/mailman/options/bitcoin-dev>, 
 <mailto:bitcoin-dev-request@lists.linuxfoundation.org?subject=unsubscribe>
List-Archive: <http://lists.linuxfoundation.org/pipermail/bitcoin-dev/>
List-Post: <mailto:bitcoin-dev@lists.linuxfoundation.org>
List-Help: <mailto:bitcoin-dev-request@lists.linuxfoundation.org?subject=help>
List-Subscribe: <https://lists.linuxfoundation.org/mailman/listinfo/bitcoin-dev>, 
 <mailto:bitcoin-dev-request@lists.linuxfoundation.org?subject=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<const unsigned char>{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<const unsigned char>{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<const unsigned
char>{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: <out_i> <ctv-hash>
{
    <alternate_pk>,
    <merkle root of U's taptree>,
    2, OP_ROLL,
    OP_CHECKOUTPUTCONTRACTVERIFY,

    <unvault_pk>
    OP_CHECKSIG
}

Script 2: "recover"
        # witness: <out_i>
{
    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: <ctv_hash>
{
    OP_DUP,

    # check that the top of the stack is the
    # embedded data in the current input
    <alternate_pk>, OP_SWAP,
    OP_CHECKINPUTCONTRACTVERIFY,

    # Check timelock
    <spend_delay>,
    OP_CHECKSEQUENCEVERIFY,
    OP_DROP,

    # Check that the transaction output is as expected
    OP_CHECKTEMPLATEVERIFY
}

Script 2: "recover"
        # witness: <out_i>
{
    <recover_pk>,
    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

<div dir=3D"ltr">Hello list,<br><br>TL;DR: the core opcodes of MATT can bui=
ld vaults with a very similar design<br>to OP_VAULT. Code example here:<br>=
<br>=C2=A0<a href=3D"https://github.com/bitcoin-inquisition/bitcoin/compare=
/24.0...bigspider:bitcoin-inquisition:matt-vault"> https://github.com/bitco=
in-inquisition/bitcoin/compare/24.0...bigspider:bitcoin-inquisition:matt-va=
ult</a><br><br><br>In my previous emails about the MATT proposal for smart =
contracts in<br>bitcoin [1], I mostly focused on proving its generality; th=
at is, it<br>allows arbitrary smart contracts thanks to fraud proofs.<br><b=
r>While I still find this &quot;completeness&quot; result compelling, I spe=
nt more time<br>thinking about the framework itself; the construction is no=
t very interesting<br>if it turns simple things into complicated ones. Luck=
ily, this is not the case.<br>In particular, in this email we will not merk=
leize anything (other than taptrees).<br><br>This post describes some progr=
ess into formalizing the semantics of the core<br>opcodes, and demonstrates=
 how they could be used to create vaults that seem<br>comparable to the one=
s built with OP_VAULT [2], despite using general purpose<br>opcodes.<br><br=
>An implementation and some minimal tests matching the content of this<br>e=
-mail can be found in the link above, using the bitcoin-inquisition as the<=
br>base branch.<br><br>Note that the linked code is not well tested and is =
only intended for<br>exploratory and demonstrative purposes; therefore, bug=
s are likely at this<br>stage.<br><br><br>##########################<br>#=
=C2=A0 =C2=A0 PART 1: MATT&#39;s core<br>##########################<br><br>=
In this section, I will discuss plausible semantics for the core opcodes fo=
r MATT.<br><br>The two core opcodes are defined below as OP_CHECKINPUTCONTR=
ACTVERIFY and<br>OP_CHECKOUTPUTCONTRACTVERIFY.<br><br>(the initial posts na=
med them OP_CHECK{INPUT,OUTPUT}COVENANTVERIFY)<br><br>They enhance Script w=
ith the following capabilities:<br>=C2=A0 - decide the taptree of the outpu=
t<br>=C2=A0 - embed some (dynamically computed) data in the output<br>=C2=
=A0 - access the embedded data in the current UTXO (if any)<br><br>The opco=
des below are incomplete, as they only control the output&#39;s Script and<=
br>not the amounts; more on that below.<br><br>Other than that, the semanti=
cs should be quite close to the &quot;right&quot; one for<br>the MATT frame=
work.<br><br><br>### The opcodes<br><br><font face=3D"monospace">case OP_CH=
ECKINPUTCONTRACTVERIFY:<br>{<br>=C2=A0 =C2=A0 // OP_CHECKINPUTCONTRACTVERIF=
Y is only available in Tapscript<br>=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);<br>=C2=A0 =C2=A0 // (x d -- )<br>=C2=A0 =
=C2=A0 if (stack.size() &lt; 2)<br>=C2=A0 =C2=A0 =C2=A0 =C2=A0 return set_e=
rror(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);<br>=C2=A0 =C2=A0 valtype&=
amp; x =3D stacktop(-2);<br>=C2=A0 =C2=A0 valtype&amp; d =3D stacktop(-1);<=
br>=C2=A0 =C2=A0 if (x.size() !=3D 32 || d.size() !=3D 32)<br>=C2=A0 =C2=A0=
 =C2=A0 =C2=A0 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION)=
;<br>=C2=A0 =C2=A0 const XOnlyPubKey nakedXOnlyKey{Span&lt;const unsigned c=
har&gt;{x.data(), x.data() + 32}};<br>=C2=A0 =C2=A0 const uint256 data(d);<=
br>=C2=A0 =C2=A0 if (!execdata.m_internal_key.has_value())<br>=C2=A0 =C2=A0=
 =C2=A0 =C2=A0 return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR); =C2=A0//=
 TODO<br>=C2=A0 =C2=A0 // Verify that tweak(lift_x(x), d) equals the intern=
al pubkey<br>=C2=A0 =C2=A0 if (!execdata.m_internal_key.value().CheckDouble=
Tweak(nakedXOnlyKey, &amp;data, nullptr))<br>=C2=A0 =C2=A0 =C2=A0 =C2=A0 re=
turn set_error(serror, SCRIPT_ERR_WRONGCONTRACTDATA);<br>=C2=A0 =C2=A0 pops=
tack(stack);<br>=C2=A0 =C2=A0 popstack(stack);<br>}<br>break;<br>case OP_CH=
ECKOUTPUTCONTRACTVERIFY:<br>{<br>=C2=A0 =C2=A0 // OP_CHECKOUTPUTCONTRACTVER=
IFY is only available in Tapscript<br>=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);<br>=C2=A0 =C2=A0 // (out_i x taptree d -=
- )<br>=C2=A0 =C2=A0 if (stack.size() &lt; 4)<br>=C2=A0 =C2=A0 =C2=A0 =C2=
=A0 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);<br>=C2=A0=
 =C2=A0 int out_i =3D CScriptNum(stacktop(-4), fRequireMinimal).getint();<b=
r>=C2=A0 =C2=A0 valtype&amp; x =3D stacktop(-3);<br>=C2=A0 =C2=A0 valtype&a=
mp; taptree =3D stacktop(-2);<br>=C2=A0 =C2=A0 valtype&amp; d =3D stacktop(=
-1);<br>=C2=A0 =C2=A0 auto outps =3D checker.GetTxvOut();<br>=C2=A0 =C2=A0 =
// Return error if the evaluation context is unavailable<br>=C2=A0 =C2=A0 i=
f (!outps)<br>=C2=A0 =C2=A0 =C2=A0 =C2=A0 return set_error(serror, SCRIPT_E=
RR_UNKNOWN_ERROR); // TODO<br>=C2=A0 =C2=A0 if (x.size() !=3D 32 || taptree=
.size() !=3D 32 || (d.size() !=3D 0 &amp;&amp; d.size() !=3D 32))<br>=C2=A0=
 =C2=A0 =C2=A0 =C2=A0 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPE=
RATION);<br>=C2=A0 =C2=A0 if (out_i &lt; 0 || out_i &gt;=3D (int)outps-&gt;=
size())<br>=C2=A0 =C2=A0 =C2=A0 =C2=A0 return set_error(serror, SCRIPT_ERR_=
INVALID_STACK_OPERATION);<br>=C2=A0 =C2=A0 const XOnlyPubKey nakedXOnlyKey{=
Span&lt;const unsigned char&gt;{x.data(), x.data() + 32}};<br>=C2=A0 =C2=A0=
 const uint256 data(d);<br>=C2=A0 =C2=A0 const uint256 *data_ptr =3D (d.siz=
e() =3D=3D 0 ? nullptr : &amp;data);<br>=C2=A0 =C2=A0 const uint256 merkle_=
tree(taptree);<br>=C2=A0 =C2=A0 CScript scriptPubKey =3D outps-&gt;at(out_i=
).scriptPubKey;<br>=C2=A0 =C2=A0 if (scriptPubKey.size() !=3D 1 + 1 + 32 ||=
 scriptPubKey[0] !=3D OP_1 || scriptPubKey[1] !=3D 32)<br>=C2=A0 =C2=A0 =C2=
=A0 =C2=A0 return set_error(serror, SCRIPT_ERR_WRONGCONTRACTDATA);<br>=C2=
=A0 =C2=A0 const XOnlyPubKey outputXOnlyKey{Span&lt;const unsigned char&gt;=
{scriptPubKey.data() + 2, scriptPubKey.data() + 34}};<br>=C2=A0 =C2=A0 // V=
erify that taptweak(tweak(lift_x(x), d), taptree) equals the internal pubke=
y<br>=C2=A0 =C2=A0 if (!outputXOnlyKey.CheckDoubleTweak(nakedXOnlyKey, data=
_ptr, &amp;merkle_tree))<br>=C2=A0 =C2=A0 =C2=A0 =C2=A0 return set_error(se=
rror, SCRIPT_ERR_WRONGCONTRACTDATA);<br>=C2=A0 =C2=A0 popstack(stack);<br>=
=C2=A0 =C2=A0 popstack(stack);<br>=C2=A0 =C2=A0 popstack(stack);<br>=C2=A0 =
=C2=A0 popstack(stack);<br>}<br>break;</font><br><br>### Commentary<br><br>=
CheckDoubleTweak function (implemented in the branch) gets an x-only pubkey=
,<br>optionally some data, and optionally taptree&#39;s merkle root.<br>It =
verifies that the x-only pubkey being tested equals the given naked pubkey,=
<br>optionally tweaked with the embedded data, optionally tweaked with the =
tagged<br>hash of the merkle tree per BIP-0341 [3].<div>Making both the twe=
aks optional allows to simplify=C2=A0the code, and also to obtain</div><div=
>more compact scripts in some spending paths.<br><br>In words:<br><br>- OP_=
CHECKINPUTCONTRACTVERIFY: verify that the current input&#39;s internal key<=
br>=C2=A0 contains some embedded data (which would typically be passed thro=
ugh the<br>=C2=A0 witness stack)<br>- OP_CHECKOUTPUTCONTRACTVERIFY: verify =
that a given output=C2=A0is a certain P2TR<br>=C2=A0 output script containi=
ng the desired embedded data.<br><br>TBD if the tweaking used for the embed=
ded data tweak should use a tagged hash;<br>omitted for simplicity in this =
demo implementation.<br><br>### Amount preservation<br><br>In the code abov=
e and in the linked demo implementation, the opcodes only<br>operate on the=
 scriptPubkey; a complete implementation would want to make sure<br>that am=
ounts are correctly preserved.<br><br>The most direct and general way to ad=
dress this would be to allow direct<br>introspection on the output amounts.=
 This has the complication that output<br>amounts require 64-bits arithmeti=
cs, as discussed in the context of other<br>proposals, for example: [4].<br=
><br>One more limited approach that works well for many interesting=C2=A0co=
ntracts<br>is that of the deferred checks, implemented in OP_VAULT [2].<br>=
The idea is that all the amounts of the inputs that commit to the same outp=
ut<br>script with OP_CHECKOUTPUTCONTRACTVERIFY are added together, and the =
script<br>interpreter requires that the amount of that output is not smalle=
r than the<br>total amount of those inputs. This check is therefore transac=
tion-wide rather<br>than being tested during the input&#39;s script evaluat=
ion.<br><br>This behaviour is adequate for vaults and likely suitable for m=
any other<br>applications; however, it&#39;s not the most general approach.=
 I didn&#39;t try to<br>implement it yet, and defer the decision on the bes=
t approach to a later time.<br><br>### Extensions<br><br>The opcodes above =
are not enough for the full generality of MATT: one would<br>need to add an=
 opcode like OP_SHA256CAT to allow the data embedding to commit<br>to multi=
ple pieces of data.<br>This is not used in today&#39;s post, therefore I le=
ft it out of these code examples.<br><br>It would be easy to extend OP_CHEC=
KOUTPUTCONTRACTVERIFY to also apply for<br>an arbitrary input (typically, d=
ifferent from the currently executed one); there<br>are likely use cases fo=
r that, allowing to define contracts with more complex<br>cross-input seman=
tics, but I preferred to keep things simple.<br><br>Of course, one could al=
so entirely replace CICV/COCV with generic full<br>introspection on inputs/=
output&#39;s program, plus opcodes for elliptic curve math<br>and tagged ha=
shes.<br><br><br>##########################<br>#=C2=A0 =C2=A0 PART 2: Vault=
s with MATT<br>##########################<br><br>In the rest of this post, =
I will document the first attempt at creating a vault<br>using the opcodes =
described.<br><br>While not an attempt at cloning exactly the functionality=
 of OP_VAULT [2],<br>it borrows heavily from the excellent work that was do=
ne there.<br><br>In particular, it also inherits the choice of using OP_CTV=
 as a primitive,<br>building on top of the bitcoin-inquisition&#39;s curren=
t branch that has already<br>merged OP_CTV. Reasonable vaults would be poss=
ible without CTV, but they<br>would be less efficient, particularly in the =
case of sending to many addresses<br>in a single unvaulting flow.<br><br>##=
# Distilling OP_VAULT<br><br>Abstracting from the implementation details, I=
 mentally model a vault as a<br>simple state machine with 2 states: [V] and=
 [U]:<br><br>[V]: the initial vault UTXO(s);<br>[U]: the utxo produced by t=
he &quot;trigger transaction&quot; during unvaulting.<br><br>On the typical=
 path: one or more [V] UTXOs are sent to the [U] state, and after<br>a time=
lock set on [U] expires, [U] is spent to one or several destinations.<br>Cr=
ucially, the destination outputs and amounts are already decided when [V] i=
s<br>spent into [U].<br><br>At any time before the funds are spent from [U]=
, they can always be spent by<br>sending them to some specified recovery pa=
th.<br><br>There are two key elements that are part of OP_VAULT&#39;s seman=
tics, and could be<br>generalized:<br><br>=E2=88=92 Forcing the script/amou=
nt of the next stepon<br>=E2=88=92 Storing some data for future Script&#39;=
s access (in the vault&#39;s case, a hash<br>=C2=A0 =C2=A0that commits to t=
he final withdrawal transaction).<br><br>CICV/COCV generalize both to arbit=
rary scripts (taptrees) and state machines,<br>and to dynamical and witness=
-dependent data embedded in the pubkey of a P2TR<br>output.<br><br>### Vaul=
t parameters<br><br>A contract that represents a vault has the following pa=
rameters (hardcoded in<br>the script when the vault is created):<br><br>- a=
lternate_pk: a key that can be used any time.<br>- spend_delay: the relativ=
e timelock before the withdrawal can be finalized;<br>- recover_pk: a pubke=
y for a P2TR output where funds can be sent at any time.<br><br>The alterna=
te_pk is a pubkey that can optionally be used as the key-path<br>spending c=
ondition for both states [V] and [U]. If such a spending condition is not<d=
iv>desired, it can be replaced with a NUMS point, making the key-path unspe=
ndable.<br><br>The spend_delay is the number of blocks that must be mined b=
efore the final<br>withdrawal transaction<br><br>In this example we also us=
e an unvault_pk needed to authorize the unvaulting<br>process (that is, spe=
nd [V] into [U]); this could be replaced with any miniscript<br>or other co=
nditions expressible in Script.<br><br>### P2TR structure for [V] (vault)<b=
r><br>internal key: alternate_pk<br><br>Script 1: &quot;trigger&quot;<br>=
=C2=A0 =C2=A0 =C2=A0 =C2=A0 # witness: &lt;out_i&gt; &lt;ctv-hash&gt;<br><f=
ont face=3D"monospace">{<br>=C2=A0 =C2=A0 &lt;alternate_pk&gt;,<br>=C2=A0 =
=C2=A0 &lt;merkle root of U&#39;s taptree&gt;,<br>=C2=A0 =C2=A0 2, OP_ROLL,=
<br>=C2=A0 =C2=A0 OP_CHECKOUTPUTCONTRACTVERIFY,<br><br>=C2=A0 =C2=A0 &lt;un=
vault_pk&gt;<br>=C2=A0 =C2=A0 OP_CHECKSIG<br>}</font><br><br>Script 2: &quo=
t;recover&quot;<br>=C2=A0 =C2=A0 =C2=A0 =C2=A0 # witness: &lt;out_i&gt;<br>=
<font face=3D"monospace">{<br>=C2=A0 =C2=A0 recover_pk,<br>=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<br>=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<br>=C2=A0 =C2=A0 OP_CHECKOUTPUTCONTRACTVERIFY,<br>=C2=A0 =
=C2=A0 OP_TRUE<br>}</font><br><br>The &quot;trigger&quot; script requires i=
n the witness an output index and the ctv-hash<br>that describes the withdr=
awal transaction.<br>COCV forces the output to contain the ctv-hash as embe=
dded data.<br>That&#39;s followed by the unvaulting condition =E2=88=92 in =
this example, a simple<br>signature check.<br><br>The &quot;recover&quot; s=
cript doesn&#39;t require any signature, and it simply forces<br>the output=
 specified in the witness to be a P2TR output with recover_pk as its<br>pub=
key.<br><br>(Omitting the &quot;recover&quot; script in [V] would reduce th=
e size of the witness by<br>32 bytes in the expected case, and might be pre=
ferred for some users)<br><br>### P2TR structure for [U] (unvaulting state)=
<br><br>internal key: alternate_pk (tweaked with ctv_hash)<br><br>Script 1:=
 &quot;withdrawal&quot;<br>=C2=A0 =C2=A0 =C2=A0 =C2=A0 # witness: &lt;ctv_h=
ash&gt;<br><font face=3D"monospace">{<br>=C2=A0 =C2=A0 OP_DUP,<br><br>=C2=
=A0 =C2=A0 # check that the top of the stack is the<br>=C2=A0 =C2=A0 # embe=
dded data in the current input<br>=C2=A0 =C2=A0 &lt;alternate_pk&gt;, OP_SW=
AP,<br>=C2=A0 =C2=A0 OP_CHECKINPUTCONTRACTVERIFY,<br><br>=C2=A0 =C2=A0 # Ch=
eck timelock<br>=C2=A0 =C2=A0 &lt;spend_delay&gt;,<br>=C2=A0 =C2=A0 OP_CHEC=
KSEQUENCEVERIFY,<br>=C2=A0 =C2=A0 OP_DROP,<br><br>=C2=A0 =C2=A0 # Check tha=
t the transaction output is as expected<br>=C2=A0 =C2=A0 OP_CHECKTEMPLATEVE=
RIFY<br>}</font><br><br>Script 2: &quot;recover&quot;<br>=C2=A0 =C2=A0 =C2=
=A0 =C2=A0 # witness: &lt;out_i&gt;<br><font face=3D"monospace">{<br>=C2=A0=
 =C2=A0 &lt;recover_pk&gt;,<br>=C2=A0 =C2=A0 OP_0,<br>=C2=A0 =C2=A0 OP_0,<b=
r>=C2=A0 =C2=A0 OP_CHECKOUTPUTCONTRACTVERIFY,<br>=C2=A0 =C2=A0 OP_TRUE<br>}=
</font><br><br>The &quot;withdrawal&quot; finalizes the transaction, by che=
cking that the timelock expired and</div><div>the outputs satisfy the CTV h=
ash that was committed to in the previous transaction.<br><br>The &quot;rec=
over&quot; script is identical as before.<br><br><br>### Differences with O=
P_VAULT vaults<br><br>Here I refer to the latest version of OP_VAULT at the=
 time of writing. [5]<br>It is not a thorough analysis.<br><br>Unlike the i=
mplementation based on OP_VAULT, the [V] utxos don&#39;t have an option<br>=
to add an additional output that is sent back to the same exact vault.<br>S=
upporting this use case seems to require a more general way of handling the=
<br>distribution of amounts than what I discussed in the section above: tha=
t would<br>in fact need to be generalized to the case of multiple<br>OP_CHE=
CKOUTPUTCONTRACTVERIFY opcodes executed for the same input.<br><br>By separ=
ating the ctv-hash (which is considered &quot;data&quot;) from the scripts =
in the<br>taptree, one entirely avoids the need to dynamically create taptr=
ees and<br>replace leaves in the covenant-encumbered UTXOs; in fact, the ta=
ptrees of [V]<br>and [U] are already set in stone when [V] utxos are create=
d, and only the<br>&quot;data&quot; portion of [U]&#39;s scriptPubKey is dy=
namically computed. In my opinion,<br>this makes it substantially easier to=
 program &quot;state machines&quot; that control the<br>behavior of coins, =
of which vaults are a special case.<br><br>I hope you&#39;ll find this inte=
resting, and look forward to your comments.</div><div><br></div><div>Salvat=
ore Ingala<br><br><br>[1] - <a href=3D"https://lists.linuxfoundation.org/pi=
permail/bitcoin-dev/2022-November/021223.html">https://lists.linuxfoundatio=
n.org/pipermail/bitcoin-dev/2022-November/021223.html</a><br>[2] - <a href=
=3D"https://github.com/bitcoin/bips/pull/1421">https://github.com/bitcoin/b=
ips/pull/1421</a><br>[3] - <a href=3D"https://github.com/bitcoin/bips/blob/=
master/bip-0341.mediawiki">https://github.com/bitcoin/bips/blob/master/bip-=
0341.mediawiki</a><br>[4] - <a href=3D"https://lists.linuxfoundation.org/pi=
permail/bitcoin-dev/2021-September/019420.html">https://lists.linuxfoundati=
on.org/pipermail/bitcoin-dev/2021-September/019420.html</a><br>[5] - <a hre=
f=3D"https://github.com/bitcoin/bips/blob/7112f308b356cdf0c51d917dbdc1b98e3=
0621f80/bip-0345.mediawiki">https://github.com/bitcoin/bips/blob/7112f308b3=
56cdf0c51d917dbdc1b98e30621f80/bip-0345.mediawiki</a><br></div></div></div>

--0000000000004de2e205fa1a2340--