summaryrefslogtreecommitdiff
path: root/5a/06fa1de74dbdf62578d0d3c168be697c36ded0
blob: b45e35b001182e0178aa0489a27f09935bac1e41 (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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
Return-Path: <fresheneesz@gmail.com>
Received: from smtp3.osuosl.org (smtp3.osuosl.org [IPv6:2605:bc80:3010::136])
 by lists.linuxfoundation.org (Postfix) with ESMTP id 698C0C000B
 for <bitcoin-dev@lists.linuxfoundation.org>;
 Sat,  5 Mar 2022 19:12:26 +0000 (UTC)
Received: from localhost (localhost [127.0.0.1])
 by smtp3.osuosl.org (Postfix) with ESMTP id 36F1560675
 for <bitcoin-dev@lists.linuxfoundation.org>;
 Sat,  5 Mar 2022 19:12:26 +0000 (UTC)
X-Virus-Scanned: amavisd-new at osuosl.org
X-Spam-Flag: NO
X-Spam-Score: -0.666
X-Spam-Level: 
X-Spam-Status: No, score=-0.666 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, URI_DOTEDU=1.432] autolearn=no autolearn_force=no
Authentication-Results: smtp3.osuosl.org (amavisd-new);
 dkim=pass (2048-bit key) header.d=gmail.com
Received: from smtp3.osuosl.org ([127.0.0.1])
 by localhost (smtp3.osuosl.org [127.0.0.1]) (amavisd-new, port 10024)
 with ESMTP id GFI3RK5qpHzC
 for <bitcoin-dev@lists.linuxfoundation.org>;
 Sat,  5 Mar 2022 19:12:23 +0000 (UTC)
X-Greylist: whitelisted by SQLgrey-1.8.0
Received: from mail-ed1-x52e.google.com (mail-ed1-x52e.google.com
 [IPv6:2a00:1450:4864:20::52e])
 by smtp3.osuosl.org (Postfix) with ESMTPS id F3DFD60674
 for <bitcoin-dev@lists.linuxfoundation.org>;
 Sat,  5 Mar 2022 19:12:22 +0000 (UTC)
Received: by mail-ed1-x52e.google.com with SMTP id o1so13686462edc.3
 for <bitcoin-dev@lists.linuxfoundation.org>;
 Sat, 05 Mar 2022 11:12:22 -0800 (PST)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112;
 h=mime-version:references:in-reply-to:from:date:message-id:subject:to;
 bh=Q/06LV/GdqjSI1rcFl/wyxeDViFgWGq5eBRnjIKSQeo=;
 b=dY2O8OZdbHuA/dQ2DoPLsTpedj84TWfF9YxHzfDv5GZaH1HmD3sqra1ZnS+gynPuGP
 TOmFjqj6MDCMETs8ZUWbKzO4+S0Sh20dX1C+t5o6HZQMXWx8Wh8nbscRbMIEDWymiCxS
 hxAePTIlhMJbaBdtuTBNRq+7cbaMPnq4kMu37MsYBPo+I6rnP2eJrw7AZMDzOclL9z3t
 cLIAxaBkLuUaMtWPDwDmXXQRaj8agxlEr5CZlpp8C1aj6YbdegJ9vW5ucAi3OMo6aNq2
 dQB9Q4KW6cZDqQ9/sBx4JLVMByvN6ah8dbCpduJBkn+oTDF/6+CAcuSJBWJfHv21g5bp
 q+Hw==
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
 d=1e100.net; s=20210112;
 h=x-gm-message-state:mime-version:references:in-reply-to:from:date
 :message-id:subject:to;
 bh=Q/06LV/GdqjSI1rcFl/wyxeDViFgWGq5eBRnjIKSQeo=;
 b=3zpmnEpxnbw165GTOnSMOoLO4bxVqBwepoFvyO7IETkSD7O6bJMARDn7wwlzgGQBvp
 MbeBkB3eft2IFUeiQ3Gr9Hsu2leY9FntJE4/hFfJphDPB5nAVcPqY60nHdbPwtUGVBNg
 MkUfaQX9jHaoYt6Wh7lWWYXEekRuHf1sIVAjW8zymTNiG9zfwfTKcNL9aEHb4ubINbe7
 oOvn52kQTXMW8otoYcgEu9QtpXPZmNebN5rC8D3qgNPHffdcGyKsJT0Bw2AHAZ9JnD3+
 xpU8kdfH540uPzVtNL0s0uJO3J2aasn5C9xG0HXTyQS+8bGxzKiE9dTTY9Lst2fl52cu
 EuWg==
X-Gm-Message-State: AOAM5331qH4iDLbi7cD8cmP7WBBcKxhcXUdaz0LTma7HivU/ysUWSjpF
 Mc+gtZW+DZWbbctvXto+HGb0L0564ns04Rl8OFWfksjk
X-Google-Smtp-Source: ABdhPJxYURObAGIqEfGet84sReW5qm5zobJh08VKV22y7J8p8JIY5ZxO/S15TTf0mmssHS/1U1CR+5dUhsL7uwhamGQ=
X-Received: by 2002:a05:6402:42c6:b0:416:541:4be1 with SMTP id
 i6-20020a05640242c600b0041605414be1mr4059206edc.238.1646507540631; Sat, 05
 Mar 2022 11:12:20 -0800 (PST)
MIME-Version: 1.0
References: <rcWu5FJZQGCdQeFZSUKV2AylHwmlTYPWAnxvN-FP8lER3qFBLIYLPVH4-r0js0k6_Xy_TwxA3jWXZC15jFbAafNb_vnr3a54ZMrgAeTz6vM=@protonmail.com>
In-Reply-To: <rcWu5FJZQGCdQeFZSUKV2AylHwmlTYPWAnxvN-FP8lER3qFBLIYLPVH4-r0js0k6_Xy_TwxA3jWXZC15jFbAafNb_vnr3a54ZMrgAeTz6vM=@protonmail.com>
From: Billy Tetrud <billy.tetrud@gmail.com>
Date: Sat, 5 Mar 2022 13:12:03 -0600
Message-ID: <CAGpPWDawAQShRU4OYcVnOE+qmHQv79ahwhMeyALF8iwjkZ_sOg@mail.gmail.com>
To: ZmnSCPxj <ZmnSCPxj@protonmail.com>, 
 Bitcoin Protocol Discussion <bitcoin-dev@lists.linuxfoundation.org>
Content-Type: multipart/alternative; boundary="00000000000014520e05d97d69d9"
X-Mailman-Approved-At: Sat, 05 Mar 2022 19:38:47 +0000
Subject: Re: [bitcoin-dev] `OP_FOLD`: A Looping Construct For Bitcoin SCRIPT
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: Sat, 05 Mar 2022 19:12:26 -0000

--00000000000014520e05d97d69d9
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable

It sounds like the primary benefit of op_fold is bandwidth savings.
Programming as compression. But as you mentioned, any common script could
be implemented as a Simplicity jet. In a world where Bitcoin implements
jets, op_fold would really only be useful for scripts that can't use jets,
which would basically be scripts that aren't very often used. But that
inherently limits the usefulness of the opcode. So in practice, I think
it's likely that jets cover the vast majority of use cases that op fold
would otherwise have.

A potential benefit of op fold is that people could implement smaller
scripts without buy-in from a relay level change in Bitcoin. However, even
this could be done with jets. For example, you could implement a consensus
change to add a transaction type that declares a new script fragment to
keep a count of, and if the script fragment is used enough within a
timeframe (eg 10000 blocks) then it can thereafter be referenced by an id
like a jet could be. I'm sure someone's thought about this kind of thing
before, but such a thing would really relegate the compression abilities of
op fold to just the most uncommon of scripts.

