Source file cryptobox.ml
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
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
open Error_monad
include Cryptobox_intf
module Base58 = Tezos_crypto.Base58
module Srs_g1 = Octez_bls12_381_polynomial.Srs.Srs_g1
module Srs_g2 = Octez_bls12_381_polynomial.Srs.Srs_g2
type error += Failed_to_load_trusted_setup of string
let () =
register_error_kind
`Permanent
~id:"dal.node.trusted_setup_loading_failed"
~title:"Trusted setup loading failed"
~description:"Trusted setup failed to load"
~pp:(fun ppf msg ->
Format.fprintf ppf "Trusted setup failed to load: %s" msg)
Data_encoding.(obj1 (req "msg" string))
(function
| Failed_to_load_trusted_setup parameter -> Some parameter | _ -> None)
(fun parameter -> Failed_to_load_trusted_setup parameter)
[@@coverage off]
type initialisation_parameters = {srs_g1 : Srs_g1.t; srs_g2 : Srs_g2.t}
let initialisation_parameters = ref None
type error += Dal_initialisation_twice
let () =
register_error_kind
`Permanent
~id:"dal.node.initialisation_twice"
~title:"Initialisation_twice"
~description:"DAL parameters were initialised twice"
~pp:(fun ppf () ->
Format.fprintf ppf "DAL parameters were initialised twice")
Data_encoding.empty
(function Dal_initialisation_twice -> Some () | _ -> None)
(function () -> Dal_initialisation_twice)
[@@coverage off]
let load_parameters parameters =
let open Result_syntax in
match !initialisation_parameters with
| None ->
initialisation_parameters := Some parameters ;
return_unit
| Some _ -> fail [Dal_initialisation_twice]
let initialisation_parameters_from_files ~srs_g1_path ~srs_g2_path
~srs_size_log2 =
let open Lwt_result_syntax in
let len = 1 lsl srs_size_log2 in
let to_bigstring ~path =
let open Lwt_syntax in
let* fd = Lwt_unix.openfile path [Unix.O_RDONLY] 0o440 in
Lwt.finalize
(fun () ->
return
(match
Lwt_bytes.map_file
~fd:(Lwt_unix.unix_file_descr fd)
~shared:false
()
with
| exception Unix.Unix_error (error_code, function_name, _) ->
Error
[
Failed_to_load_trusted_setup
(Format.sprintf
"%s: Unix.Unix_error: %s"
function_name
(Unix.error_message error_code));
]
| exception e ->
Error [Failed_to_load_trusted_setup (Printexc.to_string e)]
| res -> Ok res))
(fun () -> Lwt_unix.close fd)
in
let* srs_g1_bigstring = to_bigstring ~path:srs_g1_path in
let* srs_g2_bigstring = to_bigstring ~path:srs_g2_path in
match
let open Result_syntax in
let* srs_g1 = Srs_g1.of_bigstring srs_g1_bigstring ~len in
let* srs_g2 = Srs_g2.of_bigstring srs_g2_bigstring ~len in
return (srs_g1, srs_g2)
with
| Error (`End_of_file s) ->
tzfail (Failed_to_load_trusted_setup ("EOF: " ^ s))
| Error (`Invalid_point p) ->
tzfail
(Failed_to_load_trusted_setup (Printf.sprintf "Invalid point %i" p))
| Ok (srs_g1, srs_g2) -> return {srs_g1; srs_g2}
type srs = {
raw : initialisation_parameters;
kate_amortized_srs_g2_shards : Bls12_381.G2.t;
kate_amortized_srs_g2_pages : Bls12_381.G2.t;
}
module Inner = struct
module Scalar = Bls12_381.Fr
module Polynomials = Octez_bls12_381_polynomial.Polynomial
module G1_array = Octez_bls12_381_polynomial.G1_carray
module Evaluations = Octez_bls12_381_polynomial.Evaluations
module Domains = Octez_bls12_381_polynomial.Domain
type slot = bytes
type scalar = Scalar.t
type polynomial = Polynomials.t
type commitment = Bls12_381.G1.t
type shard_proof = Bls12_381.G1.t
type commitment_proof = Bls12_381.G1.t
type page_proof = Bls12_381.G1.t
type page = bytes
type share = Scalar.t array
type shard = {index : int; share : share}
type shards_proofs_precomputation = scalar array * shard_proof array array
type ('a, 'b) error_container = {given : 'a; expected : 'b}
module Encoding = struct
open Data_encoding
let fr_encoding =
conv
Bls12_381.Fr.to_bytes
Bls12_381.Fr.of_bytes_exn
(Fixed.bytes Bls12_381.Fr.size_in_bytes)
let g1_encoding =
conv
Bls12_381.G1.to_compressed_bytes
Bls12_381.G1.of_compressed_bytes_exn
bytes
let page_proof_encoding = g1_encoding
let share_encoding = array fr_encoding
let shard_proof_encoding = g1_encoding
let shard_encoding =
conv
(fun {index; share} -> (index, share))
(fun (index, share) -> {index; share})
(tup2 int31 share_encoding)
[@@coverage off]
let shards_proofs_precomputation_encoding =
tup2 (array fr_encoding) (array (array g1_encoding))
let error_container_encoding (given_encoding : 'a encoding)
(expected_encoding : 'b encoding) : ('a, 'b) error_container encoding =
conv
(fun {given; expected} -> (given, expected))
(fun (given, expected) -> {given; expected})
(obj2 (req "given" given_encoding) (req "expected" expected_encoding))
end
include Encoding
module Commitment = struct
type t = commitment
type Base58.data += Data of t
let zero = Bls12_381.G1.zero
let equal = Bls12_381.G1.eq
let commitment_to_bytes = Bls12_381.G1.to_compressed_bytes
let commitment_of_bytes_opt = Bls12_381.G1.of_compressed_bytes_opt
[@@coverage off]
let commitment_of_bytes_exn bytes =
match Bls12_381.G1.of_compressed_bytes_opt bytes with
| None ->
Format.kasprintf Stdlib.failwith "Unexpected data (DAL commitment)"
| Some commitment -> commitment
[@@coverage off]
let commitment_size = Bls12_381.G1.compressed_size_in_bytes [@@coverage off]
let to_string commitment = commitment_to_bytes commitment |> Bytes.to_string
[@@coverage off]
let of_string_opt str = commitment_of_bytes_opt (String.to_bytes str)
[@@coverage off]
let b58check_encoding =
Base58.register_encoding
~prefix:Base58.Prefix.slot_header
~length:commitment_size
~to_raw:to_string
~of_raw:of_string_opt
~wrap:(fun x -> Data x)
[@@coverage off]
let raw_encoding =
let open Data_encoding in
conv
commitment_to_bytes
commitment_of_bytes_exn
(Fixed.bytes commitment_size)
[@@coverage off]
let compare_commitments a b =
if Bls12_381.G1.eq a b then 0
else Bytes.compare (Bls12_381.G1.to_bytes a) (Bls12_381.G1.to_bytes b)
let compare = compare_commitments
include Tezos_crypto.Helpers.Make (struct
type t = commitment
let name = "DAL_commitment"
let title = "Commitment representation for the DAL"
let b58check_encoding = b58check_encoding
let raw_encoding = raw_encoding
let compare = compare_commitments
let equal = Bls12_381.G1.eq
let hash _ =
assert false
[@@coverage off]
let seeded_hash _ _ =
assert false
[@@coverage off]
end)
let of_b58check = of_b58check
end
module Commitment_proof = struct
let zero = Bls12_381.G1.zero
let to_bytes = Bls12_381.G1.to_compressed_bytes
let of_bytes_exn bytes =
match Bls12_381.G1.of_compressed_bytes_opt bytes with
| None ->
Format.kasprintf
Stdlib.failwith
"Unexpected data (DAL commitment proof)"
| Some proof -> proof
[@@coverage off]
let size = Bls12_381.G1.compressed_size_in_bytes
let raw_encoding =
let open Data_encoding in
conv to_bytes of_bytes_exn (Fixed.bytes size)
let encoding = raw_encoding
end
type error += Invalid_precomputation_hash of (string, string) error_container
let () =
register_error_kind
`Permanent
~id:"dal.node.invalid_precomputation_hash"
~title:"Invalid_precomputation_hash"
~description:"Unexpected precomputation hash"
~pp:(fun ppf {given; expected} ->
Format.fprintf
ppf
"Invalid precomputation hash: expected %s. Got %s"
expected
given)
(Encoding.error_container_encoding
Data_encoding.string
Data_encoding.string)
(function Invalid_precomputation_hash err -> Some err | _ -> None)
(function err -> Invalid_precomputation_hash err)
[@@coverage off]
let scalar_bytes_amount = Scalar.size_in_bytes - 1
let make_domain n = Domains.build n
type t = {
redundancy_factor : int;
slot_size : int;
page_size : int;
number_of_shards : int;
max_polynomial_length : int;
erasure_encoded_polynomial_length : int;
domain_polynomial_length : Domains.t;
domain_2_times_polynomial_length : Domains.t;
domain_erasure_encoded_polynomial_length : Domains.t;
shard_length : int;
pages_per_slot : int;
page_length : int;
page_length_domain : int;
remaining_bytes : int;
srs : srs;
}
let is_power_of_two n =
assert (n >= 0) ;
n <> 0 && n land (n - 1) = 0
let combinations_factors =
let rec powerset = function
| [] -> [[]]
| x :: xs ->
let ps = powerset xs in
List.concat [ps; List.map (fun ss -> x :: ss) ps]
in
powerset [3; 11; 19]
let select_fft_domain (domain_size : int) : int * int * int =
assert (domain_size > 0) ;
let order_multiplicative_group = Z.pred Scalar.order in
assert (
List.for_all
(fun x -> Z.(divisible order_multiplicative_group (of_int x)))
[3; 11; 19]) ;
if domain_size = 1 then (2, 2, 1)
else
let domain_from_factors (factors : int list) : int * int list =
let prod_factors = List.fold_left ( * ) 1 factors in
let rec get_next_power_of_two k =
if prod_factors lsl k >= domain_size then 1 lsl k
else get_next_power_of_two (k + 1)
in
let next_power_of_two = get_next_power_of_two 0 in
let size = prod_factors * next_power_of_two in
(size, next_power_of_two :: factors)
in
let candidate_domains =
List.map domain_from_factors combinations_factors
in
let domain_length, prime_factor_decomposition =
List.fold_left
min
(List.hd candidate_domains)
(List.tl candidate_domains)
in
let power_of_two = List.hd prime_factor_decomposition in
let remainder_product =
List.fold_left ( * ) 1 (List.tl prime_factor_decomposition)
in
(domain_length, power_of_two, remainder_product)
let fft_aux ~dft ~fft ~fft_pfa size coefficients =
let _domain_length, power_of_two, remainder_product =
select_fft_domain size
in
if size = power_of_two || size = remainder_product then
let domain = Domains.build size in
(if is_power_of_two size then fft else dft) domain coefficients
else
let domain1 = Domains.build power_of_two in
let domain2 = Domains.build remainder_product in
fft_pfa ~domain1 ~domain2 coefficients
let fft =
fft_aux
~dft:Evaluations.dft
~fft:Evaluations.evaluation_fft
~fft_pfa:Evaluations.evaluation_fft_prime_factor_algorithm
let ifft_inplace =
fft_aux
~dft:Evaluations.idft
~fft:Evaluations.interpolation_fft
~fft_pfa:Evaluations.interpolation_fft_prime_factor_algorithm
let page_length ~page_size = Int.div page_size scalar_bytes_amount + 1
let slot_as_polynomial_length ~slot_size ~page_size =
let page_length = page_length ~page_size in
let page_length_domain, _, _ = select_fft_domain page_length in
slot_size / page_size * page_length_domain
let ensure_validity ~slot_size ~page_size ~erasure_encoded_polynomial_length
~max_polynomial_length ~redundancy_factor ~number_of_shards ~shard_length
~srs_g1_length ~srs_g2_length =
let open Result_syntax in
let assert_result condition error_message =
if not condition then fail (`Fail (error_message ())) else return_unit
in
let* () =
assert_result
(is_power_of_two slot_size)
(fun () ->
Format.asprintf
"Slot size is expected to be a power of 2. Given: %d"
slot_size)
in
let* () =
assert_result
(is_power_of_two page_size)
(fun () ->
Format.asprintf
"Page size is expected to be a power of 2. Given: %d"
page_size)
in
let* () =
assert_result
(is_power_of_two redundancy_factor && redundancy_factor >= 2)
(fun () ->
Format.asprintf
"Redundancy factor is expected to be a power of 2 and greater than \
2. Given: %d"
redundancy_factor)
in
let* () =
assert_result
(page_size >= 32 && page_size < slot_size)
(fun () ->
Format.asprintf
"Page size is expected to be greater than '32' and strictly less \
than the slot_size '%d'. Got: %d"
slot_size
page_size)
in
let max_two_adicity_log = 32 in
let two_adicity_log =
snd Z.(remove (of_int erasure_encoded_polynomial_length) (of_int 2))
in
let* () =
assert_result
(two_adicity_log <= max_two_adicity_log)
(fun () ->
Format.asprintf
"Slot size (%d) and/or redundancy factor (%d) is/are too high: \
expected 2-adicity of erasure_encoded_polynomial_length (%d) to \
be at most 2^%d, got: 2^%d"
slot_size
redundancy_factor
erasure_encoded_polynomial_length
max_two_adicity_log
two_adicity_log)
in
let* () =
assert_result
(erasure_encoded_polynomial_length mod number_of_shards == 0
&& number_of_shards < erasure_encoded_polynomial_length)
(fun () ->
Format.asprintf
"The number of shards must divide, and not be equal to %d. For the \
given parameter, the maximum number of shards is %d. Got: %d."
erasure_encoded_polynomial_length
(erasure_encoded_polynomial_length / 2)
number_of_shards)
in
let* () =
assert_result
(shard_length < max_polynomial_length)
(fun () ->
Format.asprintf
"For the given parameters, the minimum number of shards is %d. Got \
%d."
(redundancy_factor * 2)
number_of_shards)
in
let* () =
assert_result
(max_polynomial_length <= srs_g1_length)
(fun () ->
Format.asprintf
"SRS on G1 size is too small. Expected more than %d. Got %d"
max_polynomial_length
srs_g1_length)
in
assert_result
(let shard_length =
erasure_encoded_polynomial_length / number_of_shards
in
let srs_g2_expected_length =
max max_polynomial_length shard_length + 1
in
srs_g2_expected_length <= srs_g2_length)
(fun () ->
Format.asprintf
"SRS on G2 size is too small. Expected more than %d. Got %d"
max_polynomial_length
srs_g2_length)
type parameters = Dal_config.parameters = {
redundancy_factor : int;
page_size : int;
slot_size : int;
number_of_shards : int;
}
let parameters_encoding = Dal_config.parameters_encoding
let pages_per_slot {slot_size; page_size; _} = slot_size / page_size
let make
({redundancy_factor; slot_size; page_size; number_of_shards} as
parameters) =
let open Result_syntax in
let max_polynomial_length =
slot_as_polynomial_length ~slot_size ~page_size
in
let erasure_encoded_polynomial_length =
redundancy_factor * max_polynomial_length
in
let shard_length = erasure_encoded_polynomial_length / number_of_shards in
let* raw =
match !initialisation_parameters with
| None -> fail (`Fail "Dal_cryptobox.make: DAL was not initialised.")
| Some srs -> return srs
in
let* () =
ensure_validity
~slot_size
~page_size
~erasure_encoded_polynomial_length
~max_polynomial_length
~redundancy_factor
~number_of_shards
~shard_length
~srs_g1_length:(Srs_g1.size raw.srs_g1)
~srs_g2_length:(Srs_g2.size raw.srs_g2)
in
let page_length = page_length ~page_size in
let page_length_domain, _, _ = select_fft_domain page_length in
let srs =
{
raw;
kate_amortized_srs_g2_shards = Srs_g2.get raw.srs_g2 shard_length;
kate_amortized_srs_g2_pages = Srs_g2.get raw.srs_g2 page_length_domain;
}
in
return
{
redundancy_factor;
slot_size;
page_size;
number_of_shards;
max_polynomial_length;
erasure_encoded_polynomial_length;
domain_polynomial_length = make_domain max_polynomial_length;
domain_2_times_polynomial_length =
make_domain (2 * max_polynomial_length);
domain_erasure_encoded_polynomial_length =
make_domain erasure_encoded_polynomial_length;
shard_length;
pages_per_slot = pages_per_slot parameters;
page_length;
page_length_domain;
remaining_bytes = page_size mod scalar_bytes_amount;
srs;
}
let parameters
({redundancy_factor; slot_size; page_size; number_of_shards; _} : t) =
{redundancy_factor; slot_size; page_size; number_of_shards}
[@@coverage off]
let polynomial_degree = Polynomials.degree
let polynomial_evaluate = Polynomials.evaluate
let polynomials_product d ps =
let evaluations = List.map (fft d) ps in
ifft_inplace d (Evaluations.mul_c ~evaluations ())
let polynomial_from_slot (t : t) slot =
if Bytes.length slot <> t.slot_size then
Error
(`Slot_wrong_size
(Printf.sprintf "message must be %d bytes long" t.slot_size))
else
let offset = ref 0 in
let coefficients =
Array.init t.max_polynomial_length (fun _ -> Scalar.(copy zero))
in
for page = 0 to t.pages_per_slot - 1 do
for elt = 0 to t.page_length - 2 do
if !offset >= t.slot_size then ()
else
let dst = Bytes.create scalar_bytes_amount in
Bytes.blit slot !offset dst 0 scalar_bytes_amount ;
offset := !offset + scalar_bytes_amount ;
coefficients.((elt * t.pages_per_slot) + page) <-
Scalar.of_bytes_exn dst
done ;
let dst = Bytes.create t.remaining_bytes in
Bytes.blit slot !offset dst 0 t.remaining_bytes ;
offset := !offset + t.remaining_bytes ;
coefficients.(((t.page_length - 1) * t.pages_per_slot) + page) <-
Scalar.of_bytes_exn dst
done ;
Ok
(ifft_inplace
t.max_polynomial_length
(Evaluations.of_array (t.max_polynomial_length - 1, coefficients)))
let polynomial_to_slot t p =
let evaluations = fft t.max_polynomial_length p in
let slot = Bytes.make t.slot_size '\x00' in
let offset = ref 0 in
for page = 0 to t.pages_per_slot - 1 do
for elt = 0 to t.page_length - 2 do
let idx = (elt * t.pages_per_slot) + page in
let coeff = Scalar.to_bytes (Evaluations.get evaluations idx) in
Bytes.blit coeff 0 slot !offset scalar_bytes_amount ;
offset := !offset + scalar_bytes_amount
done ;
let idx = ((t.page_length - 1) * t.pages_per_slot) + page in
let coeff = Scalar.to_bytes (Evaluations.get evaluations idx) in
Bytes.blit coeff 0 slot !offset t.remaining_bytes ;
offset := !offset + t.remaining_bytes
done ;
slot
let encode t p =
Evaluations.to_array (fft t.erasure_encoded_polynomial_length p)
let shards_from_polynomial t p =
let codeword = encode t p in
let rec loop index seq =
if index < 0 then seq
else
let share = Array.init t.shard_length (fun _ -> Scalar.(copy zero)) in
for j = 0 to t.shard_length - 1 do
share.(j) <- codeword.((t.number_of_shards * j) + index)
done ;
loop (index - 1) (Seq.cons {index; share} seq)
in
loop (t.number_of_shards - 1) Seq.empty
module ShardSet = Set.Make (struct
type t = shard
let compare a b = Int.compare a.index b.index
end)
let encoded_share_size t =
let share_scalar_len =
t.erasure_encoded_polynomial_length / t.number_of_shards
in
(share_scalar_len * Scalar.size_in_bytes) + 4
let polynomial_from_shards t shards =
let shards =
Seq.take (t.max_polynomial_length / t.shard_length) shards
|> ShardSet.of_seq
in
if t.max_polynomial_length / t.shard_length > ShardSet.cardinal shards then
Error
(`Not_enough_shards
(Printf.sprintf
"there must be at least %d shards to decode"
(t.max_polynomial_length / t.shard_length)))
else if
ShardSet.exists
(fun {share; _} -> Array.length share <> t.shard_length)
shards
then
Error
(`Invalid_shard_length
(Printf.sprintf
"At least one shard of invalid length: expected length %d."
t.shard_length))
else if
ShardSet.exists
(fun {index; _} -> index >= t.number_of_shards || index < 0)
shards
then
Error
(`Shard_index_out_of_range
(Printf.sprintf
"At least one shard index out of range: expected indices within \
the range [%d, %d]."
0
(t.number_of_shards - 1)))
else
let mul acc i =
Polynomials.mul_xn
acc
t.shard_length
(Scalar.negate
(Domains.get
t.domain_erasure_encoded_polynomial_length
(i * t.shard_length)))
in
let partition_products seq =
ShardSet.fold
(fun {index; _} (l, r) -> (mul r index, l))
seq
(Polynomials.one, Polynomials.one)
in
let p1, p2 = partition_products shards in
assert (
Polynomials.degree p1 + Polynomials.degree p2 = t.max_polynomial_length) ;
let a_poly = polynomials_product (2 * t.max_polynomial_length) [p1; p2] in
assert (Polynomials.degree a_poly = t.max_polynomial_length) ;
let a' = Polynomials.derivative a_poly in
let eval_a' = fft t.erasure_encoded_polynomial_length a' in
let compute_n t eval_a' shards =
let n_poly =
Array.init t.erasure_encoded_polynomial_length (fun _ ->
Scalar.(copy zero))
in
ShardSet.iter
(fun {index; share} ->
for j = 0 to Array.length share - 1 do
let c_i = share.(j) in
let i = (t.number_of_shards * j) + index in
let x_i =
Domains.get t.domain_erasure_encoded_polynomial_length i
in
let tmp = Evaluations.get eval_a' i in
Scalar.mul_inplace tmp tmp x_i ;
Scalar.inverse_exn_inplace tmp tmp ;
Scalar.mul_inplace tmp tmp c_i ;
n_poly.(i) <- tmp
done)
shards ;
Evaluations.of_array (t.erasure_encoded_polynomial_length - 1, n_poly)
in
let n_poly = compute_n t eval_a' shards in
let b =
Polynomials.truncate
~len:t.max_polynomial_length
(ifft_inplace t.erasure_encoded_polynomial_length n_poly)
in
Polynomials.mul_by_scalar_inplace
b
Scalar.(negate (of_int t.erasure_encoded_polynomial_length))
b ;
let p = polynomials_product (2 * t.max_polynomial_length) [a_poly; b] in
Ok (Polynomials.truncate ~len:t.max_polynomial_length p)
let commit t p =
let degree = Polynomials.degree p in
let srs_g1_size = Srs_g1.size t.srs.raw.srs_g1 in
if degree >= srs_g1_size then
Error
(`Invalid_degree_strictly_less_than_expected
{given = degree; expected = srs_g1_size})
else Ok (Srs_g1.pippenger t.srs.raw.srs_g1 p)
let pp_commit_error fmt
(`Invalid_degree_strictly_less_than_expected {given; expected}) =
Format.fprintf
fmt
"Invalid degree: expecting input polynomial to commit function to have a \
degree strictly less than %d. Got %d."
expected
given
let string_of_commit_error err = Format.asprintf "%a" pp_commit_error err
let prove_commitment (t : t) p =
let max_allowed_committed_poly_degree = t.max_polynomial_length - 1 in
let max_committable_degree = Srs_g1.size t.srs.raw.srs_g1 - 1 in
let offset_monomial_degree =
max_committable_degree - max_allowed_committed_poly_degree
in
let p_with_offset =
Polynomials.mul_xn p offset_monomial_degree Scalar.(copy zero)
in
commit t p_with_offset
let verify_commitment (t : t) cm proof =
let max_allowed_committed_poly_degree = t.max_polynomial_length - 1 in
let max_committable_degree = Srs_g1.size t.srs.raw.srs_g1 - 1 in
let offset_monomial_degree =
max_committable_degree - max_allowed_committed_poly_degree
in
let committed_offset_monomial =
Srs_g2.get t.srs.raw.srs_g2 offset_monomial_degree
in
let open Bls12_381 in
Pairing.pairing_check
[(cm, committed_offset_monomial); (proof, G2.(negate (copy one)))]
let diff_next_power_of_two x = (1 lsl Z.log2up (Z.of_int x)) - x
let preprocess_multiple_multi_reveals t =
assert (t.max_polynomial_length mod t.shard_length = 0) ;
let domain_length = 2 * t.max_polynomial_length / t.shard_length in
let domain = Domains.build domain_length in
let srs = t.srs.raw.srs_g1 in
let s_j j =
let quotient = (t.max_polynomial_length - j) / t.shard_length in
let points =
G1_array.init domain_length (fun i ->
if i < quotient then
Srs_g1.get
srs
(t.max_polynomial_length - j - ((i + 1) * t.shard_length))
else Bls12_381.G1.(copy zero))
in
G1_array.evaluation_ecfft ~domain ~points
in
(domain, Array.init t.shard_length s_j)
let multiple_multi_reveals t ~preprocess:(domain, sj) ~coefficients :
shard_proof array =
assert (t.shard_length < t.max_polynomial_length) ;
let domain_length = Domains.length domain in
let h_j j =
let remainder = (t.max_polynomial_length - j) mod t.shard_length in
let quotient = (t.max_polynomial_length - j) / t.shard_length in
let padding = diff_next_power_of_two quotient in
let points =
Polynomials.init domain_length (fun i ->
let idx =
remainder + ((i - (quotient + (2 * padding))) * t.shard_length)
in
if i = 0 then Scalar.copy coefficients.(t.max_polynomial_length - j)
else if
i <= quotient + (2 * padding) || idx > t.max_polynomial_length
then Scalar.(copy zero)
else Scalar.copy coefficients.(idx))
in
Evaluations.evaluation_fft domain points
in
let evaluations = Array.init t.shard_length h_j in
let h_j = G1_array.mul_arrays ~evaluations ~arrays:sj in
let sum = h_j.(0) in
for i = 1 to t.shard_length - 1 do
G1_array.add_arrays_inplace sum h_j.(i)
done ;
G1_array.interpolation_ecfft_inplace ~domain ~points:sum ;
let len = Domains.length domain / 2 in
let points = G1_array.sub sum ~off:0 ~len in
let domain = Domains.build t.number_of_shards in
G1_array.(to_array (evaluation_ecfft ~domain ~points))
let interpolation_poly ~root ~domain ~evaluations =
assert (Array.length evaluations = Domains.length domain) ;
let size = Domains.length domain in
let evaluations =
ifft_inplace size (Evaluations.of_array (size - 1, evaluations))
in
let root_inverse = Scalar.inverse_exn root in
snd
(Polynomials.fold_left_map
(fun root_pow_inverse coefficient ->
( Scalar.mul root_pow_inverse root_inverse,
Scalar.mul coefficient root_pow_inverse ))
Scalar.(copy one)
evaluations)
let verify t ~commitment ~srs_point ~domain ~root ~evaluations ~proof =
let open Bls12_381 in
let open Result_syntax in
let remainder = interpolation_poly ~root ~domain ~evaluations in
let* commitment_remainder = commit t remainder in
let root_pow = Scalar.pow root (Z.of_int (Domains.length domain)) in
let commit_srs_point_minus_root_pow =
G2.(add srs_point (negate (mul (copy one) root_pow)))
in
let diff_commits = G1.(add commitment_remainder (negate commitment)) in
Ok
(Pairing.pairing_check
[
(diff_commits, G2.(copy one));
(proof, commit_srs_point_minus_root_pow);
])
let save_precompute_shards_proofs precomputation ~filename =
protect (fun () ->
Lwt_io.with_file ~mode:Output filename (fun chan ->
let open Lwt_result_syntax in
let str =
Data_encoding.Binary.to_string_exn
Encoding.shards_proofs_precomputation_encoding
precomputation
in
let*! () = Lwt_io.write chan str in
return_unit))
let hash_precomputation precomputation =
let encoding =
Data_encoding.Binary.to_bytes_exn
Encoding.shards_proofs_precomputation_encoding
precomputation
in
Tezos_crypto.Blake2B.hash_bytes [encoding]
let load_precompute_shards_proofs ~hash ~filename () =
protect (fun () ->
Lwt_io.with_file ~mode:Input filename (fun chan ->
let open Lwt_result_syntax in
let*! str = Lwt_io.read chan in
let precomputation =
Data_encoding.Binary.of_string_exn
Encoding.shards_proofs_precomputation_encoding
str
in
let* () =
match hash with
| Some given ->
let expected = hash_precomputation precomputation in
if Tezos_crypto.Blake2B.equal given expected then return_unit
else
tzfail
(Invalid_precomputation_hash
{
given = Tezos_crypto.Blake2B.to_string given;
expected = Tezos_crypto.Blake2B.to_string expected;
})
| None -> return_unit
in
return precomputation))
let precompute_shards_proofs t =
let domain, precomputation = preprocess_multiple_multi_reveals t in
( Octez_bls12_381_polynomial.Domain.to_array domain,
Array.map G1_array.to_array precomputation )
let prove_shards t ~precomputation:(domain, precomp) ~polynomial =
let setup =
(Domains.of_array domain, Array.map G1_array.of_array precomp)
in
let coefficients =
Array.init (t.max_polynomial_length + 1) (fun _ -> Scalar.(copy zero))
in
let p_length = Polynomials.degree polynomial + 1 in
let p = Polynomials.to_dense_coefficients polynomial in
Array.blit p 0 coefficients 0 p_length ;
multiple_multi_reveals t ~preprocess:setup ~coefficients
let verify_shard (t : t) commitment {index = shard_index; share = evaluations}
proof =
if shard_index < 0 || shard_index >= t.number_of_shards then
Error
(`Shard_index_out_of_range
(Printf.sprintf
"Shard index out of range: got index %d, expected index within \
range [%d, %d]."
shard_index
0
(t.number_of_shards - 1)))
else
let expected_shard_length = t.shard_length in
let got_shard_length = Array.length evaluations in
if expected_shard_length <> got_shard_length then
Error `Shard_length_mismatch
else
let root =
Domains.get t.domain_erasure_encoded_polynomial_length shard_index
in
let domain = Domains.build t.shard_length in
let srs_point = t.srs.kate_amortized_srs_g2_shards in
match
verify t ~commitment ~srs_point ~domain ~root ~evaluations ~proof
with
| Ok true -> Ok ()
| Ok false -> Error `Invalid_shard
| Error e -> Error e
let prove_page t p page_index =
if page_index < 0 || page_index >= t.pages_per_slot then
Error `Page_index_out_of_range
else
let wi = Domains.get t.domain_polynomial_length page_index in
let quotient, _ =
Polynomials.division_xn
p
t.page_length_domain
Scalar.(negate (pow wi (Z.of_int t.page_length_domain)))
in
commit t quotient
let verify_page t commitment ~page_index page proof =
if page_index < 0 || page_index >= t.pages_per_slot then
Error `Page_index_out_of_range
else
let expected_page_length = t.page_size in
let got_page_length = Bytes.length page in
if expected_page_length <> got_page_length then
Error `Page_length_mismatch
else
let domain = Domains.build t.page_length_domain in
let evaluations =
Array.init t.page_length_domain (function
| i when i < t.page_length - 1 ->
let dst = Bytes.create scalar_bytes_amount in
Bytes.blit
page
(i * scalar_bytes_amount)
dst
0
scalar_bytes_amount ;
Scalar.of_bytes_exn dst
| i when i = t.page_length - 1 ->
let dst = Bytes.create t.remaining_bytes in
Bytes.blit
page
(i * scalar_bytes_amount)
dst
0
t.remaining_bytes ;
Scalar.of_bytes_exn dst
| _ -> Scalar.(copy zero))
in
let root = Domains.get t.domain_polynomial_length page_index in
match
verify
t
~commitment
~srs_point:t.srs.kate_amortized_srs_g2_pages
~domain
~root
~evaluations
~proof
with
| Ok true -> Ok ()
| Ok false -> Error `Invalid_page
| Error e -> Error e
end
include Inner
module Verifier = Inner
module Internal_for_tests = struct
let parameters_initialisation
{slot_size; page_size; number_of_shards; redundancy_factor; _} =
let length = slot_as_polynomial_length ~slot_size ~page_size in
let secret =
Bls12_381.Fr.of_string
"20812168509434597367146703229805575690060615791308155437936410982393987532344"
in
let srs_g1 = Srs_g1.generate_insecure length secret in
let erasure_encoded_polynomial_length = redundancy_factor * length in
let evaluations_per_proof =
match erasure_encoded_polynomial_length / number_of_shards with
| exception Invalid_argument _ -> 0
| x -> x
in
let srs_g2 =
Srs_g2.generate_insecure (max length evaluations_per_proof + 1) secret
in
{srs_g1; srs_g2}
let load_parameters parameters = initialisation_parameters := Some parameters
let make_dummy_shards (t : t) ~state =
Random.set_state state ;
let rec loop index seq =
if index = t.number_of_shards then seq
else
let share =
Array.init
(t.shard_length + 1 + Random.int 100)
(fun _ -> Scalar.(random ~state ()))
in
loop (index + 1) (Seq.cons {index; share} seq)
in
loop 0 Seq.empty
let polynomials_equal = Polynomials.equal
let page_proof_equal = Bls12_381.G1.eq
let alter_proof proof = Bls12_381.G1.(add proof one)
let alter_page_proof (proof : page_proof) = alter_proof proof
let alter_shard_proof (proof : shard_proof) = alter_proof proof
let alter_commitment_proof (proof : commitment_proof) = alter_proof proof
let minimum_number_of_shards_to_reconstruct_slot (t : t) =
t.number_of_shards / t.redundancy_factor
let select_fft_domain = select_fft_domain
let precomputation_equal ((d1, a1) : shards_proofs_precomputation)
((d2, a2) : shards_proofs_precomputation) =
Array.for_all2 Scalar.eq d1 d2
&& Array.for_all2 (Array.for_all2 Bls12_381.G1.eq) a1 a2
let reset_initialisation_parameters () = initialisation_parameters := None
let dummy_commitment ~state () = Bls12_381.G1.random ~state ()
let dummy_page_proof ~state () = Bls12_381.G1.random ~state ()
let dummy_shard_proof ~state () = Bls12_381.G1.random ~state ()
let make_dummy_shard ~state ~index ~length =
{index; share = Array.init length (fun _ -> Scalar.(random ~state ()))}
let number_of_pages t = t.pages_per_slot
let shard_length t = t.shard_length
let dummy_polynomial ~state ~degree =
let rec nonzero () =
let res = Bls12_381.Fr.random ~state () in
if Bls12_381.Fr.is_zero res then nonzero () else res
in
Polynomials.init (degree + 1) (fun i ->
if i = degree then nonzero () else Bls12_381.Fr.random ~state ())
let srs_size_g1 t = Srs_g1.size t.srs.raw.srs_g1
let encoded_share_size = encoded_share_size
let ensure_validity
{redundancy_factor; slot_size; page_size; number_of_shards} =
let max_polynomial_length =
slot_as_polynomial_length ~slot_size ~page_size
in
let erasure_encoded_polynomial_length =
redundancy_factor * max_polynomial_length
in
let shard_length = erasure_encoded_polynomial_length / number_of_shards in
let open Result_syntax in
(let* raw =
match !initialisation_parameters with
| None -> fail (`Fail "Dal_cryptobox.make: DAL was not initialisated.")
| Some srs -> return srs
in
ensure_validity
~slot_size
~page_size
~erasure_encoded_polynomial_length
~max_polynomial_length
~redundancy_factor
~number_of_shards
~shard_length
~srs_g1_length:(Srs_g1.size raw.srs_g1)
~srs_g2_length:(Srs_g2.size raw.srs_g2))
|> function
| Ok _ -> true
| _ -> false
end
module Config = struct
type t = Dal_config.t = {
activated : bool;
use_mock_srs_for_testing : parameters option;
bootstrap_peers : string list;
}
let encoding : t Data_encoding.t = Dal_config.encoding
let default = Dal_config.default
let init_dal ~find_srs_files ?(srs_size_log2 = 21) dal_config =
let open Lwt_result_syntax in
if dal_config.activated then
let* initialisation_parameters =
match dal_config.use_mock_srs_for_testing with
| Some parameters ->
return (Internal_for_tests.parameters_initialisation parameters)
| None ->
let*? srs_g1_path, srs_g2_path = find_srs_files () in
initialisation_parameters_from_files
~srs_g1_path
~srs_g2_path
~srs_size_log2
in
Lwt.return (load_parameters initialisation_parameters)
else return_unit
end