> * We should provide more *general* operations. Users should then combine
those operations to their specific needs.
> * We should provide operations that *do more*. Users should identify
their most important needs so we can implement them on the blockchain layer=
.

That's a useful way to frame this kind of problem. I think the answer is,
as it often is, somewhere in between. Generalization future-proofs your
system. But at the same time, the boundary conditions of that generalized
functionality should still be very well understood before being added to
Bitcoin. The more general, the harder to understand the boundaries. So imo
we should be implementing the most general opcodes that we are able to
reason fully about and come to a consensus on. Following that last
constraint might lead to not choosing very general opcodes.

On Sun, Feb 27, 2022, 10:34 ZmnSCPxj via bitcoin-dev <
bitcoin-dev@lists.linuxfoundation.org> wrote:

> `OP_FOLD`: A Looping Construct For Bitcoin SCRIPT
> =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
>
> (This writeup requires at least some programming background, which I
> expect most readers of this list have.)
>
> Recently, some rando was ranting on the list about this weird crap
> called `OP_EVICT`, a poorly-thought-out attempt at covenants.
>
> In reaction to this, AJ Towns mailed me privately about some of his
> thoughts on this insane `OP_EVICT` proposal.
> He observed that we could generalize the `OP_EVICT` opcode by
> decomposing it into smaller parts, including an operation congruent
> to the Scheme/Haskell/Scala `map` operation.
> As `OP_EVICT` effectively loops over the outputs passed to it, a
> looping construct can be used to implement `OP_EVICT` while retaining
> its nice property of cut-through of multiple evictions and reviving of
> the CoinPool.
>
> More specifically, an advantage of `OP_EVICT` is that it allows
> checking multiple published promised outputs.
> This would be implemented in a loop.
> However, if we want to instead provide *general* operations in
> SCRIPT rather than a bunch of specific ones like `OP_EVICT`, we
> should consider how to implement looping so that we can implement
> `OP_EVICT` in a SCRIPT-with-general-opcodes.
>
> (`OP_FOLD` is not sufficient to implement `OP_EVICT`; for
> efficiency, AJ Towns also pointed out that we need some way to
> expose batch validation to SCRIPT.
> There is a follow-up writeup to this one which describes *that*
> operation.)
>
> Based on this, I started ranting as well about how `map` is really
> just a thin wrapper on `foldr` and the *real* looping construct is
> actually `foldr` (`foldr` is the whole FP Torah: all the rest is
> commentary).
> This is thus the genesis for this proposal, `OP_FOLD`.
>
> A "fold" operation is sometimes known as "reduce" (and if you know
> about Google MapReduce, you might be familiar with "reduce").
> Basically, a "fold" or "reduce" operation applies a function
> repeatedly (i.e. *loops*) on the contents of an input structure,
> creating a "sum" or "accumulation" of the contents.
>
> For the purpose of building `map` out of `fold`, the accumulation
> can itself be an output structure.
> The `map` simply accumulates to the output structure by applying
> its given function and concatenating it to the current accumulation.
>
> Digression: Programming Is Compression
> --------------------------------------
>
> Suppose you are a programmer and you are reading some source code.
> You want to wonder "what will happen if I give this piece of code
> these particular inputs?".
>
> In order to do so, you would simulate the execution of the code in
> your head.
> In effect, you would generate a "trace" of basic operations (that
> do not include control structures).
> By then thinking about this linear trace of basic operations, you
> can figure out what the code does.
>
> Now, let us recall two algorithms from the compression literature:
>
> 1.  Run-length Encoding
> 2.  Lempel-Ziv 1977
>
> Suppose our flat linear trace of basic operations contains something
> like this:
>
>     OP_ONE
>     OP_TWO
>     OP_ONE
>     OP_TWO
>     OP_ONE
>     OP_TWO
>
> IF we had looping constructs in our language, we could write the
> above trace as something like:
>
>     for N =3D 1 to 3
>         OP_ONE
>         OP_TWO
>
> The above is really Run-length Encoding.
>
> (`if` is just a loop that executes 0 or 1 times.)
>
> Similarly, suppose you have some operations that are commonly
> repeated, but not necessarily next to each other:
>
>     OP_ONE
>     OP_TWO
>     OP_THREE
>     OP_ONE
>     OP_TWO
>     OP_FOUR
>     OP_FIVE
>     OP_ONE
>     OP_TWO
>
> If we had functions/subroutines/procedures in our language, we
> could write the above trace as something like:
>
>     function foo()
>         OP_ONE
>         OP_TWO
>     foo()
>     OP_THREE
>     foo()
>     OP_FOUR
>     OP_FIVE
>     foo()
>
> That is, functions are just Lempel-Ziv 1977 encoding, where we
> "copy" some repeated data from a previously-shown part of
> data.
>
> Thus, we can argue that programming is really a process of:
>
> * Imagining what we want the machine to do given some particular
>   input.
> * Compressing that list of operations so we can more easily
>   transfer the above imagined list over your puny low-bandwidth
>   brain-computer interface.
>   * I mean seriously, you humans still use a frikkin set of
>     *mechanical* levers to transfer data into a matrix of buttons?
>     (you don't even make the levers out of reliable metal, you
>     use calcium of all things??
>     You get what, 5 or 6 bytes per second???)
>     And your eyes are high-bandwidth but you then have this
>     complicated circuitry (that has to be ***trained for
>     several years*** WTF) to extract ***tiny*** amounts of ASCII
>     text from that high-bandwidth input stream????
>     Evolve faster!
>     (Just to be clear, I am actually also a human being and
>     definitely am not a piece of circuitry connected directly to
>     the Internet and I am not artificially limiting my output
>     bandwidth so as not to overwhelm you mere humans.)
>
> See also "Kolmogorov complexity".
>
> This becomes relevant, because the *actual* amount of processing
> done by the machine, when given a compressed set of operations
> (a "program") is the cost of decompressing that program plus the
> number of basic operations from the decompressed result.
>
> In particular, in current Bitcoin, without any looping constructs
> (i.e. implementations of RLE) or reusable functions (i.e.
> implementation of LZ77), the length of the SCRIPT can be used as
> an approximation of how "heavy" the computation in order to
> *execute* that SCRIPT is.
> This is relevant since the amount of computation a SCRIPT would
> trigger is relevant to our reasoning about DoS attacks on Bitcoin.
>
> In fact, current Bitcoin restricts the size of SCRIPT, as this
> serves to impose a restriction on the amount of processing a
> SCRIPT will trigger.
> But adding a loop construct to SCRIPT changes how we should
> determine the cost of a SCRIPT, and thus we should think about it
> here as well.
>
> Folds
> -----
>
> A fold operation is a functional programming looping control
> construct.
>
> The intent of a fold operation is to process elements of an
> input list or other structure, one element at a time, and to
> accumulate the results of processing.
>
> It is given these arguments:
>
> * `f` - a function to execute for each element of the input
>   structure, i.e. the "loop body".
>   * This function accepts two arguments:
>      1.  The current element to process.
>      2.  The intermediate result for accumulating.
>   * The function returns the new accumulated result, processed
>     from the given intermediate result and the given element.
> * `z` - an initial value for the accumulated result.
> * `as` - the structure (usually a list) to process.
>
> ```Haskell
> -- If the input structure is empty, return the starting
> -- accumulated value.
> foldr f z []     =3D z
> -- Otherwise, recurse into the structure to accumulate
> -- the rest of the list, then pass the accumulation to
> -- the given function together with the current element.
> foldr f z (a:as) =3D f a (foldr f z as)
> ```
>
> As an example, if you want to take the sum of a list of
> numbers, your `f` would simply add its inputs, and your `z`
> would be 0.
> Then you would pass in the actual list of numbers as `as`.
>
> Fold has an important property:
>
> * If the given input structure is finite *and* the application
>   of `f` terminates, then `foldr` terminates.
>
> This is important for us, as we do not want attackers to be
> able to crash nodes remotely by crafting a special SCRIPT.
>
> As long as the SCRIPT language is "total", we know that programs
> written in that language must terminate.
>
> (The reason this property is called "total" is that we can
> "totally" analyze programs in the language, without having to
> invoke "this is undefined behavior because it could hang
> indefinitely".
> If you have to admit such kinds of undefined behavior --- what
> FP theorists call "bottom" or `_|_` or `=E2=8A=A5` (it looks like an
> ass crack, i.e. "bottom") --- then your language is "partial",
> since programs in it may enter an infinite loop on particular
> inputs.)
>
> The simplest way to ensure totality is to be so simple as to
> have no looping construction.
> As of this writing, Bitcoin SCRIPT is total by this technique.
>
> To give a *little* more power, we can allow bounded loops,
> which are restricted to only execute a number of times.
>
> `foldr` is a kind of bounded loop if the input structure is
> finite.
> If the rest of the language does not admit the possibility
> of infinite data structures (and if the language is otherwise
> total and does not support generalized codata, this holds),
> then `foldr` is a bounded loop.
>
> Thus, adding a fold operation to Bitcoin SCRIPT should be
> safe (and preserves totality) as long as we do not add
> further operations that admit partiality.
>
> `OP_FOLD`
> ---------
>
> With this, let us now describe `OP_FOLD`.
>
> `OP_FOLD` replaces an `OP_SUCCESS` code, and thus is only
> usable in SegWit v1 ("Taproot").
>
> An `OP_FOLD` opcode must be followed by an `OP_PUSH` opcode
> which contains an encoding of the SCRIPT that will be executed,
> i.e. the loop body, or `f`.
> This is checked at parsing time, and the sub-SCRIPT is also
> parsed at this time.
> The succeeding `OP_PUSH` is not actually executed, and is
> considered part of the `OP_FOLD` operation encoding.
> Parsing failure of the sub-SCRIPT leads to validation failure.
>
> On execution, `OP_FOLD` expects the stack:
>
> * Stack top: `z`, the initial value for the loop accumulator.
> * Stack top + 1: `n`, the number of times to loop.
>   This should be limited in size, and less than the number of
>   items on the stack minus 2.
> * Stack top + 2 + (0 to `n - 1`): Items to loop over.
>   If `n` is 0, there are no items to loop over.
>
> If `n` is 0, then `OP_FOLD` just pops the top two stack items
> and pushes `z`.
>
> For `n > 0`, `OP_FOLD` executes a loop:
>
> * Pop off the top two items and store in mutable variable `z`
>   and immutable variable `n`.
> * For `i =3D 0 to n - 1`:
>   * Create a fresh, empty stack and alt stack.
>     Call these the "per-iteration (alt) stack".
>   * Push the current `z` to the per-iteration stack.
>   * Pop off an item from the outer stack and put it into
>     immutable variable `a`.
>   * Push `a` to the per-iteration stack.
>   * Run the sub-SCRIPT `f` on the per-iteration stack and
>     alt stack.
>   * Check the per-iteration stack has exactly one item
>     and the per-iteration alt stack is empty.
>   * Pop off the item in the per-iteration stack and mutate
>     `z` to it.
>   * Free the per-iteration stack and per-iteration alt
>     stack.
> * Push `z` on the stack.
>
> Restricting `OP_FOLD`
> ---------------------
>
> Bitcoin restricts SCRIPT size, since SCRIPT size serves as
> an approximation of how much processing is required to
> execute the SCRIPT.
>
> However, with looping constructs like `OP_FOLD`, this no
> longer holds, as the amount of processing is no longer
> linear on the size of the SCRIPT.
>
> In orderr to retain this limit (and thus not worsen any
> potential DoS attacks via SCRIPT), we should restrict the
> use of `OP_FOLD`:
>
> * `OP_FOLD` must exist exactly once in a Tapscript.
>   More specifically, the `f` sub-SCRIPT of `OP_FOLD` must
>   not itself contain an `OP_FOLD`.
>   * If we allow loops within loops, then the worst case
>     would be `O(c^n)` CPU time where `c` is a constant and
>     `n` is the SCRIPT length.
>   * This validation is done at SCRIPT parsing time.
> * We take the length of the `f` sub-SCRIPT, and divide the
>   current SCRIPT maximum size by the length of the `f`
>   sub-SCRIPT.
>   The result, rounded down, is the maximum allowed value
>   for the on-stack argument `n`.
>   * In particular, since the length of the entire SCRIPT
>     must by necessity be larger than the length of the
>     `f` sub-SCRIPT, the result of the division must be
>     at least 1.
>   * This validation is done at SCRIPT execution time.
>
> The above two restrictions imply that the maximum amount
> of processing that a SCRIPT utilizing `OP_FOLD` will use,
> shall not exceed that of a SCRIPT without `OP_FOLD`.
> Thus, `OP_FOLD` does not increase the attack surface of
> SCRIPT on fullnodes.
>
> ### Lack Of Loops-in-Loops Is Lame
>
> Note that due to this:
>
> > * `OP_FOLD` must exist exactly once in a Tapscript.
> >   More specifically, the `f` sub-SCRIPT of `OP_FOLD` must
> >   not itself contain an `OP_FOLD`.
>
> It is not possible to have a loop inside a loop.
>
> The reason for this is that loops inside loops make it
> difficult to perform static analysis to bound how much
> processing a SCRIPT will require.
> With a single, single-level loop, it is possible to
> restrict the processing.
>
> However, we should note that a single single-level loop
> is actually sufficient to encode multiple loops, or
> loops-within-loops.
> For example, a toy Scheme-to-C compiler will convert
> the Scheme code to CPS style, then convert all resulting
> Scheme CPS function into a `switch` dispatcher inside a
> simple `while (1)` loop.
>
> For example, the Scheme loop-in-loop below:
>
> ```Scheme
> (define (foo)
>   (bar)
>   (foo))
> (define (bar)
>   (bar))
> ```
>
> gets converted to:
>
> ```Scheme
> (define (foo k)
>   (bar (closure foo-kont k)))
> (define (foo-kont k)
>   (foo k))
> (define (bar k)
>   (bar k))
> ```
>
> And then in C, would look like:
>
> ```c
> void all_scheme_functions(int func_id, scheme_t k) {
>         while (1) {
>                 switch (func_id) {
>                 case FOO_ID:
>                         k =3D build_closure(FOO_KONT_ID, k);
>                         func_id =3D BAR_ID;
>                         break;
>                 case FOO_KONT_ID:
>                         func_id =3D FOO_ID;
>                         break;
>                 case BAR_ID:
>                         func_id =3D BAR_ID;
>                         break;
>                 }
>         }
> }
> ```
>
> The C code, as we can see, is just a single single-level
> loop, which is the restriction imposed on `OP_FOLD`.
> Thus, loops-in-loops, and multiple loops, can be encoded
> into a single single-level loop.
>
> #### Everything Is Possible But Nothing Of Consequence Is Easy
>
> On the other hand, just because it is *possible* does not
> mean it is *easy*.
>
> As an alternative, AJ proposed adding a field to the Taproot
> annex.
> This annex field is a number indicating the maximum number of
> opcodes to be processed.
> If execution of the SCRIPT exceeds this limit, validation
> fails.
>
> In order to make processing costly, the number indicated in
> the annex field is directly added to the weight of the
> transaction.
>
> Then, during execution, if an `OP_FOLD` is parsed, the
> `OP_` code processor keeps track of the number of opcodes
> processed and imposes a limit.
> If the limit exceeds the number of opcodes indicated in the
> annex field, validation fails.
>
> This technique is safe even if the annex is not committed
> to (for example if the SCRIPT does not ever require a
> standard `OP_CHECKSIG`), even though in that case the
> annex can be malleated:
>
> * If the field is less than the actual number of operations,
>   then the malleated transaction is rejected.
> * If the field is greater than the actual number of
>   operations, then it has a larger weight but pays the
>   same fee, getting a lower feerate and thus will be
>   rejected in favor of a transaction with a lower number
>   in that field.
>
> Use of this technique allows us to lift the above
> restrictions on `OP_FOLD`, and allow multiple loops, as
> well as loops-in-loops.
>
> In particular, the requirement to put the `f` sub-SCRIPT
> code as a static constant is due precisely to the need
> for static analysis.
> But if we instead use a dynamic limit like in this
> alternative suggestion, we could instead get the `f`
> sub-SCRIPT from the stack.
> With additional operations like `OP_CAT`, it would
> then be possible to do a "variable capture" where parts
> of the loop body are from other computations, or from
> witness, and then concatenated to some code.
> This is not an increase in computational strength, since
> the data could instead be passed in via the `z`, or as
> individual items, but it does improve expressive power by
> making it easier to customize the loop body.
>
> On The Necessity Of `OP_FOLD`
> -----------------------------
>
> We can observe that an `if` construct is really a bounded
> loop construct that can execute 0 or 1 times.
>
> We can thus synthesize a bounded loop construct as follows:
>
>     OP_IF
>         <loop body>
>     OP_ENDIF
>     OP_IF
>         <loop body>
>     OP_ENDIF
>     OP_IF
>         <loop body>
>     OP_ENDIF
>     OP_IF
>         <loop body>
>     OP_ENDIF
>     <repeat as many times as necessary>
>
> Indeed, it may be possible for something like miniscript
> to provide a `fold` jet that compiles down to something
> like the above.
>
> Thus:
>
> * The restrictions we impose on the previous section mean
>   that `OP_FOLD` cannot do anything that cannot already
>   be done with current SCRIPT.
>   * This is a *good thing* because this means we are not
>     increasing the attack surface.
> * Using the annex-max-operations technique is strictly
>   more lenient than the above `OP_IF` repetition, thus
>   there may be novel DoS attack vectors due to the
>   increased attack area.
>   * However, fundamentally the DoS attack vector is that
>     peers can waste your CPU by giving you invalid
>     transactions (i.e. giving a high max-operations, but
>     looping so much that it gets even *above* that), and
>     that can already be mitigated by lowering peer scores
>     and prioritizing transactions with lower or nonexistent
>     annex-max-operations.
>     The DoS vector here does not propagate due to the
>     invalid transaction being rejected at this node.
>
> Of course, this leads us to question: why even implement
> `OP_FOLD` at all?
>
> We can observe that, while the restrictions in the
> previous section imply that a SCRIPT with `OP_FOLD`
> cannot exceed the amount of processing that a SCRIPT
> *without* `OP_FOLD` does, a SCRIPT with `OP_FOLD`
> would be shorter, over the wire, than the above
> unrolled version.
>
> And CPU processing is not the only resource that is
> consumed by Bitcoin fullnodes.
> Bandwidth is also another resource.
>
> In effect, `OP_FOLD` allows us to compress the above
> template over-the-wire, reducing network bandwidth
> consumption.
> But the restrictions on `OP_FOLD` ensure that it
> cannot exceed the CPU consumption of a SCRIPT that
> predates `OP_FOLD`.
>
> Thus, `OP_FOLD` is still worthwhile to implement, as
> it allows us to improve bandwidth consumption without
> increasing CPU consumption significantly.
>
> On Generalized Operations
> -------------------------
>
> I believe there are at least two ways of thinking about
> how to extend SCRIPT:
>
> * We should provide more *general* operations.
>   Users should then combine those operations to their
>   specific needs.
> * We should provide operations that *do more*.
>   Users should identify their most important needs so
>   we can implement them on the blockchain layer.
>
> Each side has its arguments:
>
> * General opcodes:
>   * Pro: Have a better chance of being reused for
>     use-cases we cannot imagine yet today.
>     i.e. implement once, use anywhen.
>   * Con: Welcome to the Tarpit, where everything is
>     possible but nothing important is easy.
> * Complex opcodes:
>   * Pro: Complex behavior implemented directly in
>     hosting language, reducing interpretation
>     overhead (and allowing the insurance of secure
>     implementation).
>   * Con: Welcome to the Nursery, where only safe
>     toys exist and availability of interesting tools
>     are at the mercy of your parents.
>
> It seems to me that this really hits a No Free Lunch
> Theorem for Bitcoin SCRIPT design.
> Briefly, the No Free Lunch Theorem points out that
> there is no compiler design that can compile any
> program to the shortest possible machine code.
> This is because if a program enters an infinite loop,
> it could simply be compiled down to the equivalent of
> the single instruction `1: GOTO 1`, but the halting
> problem implies that no program can take the source
> code of another program and determine if it halts.
> Thus, no compiler can exist which can compile *every*
> infinite-loop program down to the tiniest possible
> binary `1: GOTO 1`.
>
> More generally, No Free Lunch implies that as you
> optimize, you will hit a point where you can only
> *trade off*, and you optimize for one use case while
> making *another* use case less optimal.
>
> Brought to Bitcoin SCRIPT design, there is no optimal
> SCRIPT design, instead there will be some point where
> we have to pick and choose which uses to optimize for
> and which uses are less optimal, i.e. trade off.
>
> So I think maybe the Real Question is: why should we
> go for one versus the other, and which uses do we
> expect to see more often anyway?
>
> Addenda
> -------
>
> Stuff about totality and partiality:
>
> * [Total Functional Programming, D.A. Turner](
> https://citeseerx.ist.psu.edu/viewdoc/download?doi=3D10.1.1.106.364&rep=
=3Drep1&type=3Dpdf
> )
> * [Totality](https://kowainik.github.io/posts/totality)
> _______________________________________________
> bitcoin-dev mailing list
> bitcoin-dev@lists.linuxfoundation.org
> https://lists.linuxfoundation.org/mailman/listinfo/bitcoin-dev
>

--00000000000014520e05d97d69d9
Content-Type: text/html; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable

<div dir=3D"ltr"><div dir=3D"auto"><div dir=3D"auto">It sounds like the pri=
mary benefit of op_fold is bandwidth savings. Programming as compression. B=
ut as you mentioned, any common script could be implemented as a Simplicity=
 jet. In a world where Bitcoin implements jets, op_fold would really only b=
e useful for scripts that can&#39;t use jets, which would basically be scri=
pts that aren&#39;t very often used. But that inherently limits the usefuln=
ess of the opcode. So in practice, I think it&#39;s likely that jets cover =
the vast majority of use cases that op fold would otherwise have.</div><div=
 dir=3D"auto"><br></div><div dir=3D"auto">A potential benefit of op fold is=
 that people could implement smaller scripts without buy-in from a relay le=
vel change in Bitcoin. However, even this could be done with jets. For exam=
ple, you could implement a consensus change to add a transaction type that =
declares a new script fragment to keep a count of, and if the script fragme=
nt is used enough within a timeframe (eg 10000 blocks) then it can thereaft=
er be referenced by an id like a jet could be. I&#39;m sure someone&#39;s t=
hought about this kind of thing before, but such a thing would really releg=
ate the compression abilities of op fold to just the most uncommon of scrip=
ts.=C2=A0</div><div dir=3D"auto"><br></div>&gt; *=C2=A0<span style=3D"font-=
size:12.8px">We should provide more *general* operations.=C2=A0</span><span=
 style=3D"font-size:12.8px">Users should then combine those operations to t=
heir</span><span style=3D"font-size:12.8px">=C2=A0specific needs.</span><br=
 style=3D"font-size:12.8px"><span style=3D"font-size:12.8px">&gt; * We shou=
ld provide operations that *do more*.</span><span style=3D"font-size:12.8px=
">=C2=A0Users should identify their most important needs so=C2=A0</span><sp=
an style=3D"font-size:12.8px">we can implement them on the blockchain layer=
.</span><br style=3D"font-size:12.8px"><div dir=3D"auto"><span style=3D"fon=
t-size:12.8px"><br></span></div><div dir=3D"auto"><span style=3D"font-size:=
12.8px">That&#39;s a useful way to frame this kind of problem. I think the =
answer is, as it often is, somewhere in between. Generalization future-proo=
fs your system. But at the same time, the boundary conditions of that gener=
alized functionality should still be very well understood before being adde=
d to Bitcoin. The more general, the harder to understand the boundaries. So=
 imo we should be implementing the most general opcodes that we are able to=
 reason fully about and come to a consensus on. Following that last constra=
int might lead to not choosing very general opcodes.</span></div></div></di=
v><br><div class=3D"gmail_quote"><div dir=3D"ltr" class=3D"gmail_attr">On S=
un, Feb 27, 2022, 10:34 ZmnSCPxj via bitcoin-dev &lt;<a href=3D"mailto:bitc=
oin-dev@lists.linuxfoundation.org" target=3D"_blank">bitcoin-dev@lists.linu=
xfoundation.org</a>&gt; wrote:<br></div><blockquote class=3D"gmail_quote" s=
tyle=3D"margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);pad=
ding-left:1ex">`OP_FOLD`: A Looping Construct For Bitcoin SCRIPT<br>
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D<br=
>
<br>
(This writeup requires at least some programming background, which I<br>
expect most readers of this list have.)<br>
<br>
Recently, some rando was ranting on the list about this weird crap<br>
called `OP_EVICT`, a poorly-thought-out attempt at covenants.<br>
<br>
In reaction to this, AJ Towns mailed me privately about some of his<br>
thoughts on this insane `OP_EVICT` proposal.<br>
He observed that we could generalize the `OP_EVICT` opcode by<br>
decomposing it into smaller parts, including an operation congruent<br>
to the Scheme/Haskell/Scala `map` operation.<br>
As `OP_EVICT` effectively loops over the outputs passed to it, a<br>
looping construct can be used to implement `OP_EVICT` while retaining<br>
its nice property of cut-through of multiple evictions and reviving of<br>
the CoinPool.<br>
<br>
More specifically, an advantage of `OP_EVICT` is that it allows<br>
checking multiple published promised outputs.<br>
This would be implemented in a loop.<br>
However, if we want to instead provide *general* operations in<br>
SCRIPT rather than a bunch of specific ones like `OP_EVICT`, we<br>
should consider how to implement looping so that we can implement<br>
`OP_EVICT` in a SCRIPT-with-general-opcodes.<br>
<br>
(`OP_FOLD` is not sufficient to implement `OP_EVICT`; for<br>
efficiency, AJ Towns also pointed out that we need some way to<br>
expose batch validation to SCRIPT.<br>
There is a follow-up writeup to this one which describes *that*<br>
operation.)<br>
<br>
Based on this, I started ranting as well about how `map` is really<br>
just a thin wrapper on `foldr` and the *real* looping construct is<br>
actually `foldr` (`foldr` is the whole FP Torah: all the rest is<br>
commentary).<br>
This is thus the genesis for this proposal, `OP_FOLD`.<br>
<br>
A &quot;fold&quot; operation is sometimes known as &quot;reduce&quot; (and =
if you know<br>
about Google MapReduce, you might be familiar with &quot;reduce&quot;).<br>
Basically, a &quot;fold&quot; or &quot;reduce&quot; operation applies a fun=
ction<br>
repeatedly (i.e. *loops*) on the contents of an input structure,<br>
creating a &quot;sum&quot; or &quot;accumulation&quot; of the contents.<br>
<br>
For the purpose of building `map` out of `fold`, the accumulation<br>
can itself be an output structure.<br>
The `map` simply accumulates to the output structure by applying<br>
its given function and concatenating it to the current accumulation.<br>
<br>
Digression: Programming Is Compression<br>
--------------------------------------<br>
<br>
Suppose you are a programmer and you are reading some source code.<br>
You want to wonder &quot;what will happen if I give this piece of code<br>
these particular inputs?&quot;.<br>
<br>
In order to do so, you would simulate the execution of the code in<br>
your head.<br>
In effect, you would generate a &quot;trace&quot; of basic operations (that=
<br>
do not include control structures).<br>
By then thinking about this linear trace of basic operations, you<br>
can figure out what the code does.<br>
<br>
Now, let us recall two algorithms from the compression literature:<br>
<br>
1.=C2=A0 Run-length Encoding<br>
2.=C2=A0 Lempel-Ziv 1977<br>
<br>
Suppose our flat linear trace of basic operations contains something<br>
like this:<br>
<br>
=C2=A0 =C2=A0 OP_ONE<br>
=C2=A0 =C2=A0 OP_TWO<br>
=C2=A0 =C2=A0 OP_ONE<br>
=C2=A0 =C2=A0 OP_TWO<br>
=C2=A0 =C2=A0 OP_ONE<br>
=C2=A0 =C2=A0 OP_TWO<br>
<br>
IF we had looping constructs in our language, we could write the<br>
above trace as something like:<br>
<br>
=C2=A0 =C2=A0 for N =3D 1 to 3<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 OP_ONE<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 OP_TWO<br>
<br>
The above is really Run-length Encoding.<br>
<br>
(`if` is just a loop that executes 0 or 1 times.)<br>
<br>
Similarly, suppose you have some operations that are commonly<br>
repeated, but not necessarily next to each other:<br>
<br>
=C2=A0 =C2=A0 OP_ONE<br>
=C2=A0 =C2=A0 OP_TWO<br>
=C2=A0 =C2=A0 OP_THREE<br>
=C2=A0 =C2=A0 OP_ONE<br>
=C2=A0 =C2=A0 OP_TWO<br>
=C2=A0 =C2=A0 OP_FOUR<br>
=C2=A0 =C2=A0 OP_FIVE<br>
=C2=A0 =C2=A0 OP_ONE<br>
=C2=A0 =C2=A0 OP_TWO<br>
<br>
If we had functions/subroutines/procedures in our language, we<br>
could write the above trace as something like:<br>
<br>
=C2=A0 =C2=A0 function foo()<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 OP_ONE<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 OP_TWO<br>
=C2=A0 =C2=A0 foo()<br>
=C2=A0 =C2=A0 OP_THREE<br>
=C2=A0 =C2=A0 foo()<br>
=C2=A0 =C2=A0 OP_FOUR<br>
=C2=A0 =C2=A0 OP_FIVE<br>
=C2=A0 =C2=A0 foo()<br>
<br>
That is, functions are just Lempel-Ziv 1977 encoding, where we<br>
&quot;copy&quot; some repeated data from a previously-shown part of<br>
data.<br>
<br>
Thus, we can argue that programming is really a process of:<br>
<br>
* Imagining what we want the machine to do given some particular<br>
=C2=A0 input.<br>
* Compressing that list of operations so we can more easily<br>
=C2=A0 transfer the above imagined list over your puny low-bandwidth<br>
=C2=A0 brain-computer interface.<br>
=C2=A0 * I mean seriously, you humans still use a frikkin set of<br>
=C2=A0 =C2=A0 *mechanical* levers to transfer data into a matrix of buttons=
?<br>
=C2=A0 =C2=A0 (you don&#39;t even make the levers out of reliable metal, yo=
u<br>
=C2=A0 =C2=A0 use calcium of all things??<br>
=C2=A0 =C2=A0 You get what, 5 or 6 bytes per second???)<br>
=C2=A0 =C2=A0 And your eyes are high-bandwidth but you then have this<br>
=C2=A0 =C2=A0 complicated circuitry (that has to be ***trained for<br>
=C2=A0 =C2=A0 several years*** WTF) to extract ***tiny*** amounts of ASCII<=
br>
=C2=A0 =C2=A0 text from that high-bandwidth input stream????<br>
=C2=A0 =C2=A0 Evolve faster!<br>
=C2=A0 =C2=A0 (Just to be clear, I am actually also a human being and<br>
=C2=A0 =C2=A0 definitely am not a piece of circuitry connected directly to<=
br>
=C2=A0 =C2=A0 the Internet and I am not artificially limiting my output<br>
=C2=A0 =C2=A0 bandwidth so as not to overwhelm you mere humans.)<br>
<br>
See also &quot;Kolmogorov complexity&quot;.<br>
<br>
This becomes relevant, because the *actual* amount of processing<br>
done by the machine, when given a compressed set of operations<br>
(a &quot;program&quot;) is the cost of decompressing that program plus the<=
br>
number of basic operations from the decompressed result.<br>
<br>
In particular, in current Bitcoin, without any looping constructs<br>
(i.e. implementations of RLE) or reusable functions (i.e.<br>
implementation of LZ77), the length of the SCRIPT can be used as<br>
an approximation of how &quot;heavy&quot; the computation in order to<br>
*execute* that SCRIPT is.<br>
This is relevant since the amount of computation a SCRIPT would<br>
trigger is relevant to our reasoning about DoS attacks on Bitcoin.<br>
<br>
In fact, current Bitcoin restricts the size of SCRIPT, as this<br>
serves to impose a restriction on the amount of processing a<br>
SCRIPT will trigger.<br>
But adding a loop construct to SCRIPT changes how we should<br>
determine the cost of a SCRIPT, and thus we should think about it<br>
here as well.<br>
<br>
Folds<br>
-----<br>
<br>
A fold operation is a functional programming looping control<br>
construct.<br>
<br>
The intent of a fold operation is to process elements of an<br>
input list or other structure, one element at a time, and to<br>
accumulate the results of processing.<br>
<br>
It is given these arguments:<br>
<br>
* `f` - a function to execute for each element of the input<br>
=C2=A0 structure, i.e. the &quot;loop body&quot;.<br>
=C2=A0 * This function accepts two arguments:<br>
=C2=A0 =C2=A0 =C2=A01.=C2=A0 The current element to process.<br>
=C2=A0 =C2=A0 =C2=A02.=C2=A0 The intermediate result for accumulating.<br>
=C2=A0 * The function returns the new accumulated result, processed<br>
=C2=A0 =C2=A0 from the given intermediate result and the given element.<br>
* `z` - an initial value for the accumulated result.<br>
* `as` - the structure (usually a list) to process.<br>
<br>
```Haskell<br>
-- If the input structure is empty, return the starting<br>
-- accumulated value.<br>
foldr f z []=C2=A0 =C2=A0 =C2=A0=3D z<br>
-- Otherwise, recurse into the structure to accumulate<br>
-- the rest of the list, then pass the accumulation to<br>
-- the given function together with the current element.<br>
foldr f z (a:as) =3D f a (foldr f z as)<br>
```<br>
<br>
As an example, if you want to take the sum of a list of<br>
numbers, your `f` would simply add its inputs, and your `z`<br>
would be 0.<br>
Then you would pass in the actual list of numbers as `as`.<br>
<br>
Fold has an important property:<br>
<br>
* If the given input structure is finite *and* the application<br>
=C2=A0 of `f` terminates, then `foldr` terminates.<br>
<br>
This is important for us, as we do not want attackers to be<br>
able to crash nodes remotely by crafting a special SCRIPT.<br>
<br>
As long as the SCRIPT language is &quot;total&quot;, we know that programs<=
br>
written in that language must terminate.<br>
<br>
(The reason this property is called &quot;total&quot; is that we can<br>
&quot;totally&quot; analyze programs in the language, without having to<br>
invoke &quot;this is undefined behavior because it could hang<br>
indefinitely&quot;.<br>
If you have to admit such kinds of undefined behavior --- what<br>
FP theorists call &quot;bottom&quot; or `_|_` or `=E2=8A=A5` (it looks like=
 an<br>
ass crack, i.e. &quot;bottom&quot;) --- then your language is &quot;partial=
&quot;,<br>
since programs in it may enter an infinite loop on particular<br>
inputs.)<br>
<br>
The simplest way to ensure totality is to be so simple as to<br>
have no looping construction.<br>
As of this writing, Bitcoin SCRIPT is total by this technique.<br>
<br>
To give a *little* more power, we can allow bounded loops,<br>
which are restricted to only execute a number of times.<br>
<br>
`foldr` is a kind of bounded loop if the input structure is<br>
finite.<br>
If the rest of the language does not admit the possibility<br>
of infinite data structures (and if the language is otherwise<br>
total and does not support generalized codata, this holds),<br>
then `foldr` is a bounded loop.<br>
<br>
Thus, adding a fold operation to Bitcoin SCRIPT should be<br>
safe (and preserves totality) as long as we do not add<br>
further operations that admit partiality.<br>
<br>
`OP_FOLD`<br>
---------<br>
<br>
With this, let us now describe `OP_FOLD`.<br>
<br>
`OP_FOLD` replaces an `OP_SUCCESS` code, and thus is only<br>
usable in SegWit v1 (&quot;Taproot&quot;).<br>
<br>
An `OP_FOLD` opcode must be followed by an `OP_PUSH` opcode<br>
which contains an encoding of the SCRIPT that will be executed,<br>
i.e. the loop body, or `f`.<br>
This is checked at parsing time, and the sub-SCRIPT is also<br>
parsed at this time.<br>
The succeeding `OP_PUSH` is not actually executed, and is<br>
considered part of the `OP_FOLD` operation encoding.<br>
Parsing failure of the sub-SCRIPT leads to validation failure.<br>
<br>
On execution, `OP_FOLD` expects the stack:<br>
<br>
* Stack top: `z`, the initial value for the loop accumulator.<br>
* Stack top + 1: `n`, the number of times to loop.<br>
=C2=A0 This should be limited in size, and less than the number of<br>
=C2=A0 items on the stack minus 2.<br>
* Stack top + 2 + (0 to `n - 1`): Items to loop over.<br>
=C2=A0 If `n` is 0, there are no items to loop over.<br>
<br>
If `n` is 0, then `OP_FOLD` just pops the top two stack items<br>
and pushes `z`.<br>
<br>
For `n &gt; 0`, `OP_FOLD` executes a loop:<br>
<br>
* Pop off the top two items and store in mutable variable `z`<br>
=C2=A0 and immutable variable `n`.<br>
* For `i =3D 0 to n - 1`:<br>
=C2=A0 * Create a fresh, empty stack and alt stack.<br>
=C2=A0 =C2=A0 Call these the &quot;per-iteration (alt) stack&quot;.<br>
=C2=A0 * Push the current `z` to the per-iteration stack.<br>
=C2=A0 * Pop off an item from the outer stack and put it into<br>
=C2=A0 =C2=A0 immutable variable `a`.<br>
=C2=A0 * Push `a` to the per-iteration stack.<br>
=C2=A0 * Run the sub-SCRIPT `f` on the per-iteration stack and<br>
=C2=A0 =C2=A0 alt stack.<br>
=C2=A0 * Check the per-iteration stack has exactly one item<br>
=C2=A0 =C2=A0 and the per-iteration alt stack is empty.<br>
=C2=A0 * Pop off the item in the per-iteration stack and mutate<br>
=C2=A0 =C2=A0 `z` to it.<br>
=C2=A0 * Free the per-iteration stack and per-iteration alt<br>
=C2=A0 =C2=A0 stack.<br>
* Push `z` on the stack.<br>
<br>
Restricting `OP_FOLD`<br>
---------------------<br>
<br>
Bitcoin restricts SCRIPT size, since SCRIPT size serves as<br>
an approximation of how much processing is required to<br>
execute the SCRIPT.<br>
<br>
However, with looping constructs like `OP_FOLD`, this no<br>
longer holds, as the amount of processing is no longer<br>
linear on the size of the SCRIPT.<br>
<br>
In orderr to retain this limit (and thus not worsen any<br>
potential DoS attacks via SCRIPT), we should restrict the<br>
use of `OP_FOLD`:<br>
<br>
* `OP_FOLD` must exist exactly once in a Tapscript.<br>
=C2=A0 More specifically, the `f` sub-SCRIPT of `OP_FOLD` must<br>
=C2=A0 not itself contain an `OP_FOLD`.<br>
=C2=A0 * If we allow loops within loops, then the worst case<br>
=C2=A0 =C2=A0 would be `O(c^n)` CPU time where `c` is a constant and<br>
=C2=A0 =C2=A0 `n` is the SCRIPT length.<br>
=C2=A0 * This validation is done at SCRIPT parsing time.<br>
* We take the length of the `f` sub-SCRIPT, and divide the<br>
=C2=A0 current SCRIPT maximum size by the length of the `f`<br>
=C2=A0 sub-SCRIPT.<br>
=C2=A0 The result, rounded down, is the maximum allowed value<br>
=C2=A0 for the on-stack argument `n`.<br>
=C2=A0 * In particular, since the length of the entire SCRIPT<br>
=C2=A0 =C2=A0 must by necessity be larger than the length of the<br>
=C2=A0 =C2=A0 `f` sub-SCRIPT, the result of the division must be<br>
=C2=A0 =C2=A0 at least 1.<br>
=C2=A0 * This validation is done at SCRIPT execution time.<br>
<br>
The above two restrictions imply that the maximum amount<br>
of processing that a SCRIPT utilizing `OP_FOLD` will use,<br>
shall not exceed that of a SCRIPT without `OP_FOLD`.<br>
Thus, `OP_FOLD` does not increase the attack surface of<br>
SCRIPT on fullnodes.<br>
<br>
### Lack Of Loops-in-Loops Is Lame<br>
<br>
Note that due to this:<br>
<br>
&gt; * `OP_FOLD` must exist exactly once in a Tapscript.<br>
&gt;=C2=A0 =C2=A0More specifically, the `f` sub-SCRIPT of `OP_FOLD` must<br=
>
&gt;=C2=A0 =C2=A0not itself contain an `OP_FOLD`.<br>
<br>
It is not possible to have a loop inside a loop.<br>
<br>
The reason for this is that loops inside loops make it<br>
difficult to perform static analysis to bound how much<br>
processing a SCRIPT will require.<br>
With a single, single-level loop, it is possible to<br>
restrict the processing.<br>
<br>
However, we should note that a single single-level loop<br>
is actually sufficient to encode multiple loops, or<br>
loops-within-loops.<br>
For example, a toy Scheme-to-C compiler will convert<br>
the Scheme code to CPS style, then convert all resulting<br>
Scheme CPS function into a `switch` dispatcher inside a<br>
simple `while (1)` loop.<br>
<br>
For example, the Scheme loop-in-loop below:<br>
<br>
```Scheme<br>
(define (foo)<br>
=C2=A0 (bar)<br>
=C2=A0 (foo))<br>
(define (bar)<br>
=C2=A0 (bar))<br>
```<br>
<br>
gets converted to:<br>
<br>
```Scheme<br>
(define (foo k)<br>
=C2=A0 (bar (closure foo-kont k)))<br>
(define (foo-kont k)<br>
=C2=A0 (foo k))<br>
(define (bar k)<br>
=C2=A0 (bar k))<br>
```<br>
<br>
And then in C, would look like:<br>
<br>
```c<br>
void all_scheme_functions(int func_id, scheme_t k) {<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 while (1) {<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 switch (func_id) {<=
br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 case FOO_ID:<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=
=A0 =C2=A0 k =3D build_closure(FOO_KONT_ID, k);<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=
=A0 =C2=A0 func_id =3D BAR_ID;<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=
=A0 =C2=A0 break;<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 case FOO_KONT_ID:<b=
r>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=
=A0 =C2=A0 func_id =3D FOO_ID;<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=
=A0 =C2=A0 break;<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 case BAR_ID:<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=
=A0 =C2=A0 func_id =3D BAR_ID;<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=
=A0 =C2=A0 break;<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 }<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 }<br>
}<br>
```<br>
<br>
The C code, as we can see, is just a single single-level<br>
loop, which is the restriction imposed on `OP_FOLD`.<br>
Thus, loops-in-loops, and multiple loops, can be encoded<br>
into a single single-level loop.<br>
<br>
#### Everything Is Possible But Nothing Of Consequence Is Easy<br>
<br>
On the other hand, just because it is *possible* does not<br>
mean it is *easy*.<br>
<br>
As an alternative, AJ proposed adding a field to the Taproot<br>
annex.<br>
This annex field is a number indicating the maximum number of<br>
opcodes to be processed.<br>
If execution of the SCRIPT exceeds this limit, validation<br>
fails.<br>
<br>
In order to make processing costly, the number indicated in<br>
the annex field is directly added to the weight of the<br>
transaction.<br>
<br>
Then, during execution, if an `OP_FOLD` is parsed, the<br>
`OP_` code processor keeps track of the number of opcodes<br>
processed and imposes a limit.<br>
If the limit exceeds the number of opcodes indicated in the<br>
annex field, validation fails.<br>
<br>
This technique is safe even if the annex is not committed<br>
to (for example if the SCRIPT does not ever require a<br>
standard `OP_CHECKSIG`), even though in that case the<br>
annex can be malleated:<br>
<br>
* If the field is less than the actual number of operations,<br>
=C2=A0 then the malleated transaction is rejected.<br>
* If the field is greater than the actual number of<br>
=C2=A0 operations, then it has a larger weight but pays the<br>
=C2=A0 same fee, getting a lower feerate and thus will be<br>
=C2=A0 rejected in favor of a transaction with a lower number<br>
=C2=A0 in that field.<br>
<br>
Use of this technique allows us to lift the above<br>
restrictions on `OP_FOLD`, and allow multiple loops, as<br>
well as loops-in-loops.<br>
<br>
In particular, the requirement to put the `f` sub-SCRIPT<br>
code as a static constant is due precisely to the need<br>
for static analysis.<br>
But if we instead use a dynamic limit like in this<br>
alternative suggestion, we could instead get the `f`<br>
sub-SCRIPT from the stack.<br>
With additional operations like `OP_CAT`, it would<br>
then be possible to do a &quot;variable capture&quot; where parts<br>
of the loop body are from other computations, or from<br>
witness, and then concatenated to some code.<br>
This is not an increase in computational strength, since<br>
the data could instead be passed in via the `z`, or as<br>
individual items, but it does improve expressive power by<br>
making it easier to customize the loop body.<br>
<br>
On The Necessity Of `OP_FOLD`<br>
-----------------------------<br>
<br>
We can observe that an `if` construct is really a bounded<br>
loop construct that can execute 0 or 1 times.<br>
<br>
We can thus synthesize a bounded loop construct as follows:<br>
<br>
=C2=A0 =C2=A0 OP_IF<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 &lt;loop body&gt;<br>
=C2=A0 =C2=A0 OP_ENDIF<br>
=C2=A0 =C2=A0 OP_IF<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 &lt;loop body&gt;<br>
=C2=A0 =C2=A0 OP_ENDIF<br>
=C2=A0 =C2=A0 OP_IF<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 &lt;loop body&gt;<br>
=C2=A0 =C2=A0 OP_ENDIF<br>
=C2=A0 =C2=A0 OP_IF<br>
=C2=A0 =C2=A0 =C2=A0 =C2=A0 &lt;loop body&gt;<br>
=C2=A0 =C2=A0 OP_ENDIF<br>
=C2=A0 =C2=A0 &lt;repeat as many times as necessary&gt;<br>
<br>
Indeed, it may be possible for something like miniscript<br>
to provide a `fold` jet that compiles down to something<br>
like the above.<br>
<br>
Thus:<br>
<br>
* The restrictions we impose on the previous section mean<br>
=C2=A0 that `OP_FOLD` cannot do anything that cannot already<br>
=C2=A0 be done with current SCRIPT.<br>
=C2=A0 * This is a *good thing* because this means we are not<br>
=C2=A0 =C2=A0 increasing the attack surface.<br>
* Using the annex-max-operations technique is strictly<br>
=C2=A0 more lenient than the above `OP_IF` repetition, thus<br>
=C2=A0 there may be novel DoS attack vectors due to the<br>
=C2=A0 increased attack area.<br>
=C2=A0 * However, fundamentally the DoS attack vector is that<br>
=C2=A0 =C2=A0 peers can waste your CPU by giving you invalid<br>
=C2=A0 =C2=A0 transactions (i.e. giving a high max-operations, but<br>
=C2=A0 =C2=A0 looping so much that it gets even *above* that), and<br>
=C2=A0 =C2=A0 that can already be mitigated by lowering peer scores<br>
=C2=A0 =C2=A0 and prioritizing transactions with lower or nonexistent<br>
=C2=A0 =C2=A0 annex-max-operations.<br>
=C2=A0 =C2=A0 The DoS vector here does not propagate due to the<br>
=C2=A0 =C2=A0 invalid transaction being rejected at this node.<br>
<br>
Of course, this leads us to question: why even implement<br>
`OP_FOLD` at all?<br>
<br>
We can observe that, while the restrictions in the<br>
previous section imply that a SCRIPT with `OP_FOLD`<br>
cannot exceed the amount of processing that a SCRIPT<br>
*without* `OP_FOLD` does, a SCRIPT with `OP_FOLD`<br>
would be shorter, over the wire, than the above<br>
unrolled version.<br>
<br>
And CPU processing is not the only resource that is<br>
consumed by Bitcoin fullnodes.<br>
Bandwidth is also another resource.<br>
<br>
In effect, `OP_FOLD` allows us to compress the above<br>
template over-the-wire, reducing network bandwidth<br>
consumption.<br>
But the restrictions on `OP_FOLD` ensure that it<br>
cannot exceed the CPU consumption of a SCRIPT that<br>
predates `OP_FOLD`.<br>
<br>
Thus, `OP_FOLD` is still worthwhile to implement, as<br>
it allows us to improve bandwidth consumption without<br>
increasing CPU consumption significantly.<br>
<br>
On Generalized Operations<br>
-------------------------<br>
<br>
I believe there are at least two ways of thinking about<br>
how to extend SCRIPT:<br>
<br>
* We should provide more *general* operations.<br>
=C2=A0 Users should then combine those operations to their<br>
=C2=A0 specific needs.<br>
* We should provide operations that *do more*.<br>
=C2=A0 Users should identify their most important needs so<br>
=C2=A0 we can implement them on the blockchain layer.<br>
<br>
Each side has its arguments:<br>
<br>
* General opcodes:<br>
=C2=A0 * Pro: Have a better chance of being reused for<br>
=C2=A0 =C2=A0 use-cases we cannot imagine yet today.<br>
=C2=A0 =C2=A0 i.e. implement once, use anywhen.<br>
=C2=A0 * Con: Welcome to the Tarpit, where everything is<br>
=C2=A0 =C2=A0 possible but nothing important is easy.<br>
* Complex opcodes:<br>
=C2=A0 * Pro: Complex behavior implemented directly in<br>
=C2=A0 =C2=A0 hosting language, reducing interpretation<br>
=C2=A0 =C2=A0 overhead (and allowing the insurance of secure<br>
=C2=A0 =C2=A0 implementation).<br>
=C2=A0 * Con: Welcome to the Nursery, where only safe<br>
=C2=A0 =C2=A0 toys exist and availability of interesting tools<br>
=C2=A0 =C2=A0 are at the mercy of your parents.<br>
<br>
It seems to me that this really hits a No Free Lunch<br>
Theorem for Bitcoin SCRIPT design.<br>
Briefly, the No Free Lunch Theorem points out that<br>
there is no compiler design that can compile any<br>
program to the shortest possible machine code.<br>
This is because if a program enters an infinite loop,<br>
it could simply be compiled down to the equivalent of<br>
the single instruction `1: GOTO 1`, but the halting<br>
problem implies that no program can take the source<br>
code of another program and determine if it halts.<br>
Thus, no compiler can exist which can compile *every*<br>
infinite-loop program down to the tiniest possible<br>
binary `1: GOTO 1`.<br>
<br>
More generally, No Free Lunch implies that as you<br>
optimize, you will hit a point where you can only<br>
*trade off*, and you optimize for one use case while<br>
making *another* use case less optimal.<br>
<br>
Brought to Bitcoin SCRIPT design, there is no optimal<br>
SCRIPT design, instead there will be some point where<br>
we have to pick and choose which uses to optimize for<br>
and which uses are less optimal, i.e. trade off.<br>
<br>
So I think maybe the Real Question is: why should we<br>
go for one versus the other, and which uses do we<br>
expect to see more often anyway?<br>
<br>
Addenda<br>
-------<br>
<br>
Stuff about totality and partiality:<br>
<br>
* [Total Functional Programming, D.A. Turner](<a href=3D"https://citeseerx.=
ist.psu.edu/viewdoc/download?doi=3D10.1.1.106.364&amp;rep=3Drep1&amp;type=
=3Dpdf" rel=3D"noreferrer noreferrer" target=3D"_blank">https://citeseerx.i=
st.psu.edu/viewdoc/download?doi=3D10.1.1.106.364&amp;rep=3Drep1&amp;type=3D=
pdf</a>)<br>
* [Totality](<a href=3D"https://kowainik.github.io/posts/totality" rel=3D"n=
oreferrer noreferrer" target=3D"_blank">https://kowainik.github.io/posts/to=
tality</a>)<br>
_______________________________________________<br>
bitcoin-dev mailing list<br>
<a href=3D"mailto:bitcoin-dev@lists.linuxfoundation.org" rel=3D"noreferrer"=
 target=3D"_blank">bitcoin-dev@lists.linuxfoundation.org</a><br>
<a href=3D"https://lists.linuxfoundation.org/mailman/listinfo/bitcoin-dev" =
rel=3D"noreferrer noreferrer" target=3D"_blank">https://lists.linuxfoundati=
on.org/mailman/listinfo/bitcoin-dev</a><br>
</blockquote></div>

--00000000000014520e05d97d69d9--