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
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
use core::cmp::Ordering;
use core::fmt::Debug;
use std::collections::{BTreeMap, HashMap};
use std::hash::Hasher;
use std::io;
use amplify::AsAny;
use commit_verify::merkle::MerkleNode;
use commit_verify::{CommitConceal, CommitEncode, ConsensusCommit};
use once_cell::sync::Lazy;
use strict_encoding::{StrictDecode, StrictEncode};
use super::{
data, seal, value, ConcealSeals, ConcealState, NoDataError, SealEndpoint, SECP256K1_ZKP,
};
use crate::contract::attachment;
use crate::{AtomicValue, ConfidentialDataError, RevealSeals, StateRetrievalError};
pub(super) static EMPTY_ASSIGNMENTS: Lazy<TypedAssignments> = Lazy::new(TypedAssignments::default);
pub type SealValueMap = BTreeMap<seal::Revealed, AtomicValue>;
pub type EndpointValueMap = BTreeMap<SealEndpoint, AtomicValue>;
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
pub enum StateType {
Void,
Value,
Data,
Attachment,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[derive(StrictEncode, StrictDecode)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate", rename_all = "snake_case")
)]
pub enum TypedAssignments {
Void(Vec<Assignment<DeclarativeStrategy>>),
Value(Vec<Assignment<PedersenStrategy>>),
Data(Vec<Assignment<HashStrategy>>),
Attachment(Vec<Assignment<AttachmentStrategy>>),
}
impl Default for TypedAssignments {
fn default() -> Self { TypedAssignments::Void(vec![]) }
}
impl TypedAssignments {
pub fn zero_balanced(
inputs: Vec<value::Revealed>,
allocations_ours: BTreeMap<seal::Revealed, AtomicValue>,
allocations_theirs: BTreeMap<SealEndpoint, AtomicValue>,
) -> Self {
if allocations_ours.len() + allocations_theirs.len() == 0 {
return Self::Value(vec![]);
}
let mut rng = bitcoin::secp256k1::rand::thread_rng();
let count = allocations_theirs.len() + allocations_ours.len();
let mut blinding_factors = Vec::<_>::with_capacity(count);
for _ in 0..count {
blinding_factors.push(secp256k1zkp::SecretKey::new(&SECP256K1_ZKP, &mut rng));
}
let mut blinding_inputs: Vec<_> = inputs.iter().map(|inp| inp.blinding.into()).collect();
if blinding_inputs.is_empty() {
blinding_inputs.push(secp256k1zkp::key::ONE_KEY);
}
if !blinding_factors.is_empty() {
blinding_factors.pop();
let blinding_correction = SECP256K1_ZKP
.blind_sum(blinding_inputs.clone(), blinding_factors.clone())
.expect("SECP256K1_ZKP failure has negligible probability");
blinding_factors.push(blinding_correction);
}
let mut blinding_iter = blinding_factors.into_iter();
let mut set: Vec<Assignment<_>> = allocations_ours
.into_iter()
.map(|(seal, amount)| Assignment::Revealed {
seal,
state: value::Revealed {
value: amount,
blinding: blinding_iter
.next()
.expect("Internal inconsistency in `AssignmentsVariant::zero_balanced`")
.into(),
},
})
.collect();
set.extend(allocations_theirs.into_iter().map(|(seal_proto, amount)| {
let state = value::Revealed {
value: amount,
blinding: blinding_iter
.next()
.expect("Internal inconsistency in `AssignmentsVariant::zero_balanced`")
.into(),
};
match seal_proto {
SealEndpoint::ConcealedUtxo(seal) => Assignment::ConfidentialSeal { seal, state },
SealEndpoint::WitnessVout {
method,
vout,
blinding,
} => Assignment::Revealed {
seal: seal::Revealed {
method,
txid: None,
vout,
blinding,
},
state,
},
}
}));
Self::Value(set)
}
#[inline]
pub fn state_type(&self) -> StateType {
match self {
TypedAssignments::Void(_) => StateType::Void,
TypedAssignments::Value(_) => StateType::Value,
TypedAssignments::Data(_) => StateType::Data,
TypedAssignments::Attachment(_) => StateType::Attachment,
}
}
#[inline]
pub fn is_declarative(&self) -> bool { matches!(self, TypedAssignments::Void(_)) }
#[inline]
pub fn has_value(&self) -> bool { matches!(self, TypedAssignments::Value(_)) }
#[inline]
pub fn has_data(&self) -> bool { matches!(self, TypedAssignments::Data(_)) }
#[inline]
pub fn is_attachment(&self) -> bool { matches!(self, TypedAssignments::Attachment(_)) }
#[inline]
pub fn declarative_assignments_mut(
&mut self,
) -> Option<&mut Vec<Assignment<DeclarativeStrategy>>> {
match self {
TypedAssignments::Void(set) => Some(set),
_ => None,
}
}
#[inline]
pub fn value_assignments_mut(&mut self) -> Option<&mut Vec<Assignment<PedersenStrategy>>> {
match self {
TypedAssignments::Value(set) => Some(set),
_ => None,
}
}
#[inline]
pub fn data_assignments_mut(&mut self) -> Option<&mut Vec<Assignment<HashStrategy>>> {
match self {
TypedAssignments::Data(set) => Some(set),
_ => None,
}
}
#[inline]
pub fn attachment_assignments_mut(
&mut self,
) -> Option<&mut Vec<Assignment<AttachmentStrategy>>> {
match self {
TypedAssignments::Attachment(set) => Some(set),
_ => None,
}
}
#[inline]
pub fn to_declarative_assignments(&self) -> Vec<Assignment<DeclarativeStrategy>> {
match self {
TypedAssignments::Void(set) => set.clone(),
_ => Default::default(),
}
}
#[inline]
pub fn to_value_assignments(&self) -> Vec<Assignment<PedersenStrategy>> {
match self {
TypedAssignments::Value(set) => set.clone(),
_ => Default::default(),
}
}
#[inline]
pub fn to_data_assignments(&self) -> Vec<Assignment<HashStrategy>> {
match self {
TypedAssignments::Data(set) => set.clone(),
_ => Default::default(),
}
}
#[inline]
pub fn to_attachment_assignments(&self) -> Vec<Assignment<AttachmentStrategy>> {
match self {
TypedAssignments::Attachment(set) => set.clone(),
_ => Default::default(),
}
}
#[inline]
pub fn into_declarative_assignments(self) -> Vec<Assignment<DeclarativeStrategy>> {
match self {
TypedAssignments::Void(set) => set,
_ => Default::default(),
}
}
#[inline]
pub fn into_value_assignments(self) -> Vec<Assignment<PedersenStrategy>> {
match self {
TypedAssignments::Value(set) => set,
_ => Default::default(),
}
}
#[inline]
pub fn into_data_assignments(self) -> Vec<Assignment<HashStrategy>> {
match self {
TypedAssignments::Data(set) => set,
_ => Default::default(),
}
}
#[inline]
pub fn into_attachment_assignments(self) -> Vec<Assignment<AttachmentStrategy>> {
match self {
TypedAssignments::Attachment(set) => set,
_ => Default::default(),
}
}
pub fn revealed_seal_outputs(&self) -> Vec<(seal::Revealed, u16)> {
match self {
TypedAssignments::Void(s) => s
.iter()
.map(Assignment::<_>::revealed_seal)
.enumerate()
.filter_map(|(no, seal)| seal.map(|s| (s, no as u16)))
.collect(),
TypedAssignments::Value(s) => s
.iter()
.map(Assignment::<_>::revealed_seal)
.enumerate()
.filter_map(|(no, seal)| seal.map(|s| (s, no as u16)))
.collect(),
TypedAssignments::Data(s) => s
.iter()
.map(Assignment::<_>::revealed_seal)
.enumerate()
.filter_map(|(no, seal)| seal.map(|s| (s, no as u16)))
.collect(),
TypedAssignments::Attachment(s) => s
.iter()
.map(Assignment::<_>::revealed_seal)
.enumerate()
.filter_map(|(no, seal)| seal.map(|s| (s, no as u16)))
.collect(),
}
}
pub fn revealed_seal_at(&self, index: u16) -> Result<Option<seal::Revealed>, NoDataError> {
Ok(match self {
TypedAssignments::Void(vec) => {
vec.get(index as usize).ok_or(NoDataError)?.revealed_seal()
}
TypedAssignments::Value(vec) => {
vec.get(index as usize).ok_or(NoDataError)?.revealed_seal()
}
TypedAssignments::Data(vec) => {
vec.get(index as usize).ok_or(NoDataError)?.revealed_seal()
}
TypedAssignments::Attachment(vec) => {
vec.get(index as usize).ok_or(NoDataError)?.revealed_seal()
}
})
}
pub fn revealed_seals(&self) -> Result<Vec<seal::Revealed>, ConfidentialDataError> {
let list: Vec<_> = match self {
TypedAssignments::Void(s) => s.iter().map(Assignment::<_>::revealed_seal).collect(),
TypedAssignments::Value(s) => s.iter().map(Assignment::<_>::revealed_seal).collect(),
TypedAssignments::Data(s) => s.iter().map(Assignment::<_>::revealed_seal).collect(),
TypedAssignments::Attachment(s) => {
s.iter().map(Assignment::<_>::revealed_seal).collect()
}
};
let len = list.len();
let filtered: Vec<seal::Revealed> = list.into_iter().flatten().collect();
if len != filtered.len() {
return Err(ConfidentialDataError);
}
Ok(filtered)
}
pub fn filter_revealed_seals(&self) -> Vec<seal::Revealed> {
match self {
TypedAssignments::Void(s) => s
.iter()
.filter_map(Assignment::<_>::revealed_seal)
.collect(),
TypedAssignments::Value(s) => s
.iter()
.filter_map(Assignment::<_>::revealed_seal)
.collect(),
TypedAssignments::Data(s) => s
.iter()
.filter_map(Assignment::<_>::revealed_seal)
.collect(),
TypedAssignments::Attachment(s) => s
.iter()
.filter_map(Assignment::<_>::revealed_seal)
.collect(),
}
}
pub fn to_confidential_seals(&self) -> Vec<seal::Confidential> {
match self {
TypedAssignments::Void(s) => s
.iter()
.map(Assignment::<_>::to_confidential_seal)
.collect(),
TypedAssignments::Value(s) => s
.iter()
.map(Assignment::<_>::to_confidential_seal)
.collect(),
TypedAssignments::Data(s) => s
.iter()
.map(Assignment::<_>::to_confidential_seal)
.collect(),
TypedAssignments::Attachment(s) => s
.iter()
.map(Assignment::<_>::to_confidential_seal)
.collect(),
}
}
pub fn as_revealed_state_values(&self) -> Result<Vec<&value::Revealed>, StateRetrievalError> {
let list = match self {
TypedAssignments::Value(s) => s.iter().map(Assignment::<_>::as_revealed_state),
_ => return Err(StateRetrievalError::StateTypeMismatch),
};
let len = list.len();
let filtered: Vec<&value::Revealed> = list.flatten().collect();
if len != filtered.len() {
return Err(StateRetrievalError::ConfidentialData);
}
Ok(filtered)
}
pub fn as_revealed_state_data(&self) -> Result<Vec<&data::Revealed>, StateRetrievalError> {
let list = match self {
TypedAssignments::Data(s) => s.iter().map(Assignment::<_>::as_revealed_state),
_ => return Err(StateRetrievalError::StateTypeMismatch),
};
let len = list.len();
let filtered: Vec<&data::Revealed> = list.flatten().collect();
if len != filtered.len() {
return Err(StateRetrievalError::ConfidentialData);
}
Ok(filtered)
}
pub fn as_revealed_state_attachments(
&self,
) -> Result<Vec<&attachment::Revealed>, StateRetrievalError> {
let list = match self {
TypedAssignments::Attachment(s) => s.iter().map(Assignment::<_>::as_revealed_state),
_ => return Err(StateRetrievalError::StateTypeMismatch),
};
let len = list.len();
let filtered: Vec<&attachment::Revealed> = list.flatten().collect();
if len != filtered.len() {
return Err(StateRetrievalError::ConfidentialData);
}
Ok(filtered)
}
pub fn filter_revealed_state_values(&self) -> Vec<&value::Revealed> {
match self {
TypedAssignments::Void(_) => vec![],
TypedAssignments::Value(s) => s
.iter()
.filter_map(Assignment::<_>::as_revealed_state)
.collect(),
TypedAssignments::Data(_) => vec![],
TypedAssignments::Attachment(_) => vec![],
}
}
pub fn filter_revealed_state_data(&self) -> Vec<&data::Revealed> {
match self {
TypedAssignments::Void(_) => vec![],
TypedAssignments::Value(_) => vec![],
TypedAssignments::Data(s) => s
.iter()
.filter_map(Assignment::<_>::as_revealed_state)
.collect(),
TypedAssignments::Attachment(_) => vec![],
}
}
pub fn filter_revealed_state_attachments(&self) -> Vec<&attachment::Revealed> {
match self {
TypedAssignments::Void(_) => vec![],
TypedAssignments::Value(_) => vec![],
TypedAssignments::Data(_) => vec![],
TypedAssignments::Attachment(s) => s
.iter()
.filter_map(Assignment::<_>::as_revealed_state)
.collect(),
}
}
pub fn to_confidential_state_pedersen(&self) -> Vec<value::Confidential> {
match self {
TypedAssignments::Void(_) => vec![],
TypedAssignments::Value(s) => s
.iter()
.map(Assignment::<_>::to_confidential_state)
.collect(),
TypedAssignments::Data(_) => vec![],
TypedAssignments::Attachment(_) => vec![],
}
}
pub fn to_confidential_state_hashed(&self) -> Vec<data::Confidential> {
match self {
TypedAssignments::Void(_) => vec![],
TypedAssignments::Value(_) => vec![],
TypedAssignments::Data(s) => s
.iter()
.map(Assignment::<_>::to_confidential_state)
.collect(),
TypedAssignments::Attachment(_) => vec![],
}
}
pub fn to_confidential_state_attachments(&self) -> Vec<attachment::Confidential> {
match self {
TypedAssignments::Void(_) => vec![],
TypedAssignments::Value(_) => vec![],
TypedAssignments::Data(_) => vec![],
TypedAssignments::Attachment(s) => s
.iter()
.map(Assignment::<_>::to_confidential_state)
.collect(),
}
}
#[inline]
pub fn as_revealed_owned_value(
&self,
) -> Result<Vec<(seal::Revealed, &value::Revealed)>, StateRetrievalError> {
match self {
TypedAssignments::Value(vec) => {
let unfiltered: Vec<_> = vec
.iter()
.filter_map(|assignment| {
assignment.revealed_seal().and_then(|seal| {
assignment.as_revealed_state().map(|state| (seal, state))
})
})
.collect();
if unfiltered.len() != vec.len() {
Err(StateRetrievalError::ConfidentialData)
} else {
Ok(unfiltered)
}
}
_ => Err(StateRetrievalError::StateTypeMismatch),
}
}
#[inline]
pub fn as_revealed_owned_data(
&self,
) -> Result<Vec<(seal::Revealed, &data::Revealed)>, StateRetrievalError> {
match self {
TypedAssignments::Data(vec) => {
let unfiltered: Vec<_> = vec
.iter()
.filter_map(|assignment| {
assignment.revealed_seal().and_then(|seal| {
assignment.as_revealed_state().map(|state| (seal, state))
})
})
.collect();
if unfiltered.len() != vec.len() {
Err(StateRetrievalError::ConfidentialData)
} else {
Ok(unfiltered)
}
}
_ => Err(StateRetrievalError::StateTypeMismatch),
}
}
#[inline]
pub fn as_revealed_owned_attachments(
&self,
) -> Result<Vec<(seal::Revealed, &attachment::Revealed)>, StateRetrievalError> {
match self {
TypedAssignments::Attachment(vec) => {
let unfiltered: Vec<_> = vec
.iter()
.filter_map(|assignment| {
assignment.revealed_seal().and_then(|seal| {
assignment.as_revealed_state().map(|state| (seal, state))
})
})
.collect();
if unfiltered.len() != vec.len() {
Err(StateRetrievalError::ConfidentialData)
} else {
Ok(unfiltered)
}
}
_ => Err(StateRetrievalError::StateTypeMismatch),
}
}
pub fn is_empty(&self) -> bool {
match self {
TypedAssignments::Void(set) => set.is_empty(),
TypedAssignments::Value(set) => set.is_empty(),
TypedAssignments::Data(set) => set.is_empty(),
TypedAssignments::Attachment(set) => set.is_empty(),
}
}
pub fn len(&self) -> usize {
match self {
TypedAssignments::Void(set) => set.len(),
TypedAssignments::Value(set) => set.len(),
TypedAssignments::Data(set) => set.len(),
TypedAssignments::Attachment(set) => set.len(),
}
}
pub fn consensus_commitments(&self) -> Vec<MerkleNode> {
match self {
TypedAssignments::Void(vec) => vec
.iter()
.map(Assignment::<DeclarativeStrategy>::consensus_commit)
.collect(),
TypedAssignments::Value(vec) => vec
.iter()
.map(Assignment::<PedersenStrategy>::consensus_commit)
.collect(),
TypedAssignments::Data(vec) => vec
.iter()
.map(Assignment::<HashStrategy>::consensus_commit)
.collect(),
TypedAssignments::Attachment(vec) => vec
.iter()
.map(Assignment::<AttachmentStrategy>::consensus_commit)
.collect(),
}
}
}
impl RevealSeals for TypedAssignments {
fn reveal_seals(&mut self, known_seals: &[seal::Revealed]) -> usize {
let mut counter = 0;
match self {
TypedAssignments::Void(_) => {}
TypedAssignments::Value(set) => {
*self = TypedAssignments::Value(
set.iter()
.map(|assignment| {
let mut assignment = assignment.clone();
counter += assignment.reveal_seals(known_seals);
assignment
})
.collect(),
);
}
TypedAssignments::Data(set) => {
*self = TypedAssignments::Data(
set.iter()
.map(|assignment| {
let mut assignment = assignment.clone();
counter += assignment.reveal_seals(known_seals);
assignment
})
.collect(),
);
}
TypedAssignments::Attachment(set) => {
*self = TypedAssignments::Attachment(
set.iter()
.map(|assignment| {
let mut assignment = assignment.clone();
counter += assignment.reveal_seals(known_seals);
assignment
})
.collect(),
);
}
}
counter
}
}
impl ConcealSeals for TypedAssignments {
fn conceal_seals(&mut self, seals: &[seal::Confidential]) -> usize {
match self {
TypedAssignments::Void(data) => data as &mut dyn ConcealSeals,
TypedAssignments::Value(data) => data as &mut dyn ConcealSeals,
TypedAssignments::Data(data) => data as &mut dyn ConcealSeals,
TypedAssignments::Attachment(data) => data as &mut dyn ConcealSeals,
}
.conceal_seals(seals)
}
}
impl ConcealState for TypedAssignments {
fn conceal_state_except(&mut self, seals: &[seal::Confidential]) -> usize {
match self {
TypedAssignments::Void(data) => data as &mut dyn ConcealState,
TypedAssignments::Value(data) => data as &mut dyn ConcealState,
TypedAssignments::Data(data) => data as &mut dyn ConcealState,
TypedAssignments::Attachment(data) => data as &mut dyn ConcealState,
}
.conceal_state_except(seals)
}
}
pub trait ConfidentialState: StrictEncode + StrictDecode + Debug + Clone + AsAny {}
pub trait RevealedState:
StrictEncode + StrictDecode + Debug + CommitConceal + Clone + AsAny
{
}
impl TypedAssignments {
pub fn u8(&self) -> Vec<u8> {
self.filter_revealed_state_data()
.into_iter()
.filter_map(data::Revealed::u8)
.collect()
}
pub fn u16(&self) -> Vec<u16> {
self.filter_revealed_state_data()
.into_iter()
.filter_map(data::Revealed::u16)
.collect()
}
pub fn u32(&self) -> Vec<u32> {
self.filter_revealed_state_data()
.into_iter()
.filter_map(data::Revealed::u32)
.collect()
}
pub fn u64(&self) -> Vec<u64> {
self.filter_revealed_state_data()
.into_iter()
.filter_map(data::Revealed::u64)
.collect()
}
pub fn i8(&self) -> Vec<i8> {
self.filter_revealed_state_data()
.into_iter()
.filter_map(data::Revealed::i8)
.collect()
}
pub fn i16(&self) -> Vec<i16> {
self.filter_revealed_state_data()
.into_iter()
.filter_map(data::Revealed::i16)
.collect()
}
pub fn i32(&self) -> Vec<i32> {
self.filter_revealed_state_data()
.into_iter()
.filter_map(data::Revealed::i32)
.collect()
}
pub fn i64(&self) -> Vec<i64> {
self.filter_revealed_state_data()
.into_iter()
.filter_map(data::Revealed::i64)
.collect()
}
pub fn f32(&self) -> Vec<f32> {
self.filter_revealed_state_data()
.into_iter()
.filter_map(data::Revealed::f32)
.collect()
}
pub fn f64(&self) -> Vec<f64> {
self.filter_revealed_state_data()
.into_iter()
.filter_map(data::Revealed::f64)
.collect()
}
pub fn bytes(&self) -> Vec<Vec<u8>> {
self.filter_revealed_state_data()
.into_iter()
.filter_map(data::Revealed::bytes)
.collect()
}
pub fn string(&self) -> Vec<String> {
self.filter_revealed_state_data()
.into_iter()
.filter_map(data::Revealed::unicode_string)
.collect()
}
}
pub trait State: Debug {
type Confidential: ConfidentialState;
type Revealed: RevealedState;
}
#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct DeclarativeStrategy;
impl State for DeclarativeStrategy {
type Confidential = data::Void;
type Revealed = data::Void;
}
#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct PedersenStrategy;
impl State for PedersenStrategy {
type Confidential = value::Confidential;
type Revealed = value::Revealed;
}
#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct HashStrategy;
impl State for HashStrategy {
type Confidential = data::Confidential;
type Revealed = data::Revealed;
}
#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct AttachmentStrategy;
impl State for AttachmentStrategy {
type Confidential = attachment::Confidential;
type Revealed = attachment::Revealed;
}
#[derive(Clone, Debug)]
#[derive(StrictEncode, StrictDecode)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate", rename_all = "snake_case")
)]
pub enum Assignment<StateType>
where
StateType: State,
StateType::Confidential: PartialEq + Eq,
StateType::Confidential: From<<StateType::Revealed as CommitConceal>::ConcealedCommitment>,
{
Confidential {
seal: seal::Confidential,
state: StateType::Confidential,
},
Revealed {
seal: seal::Revealed,
state: StateType::Revealed,
},
ConfidentialSeal {
seal: seal::Confidential,
state: StateType::Revealed,
},
ConfidentialState {
seal: seal::Revealed,
state: StateType::Confidential,
},
}
impl<StateType> std::hash::Hash for Assignment<StateType>
where
Self: Clone,
StateType: State,
StateType::Confidential: PartialEq + Eq,
StateType::Confidential: From<<StateType::Revealed as CommitConceal>::ConcealedCommitment>,
{
fn hash<H: Hasher>(&self, state: &mut H) { state.write(&self.consensus_commit()[..]) }
}
impl<StateType> PartialOrd for Assignment<StateType>
where
StateType: State,
StateType::Confidential: PartialEq + Eq,
StateType::Confidential: From<<StateType::Revealed as CommitConceal>::ConcealedCommitment>,
{
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.to_confidential_seal()
.partial_cmp(&other.to_confidential_seal())
}
}
impl<StateType> Ord for Assignment<StateType>
where
StateType: State,
StateType::Confidential: PartialEq + Eq,
StateType::Confidential: From<<StateType::Revealed as CommitConceal>::ConcealedCommitment>,
{
fn cmp(&self, other: &Self) -> Ordering {
self.to_confidential_seal()
.cmp(&other.to_confidential_seal())
}
}
impl<StateType> PartialEq for Assignment<StateType>
where
StateType: State,
StateType::Confidential: PartialEq + Eq,
StateType::Confidential: From<<StateType::Revealed as CommitConceal>::ConcealedCommitment>,
{
fn eq(&self, other: &Self) -> bool {
self.to_confidential_seal() == other.to_confidential_seal()
&& self.to_confidential_state() == other.to_confidential_state()
}
}
impl<StateType> Eq for Assignment<StateType>
where
StateType: State,
StateType::Confidential: PartialEq + Eq,
StateType::Confidential: From<<StateType::Revealed as CommitConceal>::ConcealedCommitment>,
{
}
impl<StateType> Assignment<StateType>
where
StateType: State,
StateType::Confidential: PartialEq + Eq,
StateType::Confidential: From<<StateType::Revealed as CommitConceal>::ConcealedCommitment>,
{
pub fn with_seal_replaced(assignment: &Self, seal: seal::Revealed) -> Self {
match assignment {
Assignment::Confidential { seal: _, state }
| Assignment::ConfidentialState { seal: _, state } => Assignment::ConfidentialState {
seal,
state: state.clone(),
},
Assignment::ConfidentialSeal { seal: _, state }
| Assignment::Revealed { seal: _, state } => Assignment::Revealed {
seal,
state: state.clone(),
},
}
}
pub fn to_confidential_seal(&self) -> seal::Confidential {
match self {
Assignment::Revealed { seal, .. } | Assignment::ConfidentialState { seal, .. } => {
seal.commit_conceal()
}
Assignment::Confidential { seal, .. } | Assignment::ConfidentialSeal { seal, .. } => {
*seal
}
}
}
pub fn revealed_seal(&self) -> Option<seal::Revealed> {
match self {
Assignment::Revealed { seal, .. } | Assignment::ConfidentialState { seal, .. } => {
Some(*seal)
}
Assignment::Confidential { .. } | Assignment::ConfidentialSeal { .. } => None,
}
}
pub fn to_confidential_state(&self) -> StateType::Confidential {
match self {
Assignment::Revealed { state, .. } | Assignment::ConfidentialSeal { state, .. } => {
state.commit_conceal().into()
}
Assignment::Confidential { state, .. }
| Assignment::ConfidentialState { state, .. } => state.clone(),
}
}
pub fn as_revealed_state(&self) -> Option<&StateType::Revealed> {
match self {
Assignment::Revealed { state, .. } | Assignment::ConfidentialSeal { state, .. } => {
Some(state)
}
Assignment::Confidential { .. } | Assignment::ConfidentialState { .. } => None,
}
}
pub fn as_revealed(&self) -> Option<(&seal::Revealed, &StateType::Revealed)> {
match self {
Assignment::Revealed { seal, state } => Some((seal, state)),
_ => None,
}
}
pub fn to_revealed(&self) -> Option<(seal::Revealed, StateType::Revealed)> {
match self {
Assignment::Revealed { seal, state } => Some((*seal, state.clone())),
_ => None,
}
}
pub fn into_revealed(self) -> Option<(seal::Revealed, StateType::Revealed)> {
match self {
Assignment::Revealed { seal, state } => Some((seal, state)),
_ => None,
}
}
}
impl<StateType> CommitConceal for Assignment<StateType>
where
Self: Clone,
StateType: State,
StateType::Confidential: PartialEq + Eq,
StateType::Confidential: From<<StateType::Revealed as CommitConceal>::ConcealedCommitment>,
{
type ConcealedCommitment = Self;
fn commit_conceal(&self) -> Self::ConcealedCommitment {
match self {
Assignment::Confidential { .. } => self.clone(),
Assignment::ConfidentialState { seal, state } => Self::Confidential {
seal: seal.commit_conceal(),
state: state.clone(),
},
Assignment::Revealed { seal, state } => Self::Confidential {
seal: seal.commit_conceal(),
state: state.commit_conceal().into(),
},
Assignment::ConfidentialSeal { seal, state } => Self::Confidential {
seal: *seal,
state: state.commit_conceal().into(),
},
}
}
}
impl<StateType> RevealSeals for Assignment<StateType>
where
StateType: State,
StateType::Revealed: CommitConceal,
StateType::Confidential: PartialEq + Eq,
<StateType as State>::Confidential:
From<<StateType::Revealed as CommitConceal>::ConcealedCommitment>,
{
fn reveal_seals(&mut self, known_seals: &[seal::Revealed]) -> usize {
let known_seals: HashMap<seal::Confidential, seal::Revealed> = known_seals
.iter()
.map(|rev| (rev.commit_conceal(), *rev))
.collect();
let mut counter = 0;
match self {
Assignment::Confidential { seal, state } => {
if let Some(reveal) = known_seals.get(seal) {
*self = Assignment::ConfidentialState {
seal: *reveal,
state: state.clone(),
};
counter += 1;
};
}
Assignment::ConfidentialSeal { seal, state } => {
if let Some(reveal) = known_seals.get(seal) {
*self = Assignment::Revealed {
seal: *reveal,
state: state.clone(),
};
counter += 1;
};
}
_ => {}
}
counter
}
}
impl<StateType> ConcealSeals for Assignment<StateType>
where
StateType: State,
StateType::Revealed: CommitConceal,
StateType::Confidential: PartialEq + Eq,
<StateType as State>::Confidential:
From<<StateType::Revealed as CommitConceal>::ConcealedCommitment>,
{
fn conceal_seals(&mut self, seals: &[seal::Confidential]) -> usize {
match self {
Assignment::Confidential { .. } | Assignment::ConfidentialSeal { .. } => 0,
Assignment::ConfidentialState { seal, state } => {
if seals.contains(&seal.commit_conceal()) {
*self = Assignment::<StateType>::Confidential {
state: state.clone(),
seal: seal.commit_conceal(),
};
1
} else {
0
}
}
Assignment::Revealed { seal, state } => {
if seals.contains(&seal.commit_conceal()) {
*self = Assignment::<StateType>::ConfidentialSeal {
state: state.clone(),
seal: seal.commit_conceal(),
};
1
} else {
0
}
}
}
}
}
impl<StateType> ConcealState for Assignment<StateType>
where
StateType: State,
StateType::Revealed: CommitConceal,
StateType::Confidential: PartialEq + Eq,
<StateType as State>::Confidential:
From<<StateType::Revealed as CommitConceal>::ConcealedCommitment>,
{
fn conceal_state_except(&mut self, seals: &[seal::Confidential]) -> usize {
match self {
Assignment::Confidential { .. } | Assignment::ConfidentialState { .. } => 0,
Assignment::ConfidentialSeal { seal, state } => {
if seals.contains(seal) {
0
} else {
*self = Assignment::<StateType>::Confidential {
state: state.commit_conceal().into(),
seal: *seal,
};
1
}
}
Assignment::Revealed { seal, state } => {
if seals.contains(&seal.commit_conceal()) {
0
} else {
*self = Assignment::<StateType>::ConfidentialState {
state: state.commit_conceal().into(),
seal: *seal,
};
1
}
}
}
}
}
impl<StateType> CommitEncode for Assignment<StateType>
where
Self: Clone,
StateType: State,
StateType::Confidential: PartialEq + Eq,
StateType::Confidential: From<<StateType::Revealed as CommitConceal>::ConcealedCommitment>,
{
fn commit_encode<E: io::Write>(&self, e: E) -> usize {
self.commit_conceal().strict_encode(e).expect(
"Strict encoding must not fail for types implementing \
ConsensusCommit via marker trait ConsensusCommitFromStrictEncoding",
)
}
}
impl<StateType> ConsensusCommit for Assignment<StateType>
where
Self: Clone,
StateType: State,
StateType::Confidential: PartialEq + Eq,
StateType::Confidential: From<<StateType::Revealed as CommitConceal>::ConcealedCommitment>,
{
type Commitment = MerkleNode;
}
#[cfg(test)]
mod test {
use std::collections::BTreeMap;
use bitcoin::blockdata::transaction::OutPoint;
use bitcoin::hashes::hex::{FromHex, ToHex};
use bitcoin::hashes::{sha256, Hash};
use bp::seals::txout::TxoSeal;
use commit_verify::merkle::MerkleNode;
use commit_verify::{merklize, CommitConceal, CommitEncode, ToMerkleSource};
use secp256k1zkp::pedersen::Commitment;
use secp256k1zkp::rand::{thread_rng, Rng, RngCore};
use secp256k1zkp::{Secp256k1, SecretKey};
use strict_encoding_test::test_vec_decoding_roundtrip;
use super::super::{NodeId, OwnedRights, ParentOwnedRights};
use super::*;
use crate::contract::seal::Revealed;
use crate::schema;
static HASH_VARIANT: [u8; 267] = include!("../../test/hash_state.in");
static PEDERSAN_VARIANT: [u8; 1664] = include!("../../test/pedersan_state.in");
static DECLARATIVE_VARIANT: [u8; 161] = include!("../../test/declarative_state.in");
static PARENT_RIGHTS: [u8; 78] = include!("../../test/parent_rights.in");
static TXID_VEC: [&str; 4] = [
"201fdd1e2b62d7b6938271295118ee181f1bac5e57d9f4528925650d36d3af8e",
"f57ed27ee4199072c5ff3b774febc94d26d3e4a5559d133de4750a948df50e06",
"12072893d951c633dcafb4d3074d1fc41c5e6e64b8d53e3b0705c41bc6679d54",
"8f75db9f89c7c75f0a54322f18cd4d557ae75c24a8e5a95eae13fe26edc2d789",
];
static STATE_DATA: [&str; 4] = [
"e70a36e2ce51d31d4cf5d6731fa63738648127db833715d39652d86d927d4888",
"408e331ebce96ca98cfb7b8a6286a79300379eed6395636e6d103017d474039f",
"c6411aea082e2c5d74347368677db69545126237d5ed78faa0846352f5383f95",
"277fb00655e2523424677686c24d90fba6b70869050ae204782e8ef0ab8049c6",
];
static DECLARATIVE_OUTPOINT_HASH: [&str; 4] = [
"58f3ea4817a12aa6f1007d5b3d24dd2940ce40f8498029e05f1dc6465b3d65b4",
"6b3c1bee0bd431f53e6c099890fdaf51b8556a6dcd61c6150ca055d0e1d4a524",
"9a17566abc006cf335fd96d8f8a4136526d85493a85ebe875abbbee19795c496",
"c843ac6b197ae371191264cc0e4ed18a910b5522a0bad72a24f2080c170e2053",
];
static PEDERSAN_OUTPOINT_HASH: [&str; 4] = [
"281543d7f791d4b4f8ef1196e436bc3286a5505f7bafd978d4af9be6f112e1b4",
"32d71a47d8ff6015fc58525985af7346e0802c7ad065ad79335602c7a6562ab3",
"68955a27e1ffde810fcfdd18697eb59aa4f7b0afde2a8193cd28184b729b5195",
"698c43d973bec68540e6df67137785e40be6d29def4888ada3cd7b7884b37f62",
];
static HASH_OUTPOINT_HASH: [&str; 4] = [
"7efe71b7a37a39da798774ca6b09def9724d81303892d55cac3edb0dc8340a3a",
"9565d29461c863e013c26d176a9929307286963322849a1dc6c978e5c70c8d52",
"9b64a3024632f0517d8a608cb29902f7083eab0ac25d2827a5ef27e9a68b18f9",
"dc0d0d7139a3ad6010a210e5900201979a1a09047b10a877688ee5a740ae215a",
];
#[test]
#[ignore]
fn test_encoded_data() {
let _: TypedAssignments = test_vec_decoding_roundtrip(HASH_VARIANT).unwrap();
let _: TypedAssignments = test_vec_decoding_roundtrip(PEDERSAN_VARIANT).unwrap();
let _: TypedAssignments = test_vec_decoding_roundtrip(DECLARATIVE_VARIANT).unwrap();
}
#[test]
#[ignore]
#[should_panic(expected = "UnsupportedDataStructure")]
fn test_garbage_ped_2() {
let mut bytes = PEDERSAN_VARIANT.clone();
bytes[1] = 0x02;
TypedAssignments::strict_decode(&bytes[..]).unwrap();
}
fn zero_balance(
input_amounts: &[u64],
output_amounts: &[u64],
partition: usize,
) -> (Vec<Commitment>, Vec<Commitment>) {
let mut rng = thread_rng();
let input_revealed: Vec<value::Revealed> = input_amounts[..]
.into_iter()
.map(|amount| value::Revealed::with_amount(*amount, &mut rng))
.collect();
let mut txid_vec: Vec<bitcoin::Txid> = Vec::with_capacity(output_amounts.len());
for _ in 0..output_amounts.len() {
let mut bytes: [u8; 32] = [0; 32];
rng.fill(&mut bytes[..]);
let txid = bitcoin::Txid::from_hex(&bytes.to_vec().to_hex()[..]).unwrap();
txid_vec.push(txid);
}
let zip_data = txid_vec[..partition]
.iter()
.zip(output_amounts[..partition].iter());
let ours: SealValueMap = zip_data
.map(|(txid, amount)| {
(
Revealed::from(OutPoint::new(*txid, rng.gen_range(0, 10))),
amount.clone(),
)
})
.collect();
let zip_data2 = txid_vec[partition..]
.iter()
.zip(output_amounts[partition..].iter());
let theirs: EndpointValueMap = zip_data2
.map(|(txid, amount)| {
(
SealEndpoint::ConcealedUtxo(
Revealed::from(OutPoint::new(*txid, rng.gen_range(0, 10))).commit_conceal(),
),
amount.clone(),
)
})
.collect();
let balanced = TypedAssignments::zero_balanced(input_revealed.clone(), ours, theirs);
let outputs: Vec<Commitment> = balanced
.to_confidential_state_pedersen()
.iter()
.map(|confidential| confidential.commitment)
.collect();
let inputs: Vec<Commitment> = input_revealed
.iter()
.map(|revealed| revealed.commit_conceal().commitment)
.collect();
(inputs, outputs)
}
fn zero_balance_verify(
input_amounts: &[u64],
output_amounts: &[u64],
partition: usize,
) -> bool {
let (inputs, outputs) = zero_balance(input_amounts, output_amounts, partition);
value::Confidential::verify_commit_sum(inputs, outputs)
}
#[test]
fn test_zero_balance_nonoverflow() {
assert!(zero_balance_verify(
&[core::u64::MAX, 1],
&[1, core::u64::MAX],
1
));
assert!(zero_balance_verify(
&[core::u64::MAX, core::u64::MAX],
&[core::u64::MAX, core::u64::MAX],
1
));
assert!(zero_balance_verify(
&[core::u32::MAX as u64, core::u32::MAX as u64],
&[core::u32::MAX as u64 + core::u32::MAX as u64],
1
));
assert!(zero_balance_verify(
&[core::u32::MAX as u64, core::u32::MAX as u64, core::u64::MAX],
&[core::u64::MAX, (core::u32::MAX as u64) * 2],
1
));
}
#[test]
fn test_zero_balance_single() {
let single_amounts = vec![
[0u64],
[1u64],
[core::u16::MAX as u64],
[core::u32::MAX as u64],
[core::u64::MAX - 1u64],
[core::u64::MAX],
];
for vec in single_amounts.iter() {
assert!(zero_balance_verify(vec, vec, 0));
assert!(zero_balance_verify(vec, vec, 1));
assert!(zero_balance_verify(vec, vec, vec.len() / 2));
assert!(zero_balance_verify(vec, vec, vec.len() / 2 + 1));
}
}
#[test]
fn test_zero_balance_double() {
let double_amounts = vec![[(core::u32::MAX - 1) as u64, (core::u32::MAX - 1) as u64], [
core::u32::MAX as u64,
core::u32::MAX as u64,
]];
for vec in double_amounts.iter() {
assert!(zero_balance_verify(vec, vec, 0));
assert!(zero_balance_verify(vec, vec, 1));
assert!(zero_balance_verify(vec, vec, vec.len() / 2));
assert!(zero_balance_verify(vec, vec, vec.len() / 2 + 1));
}
}
#[test]
fn test_zero_balance_multiple() {
let multiple_amounts = vec![
[0u64, 0u64, 0u64, 0u64],
[0u64, 1u64, 0u64, 1u64],
[1u64, 2u64, 3u64, core::u64::MAX],
[10u64, 20u64, 30u64, 40u64],
[0u64, 197642u64, core::u64::MAX, 476543u64],
[core::u64::MAX, core::u64::MAX, core::u64::MAX, core::u64::MAX],
];
for vec in multiple_amounts.iter() {
assert!(zero_balance_verify(vec, vec, 0));
assert!(zero_balance_verify(vec, vec, 1));
assert!(zero_balance_verify(vec, vec, vec.len() / 2));
assert!(zero_balance_verify(vec, vec, vec.len() / 2 + 1));
}
assert!(zero_balance_verify(
&multiple_amounts[2],
&multiple_amounts[2],
0
));
assert!(zero_balance_verify(
&multiple_amounts[4],
&multiple_amounts[4],
multiple_amounts[4].len()
));
}
#[test]
fn test_zero_balance_negative() {
assert!(!zero_balance_verify(
&[0u64, 1u64, 0u64, 1u64],
&[1u64, 2u64, 3u64, core::u64::MAX],
2
));
assert!(!zero_balance_verify(
&[1u64, 2u64, 3u64, core::u64::MAX],
&[10u64, 20u64, 30u64, 40u64],
2
));
assert!(!zero_balance_verify(
&[10u64, 20u64, 30u64, 40u64],
&[0u64, 197642u64, core::u64::MAX, 476543u64],
2
));
assert!(!zero_balance_verify(
&[0u64, 197642u64, core::u64::MAX, 476543u64],
&[core::u64::MAX, core::u64::MAX, core::u64::MAX, core::u64::MAX],
2
));
assert!(!zero_balance_verify(&[1, 2, 3, 4], &[1, 2, 3, 5], 2));
assert!(!zero_balance_verify(
&[1, 2, 3, 0],
&[1, 2, 3, core::u64::MAX],
2
));
}
#[test]
fn test_zero_balance_random() {
let mut rng = thread_rng();
for _ in 0..5 {
let input_length = rng.gen_range(1, 20);
let mut input_amounts = vec![0; input_length];
for index in 0..input_length {
input_amounts[index] = rng.gen_range::<u64>(100_000, 100_000_000_000);
}
let input_sum: u64 = input_amounts.iter().sum();
let mut output_amounts = vec![0u64; rng.gen_range(1, 20)];
let output_length = output_amounts.len();
for index in 0..output_length - 1 {
output_amounts[index] = rng.gen_range::<u64>(100_000, 100_000_000_000);
}
let output_sum: u64 = output_amounts.iter().sum();
if input_sum == output_sum {
continue;
} else if output_sum > input_sum {
input_amounts[input_length - 1] += output_sum - input_sum;
} else {
output_amounts[output_length - 1] += input_sum - output_sum;
}
let (inputs, outputs) = zero_balance(
&input_amounts[..],
&output_amounts[..],
rng.gen_range(0, output_length),
);
assert!(value::Confidential::verify_commit_sum(
inputs.clone(),
outputs.clone()
));
if input_length > 1 {
assert_eq!(
value::Confidential::verify_commit_sum(
inputs[..(input_length - 1)].to_vec(),
outputs
),
false
);
} else if output_length > 1 {
assert_eq!(
value::Confidential::verify_commit_sum(
inputs,
outputs[..(output_length - 1)].to_vec()
),
false
);
}
}
}
#[test]
#[ignore]
fn test_identification() {
let declarative_type = TypedAssignments::strict_decode(&DECLARATIVE_VARIANT[..]).unwrap();
let pedersan_type = TypedAssignments::strict_decode(&PEDERSAN_VARIANT[..]).unwrap();
let hash_type = TypedAssignments::strict_decode(&HASH_VARIANT[..]).unwrap();
assert!(declarative_type.is_declarative());
assert!(pedersan_type.has_value());
assert!(hash_type.has_data());
assert!(!declarative_type.has_data());
assert!(!declarative_type.has_value());
assert!(!pedersan_type.is_declarative());
assert!(!pedersan_type.has_data());
assert!(!hash_type.is_declarative());
assert!(!hash_type.has_value());
}
#[test]
#[ignore]
fn test_extraction() {
let mut declarative_type =
TypedAssignments::strict_decode(&DECLARATIVE_VARIANT[..]).unwrap();
let mut pedersan_type = TypedAssignments::strict_decode(&PEDERSAN_VARIANT[..]).unwrap();
let mut hash_type = TypedAssignments::strict_decode(&HASH_VARIANT[..]).unwrap();
assert!(!declarative_type.to_declarative_assignments().is_empty());
assert!(!pedersan_type.to_value_assignments().is_empty());
assert!(!hash_type.to_data_assignments().is_empty());
assert!(declarative_type.to_value_assignments().is_empty());
assert!(declarative_type.clone().into_data_assignments().is_empty());
assert!(pedersan_type.to_declarative_assignments().is_empty());
assert!(pedersan_type.clone().into_data_assignments().is_empty());
assert!(hash_type.to_declarative_assignments().is_empty());
assert!(hash_type.clone().into_value_assignments().is_empty());
assert!(declarative_type.declarative_assignments_mut().is_some());
assert!(pedersan_type.value_assignments_mut().is_some());
assert!(hash_type.data_assignments_mut().is_some());
assert!(declarative_type.value_assignments_mut().is_none());
assert!(declarative_type.data_assignments_mut().is_none());
assert!(pedersan_type.declarative_assignments_mut().is_none());
assert!(pedersan_type.data_assignments_mut().is_none());
assert!(hash_type.declarative_assignments_mut().is_none());
assert!(hash_type.value_assignments_mut().is_none());
}
#[test]
#[ignore]
fn test_seal_extraction() {
let declarative_type = TypedAssignments::strict_decode(&DECLARATIVE_VARIANT[..]).unwrap();
let pedersan_type = TypedAssignments::strict_decode(&PEDERSAN_VARIANT[..]).unwrap();
let hash_type = TypedAssignments::strict_decode(&HASH_VARIANT[..]).unwrap();
let txid_1 = match declarative_type
.revealed_seal_at(2)
.unwrap()
.unwrap()
.outpoint()
{
Some(outpoint) => Some(outpoint.txid),
_ => None,
}
.unwrap()
.to_hex();
let txid_2 = match pedersan_type
.revealed_seal_at(0)
.unwrap()
.unwrap()
.outpoint()
{
Some(outpoint) => Some(outpoint.txid),
_ => None,
}
.unwrap()
.to_hex();
let txid_3 = match hash_type.revealed_seal_at(1).unwrap().unwrap().outpoint() {
Some(outpoint) => Some(outpoint.txid),
_ => None,
}
.unwrap()
.to_hex();
assert_eq!(txid_1, TXID_VEC[1]);
assert_eq!(txid_2, TXID_VEC[1]);
assert_eq!(txid_3, TXID_VEC[1]);
}
#[test]
#[ignore]
fn test_known_seals() {
let declarative_type = TypedAssignments::strict_decode(&DECLARATIVE_VARIANT[..]).unwrap();
let pedersan_type = TypedAssignments::strict_decode(&PEDERSAN_VARIANT[..]).unwrap();
let hash_type = TypedAssignments::strict_decode(&HASH_VARIANT[..]).unwrap();
let mut dec_txids: Vec<String> = declarative_type
.filter_revealed_seals()
.iter()
.map(|revealed| {
match revealed.outpoint() {
Some(outpoint) => Some(outpoint.txid),
_ => None,
}
.unwrap()
.to_hex()
})
.collect();
let mut ped_txids: Vec<String> = pedersan_type
.filter_revealed_seals()
.iter()
.map(|revealed| {
match revealed.outpoint() {
Some(outpoint) => Some(outpoint.txid),
_ => None,
}
.unwrap()
.to_hex()
})
.collect();
let mut hash_txids: Vec<String> = hash_type
.filter_revealed_seals()
.iter()
.map(|revealed| {
match revealed.outpoint() {
Some(outpoint) => Some(outpoint.txid),
_ => None,
}
.unwrap()
.to_hex()
})
.collect();
dec_txids.sort();
ped_txids.sort();
hash_txids.sort();
let mut sorted_txid = TXID_VEC[..2].to_vec().clone();
sorted_txid.sort();
assert_eq!(dec_txids, sorted_txid);
assert_eq!(ped_txids, sorted_txid);
assert_eq!(hash_txids, sorted_txid);
}
#[test]
#[ignore]
fn test_all_seals() {
let declarative_type = TypedAssignments::strict_decode(&DECLARATIVE_VARIANT[..]).unwrap();
let pedersan_type = TypedAssignments::strict_decode(&PEDERSAN_VARIANT[..]).unwrap();
let hash_type = TypedAssignments::strict_decode(&HASH_VARIANT[..]).unwrap();
let mut dec_hashes: Vec<String> = declarative_type
.to_confidential_seals()
.iter()
.map(|hash| hash.to_hex())
.collect();
let mut ped_hashes: Vec<String> = pedersan_type
.to_confidential_seals()
.iter()
.map(|hash| hash.to_hex())
.collect();
let mut hash_hashes: Vec<String> = hash_type
.to_confidential_seals()
.iter()
.map(|hash| hash.to_hex())
.collect();
dec_hashes.sort();
ped_hashes.sort();
hash_hashes.sort();
assert_eq!(dec_hashes, DECLARATIVE_OUTPOINT_HASH);
assert_eq!(ped_hashes, PEDERSAN_OUTPOINT_HASH);
assert_eq!(hash_hashes, HASH_OUTPOINT_HASH);
}
#[test]
#[ignore]
fn test_known_state_homomorphic() {
let declarative_type = TypedAssignments::strict_decode(&DECLARATIVE_VARIANT[..]).unwrap();
let pedersan_type = TypedAssignments::strict_decode(&PEDERSAN_VARIANT[..]).unwrap();
let hash_type = TypedAssignments::strict_decode(&HASH_VARIANT[..]).unwrap();
let states = pedersan_type.filter_revealed_state_values();
assert_eq!(states[0].value, 10);
assert_eq!(states[1].value, 30);
let blind_1: Vec<u8> =
Vec::from_hex("debbbefd1683e335296a0c86f1c882a2ea3759f114220b0b2cf869e37dec24c8")
.unwrap();
let blind_2: Vec<u8> =
Vec::from_hex("5d3574c4d99c08ef950619be72bfa1d50ae3c153d1f30f64bc1ac08de99ea556")
.unwrap();
assert_eq!(
SecretKey::from(states[0].blinding),
SecretKey::from_slice(&Secp256k1::new(), &blind_1[..]).unwrap()
);
assert_eq!(
SecretKey::from(states[1].blinding),
SecretKey::from_slice(&Secp256k1::new(), &blind_2[..]).unwrap()
);
assert_eq!(declarative_type.filter_revealed_state_values().len(), 0);
assert_eq!(hash_type.filter_revealed_state_values().len(), 0);
}
#[test]
#[ignore]
fn test_known_state_data() {
let declarative_type = TypedAssignments::strict_decode(&DECLARATIVE_VARIANT[..]).unwrap();
let pedersan_type = TypedAssignments::strict_decode(&PEDERSAN_VARIANT[..]).unwrap();
let hash_type = TypedAssignments::strict_decode(&HASH_VARIANT[..]).unwrap();
let data_set = hash_type.filter_revealed_state_data();
let data_1 = data::Revealed::Bytes(sha256::Hash::from_hex(STATE_DATA[2]).unwrap().to_vec());
let data_2 = data::Revealed::Bytes(sha256::Hash::from_hex(STATE_DATA[0]).unwrap().to_vec());
assert_eq!(data_set[0].to_owned(), data_1);
assert_eq!(data_set[1].to_owned(), data_2);
assert_eq!(declarative_type.filter_revealed_state_data().len(), 0);
assert_eq!(pedersan_type.filter_revealed_state_data().len(), 0);
}
#[test]
#[ignore]
fn test_all_state_pedersan() {
let declarative_type = TypedAssignments::strict_decode(&DECLARATIVE_VARIANT[..]).unwrap();
let pedersan_type = TypedAssignments::strict_decode(&PEDERSAN_VARIANT[..]).unwrap();
let hash_type = TypedAssignments::strict_decode(&HASH_VARIANT[..]).unwrap();
let conf_amounts = pedersan_type.to_confidential_state_pedersen();
assert_eq!(
conf_amounts[0].commitment,
Commitment::from_vec(
Vec::from_hex("08cc48fa5e5cb1d2d2465bd8c437c0e00514abd813f9a7dd506a778405a2c43bc0")
.unwrap()
)
);
assert_eq!(
conf_amounts[1].commitment,
Commitment::from_vec(
Vec::from_hex("091e1b9e7605fc214806f3af3eba13947b91f47bac729f5def5e8fbd530112bed1")
.unwrap()
)
);
assert_eq!(
conf_amounts[2].commitment,
Commitment::from_vec(
Vec::from_hex("089775f829c8adad92ada17b5931edf63064d54678f4eb9a6fdfe8e4cb5d95f6f4")
.unwrap()
)
);
assert_eq!(declarative_type.to_confidential_state_pedersen().len(), 0);
assert_eq!(hash_type.to_confidential_state_pedersen().len(), 0);
}
#[test]
#[ignore]
fn test_all_state_hashed() {
let declarative_type = TypedAssignments::strict_decode(&DECLARATIVE_VARIANT[..]).unwrap();
let pedersan_type = TypedAssignments::strict_decode(&PEDERSAN_VARIANT[..]).unwrap();
let hash_type = TypedAssignments::strict_decode(&HASH_VARIANT[..]).unwrap();
let extracted_states = hash_type.to_confidential_state_hashed();
let expected: [&str; 4] = [
"fa6eae3e74de3e5dd92f58ac753d02b613daaaab",
"6420cc421e1189805c8cec089d74c1980f79c069",
"43e446006c5bc93864dafb03cf4ba472bedf5ca7",
"69b01b4d96d00ceff2599eb089e4c7b979961fec",
];
assert_eq!(
extracted_states
.iter()
.map(|hash| hash.to_hex())
.collect::<Vec<String>>(),
expected
);
assert_eq!(declarative_type.to_confidential_state_hashed().len(), 0);
assert_eq!(pedersan_type.to_confidential_state_hashed().len(), 0);
}
#[test]
#[ignore]
fn test_conceal() {
let mut hash_type = TypedAssignments::strict_decode(&HASH_VARIANT[..]).unwrap();
assert_eq!(2, hash_type.conceal_state());
let known_txid: [&str; 2] = [
"f57ed27ee4199072c5ff3b774febc94d26d3e4a5559d133de4750a948df50e06",
"201fdd1e2b62d7b6938271295118ee181f1bac5e57d9f4528925650d36d3af8e",
];
let extracted_txid: Vec<String> = hash_type
.filter_revealed_seals()
.iter()
.map(|revealed| {
match revealed.outpoint() {
Some(outpoint) => Some(outpoint.txid),
_ => None,
}
.unwrap()
.to_hex()
})
.collect();
assert_eq!(known_txid.to_vec(), extracted_txid);
let all_seals_confidential: [&str; 4] = [
"7efe71b7a37a39da798774ca6b09def9724d81303892d55cac3edb0dc8340a3a",
"9565d29461c863e013c26d176a9929307286963322849a1dc6c978e5c70c8d52",
"dc0d0d7139a3ad6010a210e5900201979a1a09047b10a877688ee5a740ae215a",
"9b64a3024632f0517d8a608cb29902f7083eab0ac25d2827a5ef27e9a68b18f9",
];
let extracted_seals_confidential: Vec<String> = hash_type
.to_confidential_seals()
.iter()
.map(|hash| hash.to_hex())
.collect();
assert_eq!(
all_seals_confidential.to_vec(),
extracted_seals_confidential
);
let all_state_confidential = [
"fa6eae3e74de3e5dd92f58ac753d02b613daaaab",
"6420cc421e1189805c8cec089d74c1980f79c069",
"43e446006c5bc93864dafb03cf4ba472bedf5ca7",
"69b01b4d96d00ceff2599eb089e4c7b979961fec",
];
let extracted_state_confidential: Vec<String> = hash_type
.to_confidential_state_hashed()
.iter()
.map(|confidential| confidential.to_hex())
.collect();
assert_eq!(
all_state_confidential.to_vec(),
extracted_state_confidential
);
}
#[test]
#[ignore]
fn test_len() {
let declarative_type = TypedAssignments::strict_decode(&DECLARATIVE_VARIANT[..]).unwrap();
let pedersan_type = TypedAssignments::strict_decode(&PEDERSAN_VARIANT[..]).unwrap();
let hash_type = TypedAssignments::strict_decode(&HASH_VARIANT[..]).unwrap();
assert_eq!(declarative_type.len(), 4);
assert_eq!(pedersan_type.len(), 4);
assert_eq!(hash_type.len(), 4);
}
#[test]
fn test_encoding_ancestor() {
let _: ParentOwnedRights = test_vec_decoding_roundtrip(PARENT_RIGHTS).unwrap();
}
#[test]
#[should_panic(expected = "UnexpectedEof")]
fn test_garbage_ancestor() {
let mut data = PARENT_RIGHTS.clone();
data[0] = 0x36 as u8;
ParentOwnedRights::strict_decode(&data[..]).unwrap();
}
#[test]
fn test_parent_rights_encoding_simple() {
let mut assignment = BTreeMap::new();
let data = 0u16;
let ty = 2 as schema::OwnedRightType;
assignment.insert(ty, vec![data]);
let nodeid = NodeId::default();
let mut parent_rights = ParentOwnedRights::default();
parent_rights.as_mut().insert(nodeid, assignment);
let mut original_commit = vec![];
parent_rights
.to_merkle_source()
.commit_encode(&mut original_commit);
let mut encoded_leaf = vec![];
NodeId::default().strict_encode(&mut encoded_leaf).unwrap();
ty.strict_encode(&mut encoded_leaf).unwrap();
0u16.strict_encode(&mut encoded_leaf).unwrap();
let merkle_node = MerkleNode::hash(&encoded_leaf[..]);
let (root, _) = merklize("parent_owned_right", [merkle_node]);
let handmade_commit = root.commit_serialize();
assert_eq!(original_commit, handmade_commit);
}
#[test]
fn test_ancestor_encoding_complex() {
let mut vec1 = vec![];
let mut rng = thread_rng();
for i in 0..6 {
vec1.insert(i, rng.next_u64() as u16);
}
let mut vec2 = vec![];
let mut rng = thread_rng();
for i in 0..17 {
vec2.insert(i, rng.next_u64() as u16);
}
let mut vec3 = vec![];
let mut rng = thread_rng();
for i in 0..11 {
vec3.insert(i, rng.next_u64() as u16);
}
let type1 = 1 as schema::OwnedRightType;
let type2 = 2 as schema::OwnedRightType;
let type3 = 3 as schema::OwnedRightType;
let node_id = NodeId::default();
let mut assignments = BTreeMap::new();
assignments.insert(type1, vec1.clone());
assignments.insert(type2, vec2.clone());
assignments.insert(type3, vec3.clone());
let mut parent_rights = ParentOwnedRights::default();
parent_rights.as_mut().insert(node_id, assignments);
let mut original_commit = vec![];
parent_rights
.to_merkle_source()
.commit_encode(&mut original_commit);
let vec_1: Vec<(NodeId, schema::OwnedRightType, u16)> = vec1
.iter()
.map(|i| (NodeId::default(), type1, *i))
.collect();
let vec_2: Vec<(NodeId, schema::OwnedRightType, u16)> = vec2
.iter()
.map(|i| (NodeId::default(), type2, *i))
.collect();
let vec_3: Vec<(NodeId, schema::OwnedRightType, u16)> = vec3
.iter()
.map(|i| (NodeId::default(), type3, *i))
.collect();
let vec_4: Vec<(NodeId, schema::OwnedRightType, u16)> = [vec_1, vec_2, vec_3].concat();
let nodes: Vec<MerkleNode> = vec_4
.into_iter()
.map(|item| -> MerkleNode {
let mut e = vec![];
item.0.strict_encode(&mut e).unwrap();
item.1.strict_encode(&mut e).unwrap();
item.2.strict_encode(&mut e).unwrap();
MerkleNode::hash(&e[..])
})
.collect();
let (root, _) = merklize("parent_owned_right", nodes);
let handmade_commit = root.commit_serialize();
assert_eq!(original_commit, handmade_commit);
}
#[test]
fn test_commitencode_assignments() {
let mut rng = thread_rng();
let txid_vec: Vec<bitcoin::Txid> = TXID_VEC
.iter()
.map(|txid| bitcoin::Txid::from_hex(txid).unwrap())
.collect();
let assignment_1 = Assignment::<DeclarativeStrategy>::Revealed {
seal: Revealed::from(OutPoint::new(txid_vec[0], 1)),
state: data::Void(),
};
let assignment_2 = Assignment::<DeclarativeStrategy>::ConfidentialState {
seal: Revealed::from(OutPoint::new(txid_vec[1], 2)),
state: data::Void(),
};
let assignment_3 = Assignment::<DeclarativeStrategy>::ConfidentialSeal {
seal: Revealed::from(OutPoint::new(txid_vec[2], 3)).commit_conceal(),
state: data::Void(),
};
let assignment_4 = Assignment::<DeclarativeStrategy>::Confidential {
seal: Revealed::from(OutPoint::new(txid_vec[3], 4)).commit_conceal(),
state: data::Void(),
};
let mut set = Vec::new();
set.push(assignment_1);
set.push(assignment_2);
set.push(assignment_3);
set.push(assignment_4);
let declarative_variant = TypedAssignments::Void(set);
let txid_vec: Vec<bitcoin::Txid> = TXID_VEC
.iter()
.map(|txid| bitcoin::Txid::from_hex(txid).unwrap())
.collect();
let assignment_1 = Assignment::<PedersenStrategy>::Revealed {
seal: Revealed::from(OutPoint::new(txid_vec[0], 1)),
state: value::Revealed::with_amount(10u64, &mut rng),
};
let assignment_2 = Assignment::<PedersenStrategy>::ConfidentialState {
seal: Revealed::from(OutPoint::new(txid_vec[1], 1)),
state: value::Revealed::with_amount(20u64, &mut rng).commit_conceal(),
};
let assignment_3 = Assignment::<PedersenStrategy>::ConfidentialSeal {
seal: Revealed::from(OutPoint::new(txid_vec[2], 1)).commit_conceal(),
state: value::Revealed::with_amount(30u64, &mut rng),
};
let assignment_4 = Assignment::<PedersenStrategy>::Confidential {
seal: Revealed::from(OutPoint::new(txid_vec[3], 1)).commit_conceal(),
state: value::Revealed::with_amount(10u64, &mut rng).commit_conceal(),
};
let mut set = Vec::new();
set.push(assignment_1);
set.push(assignment_2);
set.push(assignment_3);
set.push(assignment_4);
let pedersen_variant = TypedAssignments::Value(set);
let txid_vec: Vec<bitcoin::Txid> = TXID_VEC
.iter()
.map(|txid| bitcoin::Txid::from_hex(txid).unwrap())
.collect();
let state_data_vec: Vec<data::Revealed> = STATE_DATA
.iter()
.map(|data| data::Revealed::Bytes(sha256::Hash::from_hex(data).unwrap().to_vec()))
.collect();
let assignment_1 = Assignment::<HashStrategy>::Revealed {
seal: Revealed::from(OutPoint::new(txid_vec[0], 1)),
state: state_data_vec[0].clone(),
};
let assignment_2 = Assignment::<HashStrategy>::ConfidentialState {
seal: Revealed::from(OutPoint::new(txid_vec[1], 1)),
state: state_data_vec[1].clone().commit_conceal(),
};
let assignment_3 = Assignment::<HashStrategy>::ConfidentialSeal {
seal: Revealed::from(OutPoint::new(txid_vec[2], 1)).commit_conceal(),
state: state_data_vec[2].clone(),
};
let assignment_4 = Assignment::<HashStrategy>::Confidential {
seal: Revealed::from(OutPoint::new(txid_vec[3], 1)).commit_conceal(),
state: state_data_vec[3].clone().commit_conceal(),
};
let mut set = Vec::new();
set.push(assignment_1);
set.push(assignment_2);
set.push(assignment_3);
set.push(assignment_4);
let hash_variant = TypedAssignments::Data(set);
let type1 = 1 as schema::OwnedRightType;
let type2 = 2 as schema::OwnedRightType;
let type3 = 3 as schema::OwnedRightType;
let mut owned_rights = OwnedRights::default();
owned_rights
.as_mut()
.insert(type1, declarative_variant.clone());
owned_rights
.as_mut()
.insert(type2, pedersen_variant.clone());
owned_rights.as_mut().insert(type3, hash_variant.clone());
let mut original_encoding = vec![];
owned_rights
.to_merkle_source()
.commit_encode(&mut original_encoding);
let declarative_leaves: Vec<(schema::OwnedRightType, MerkleNode)> = declarative_variant
.to_declarative_assignments()
.iter()
.map(|assignment| {
(
type1,
MerkleNode::hash(&CommitEncode::commit_serialize(assignment)),
)
})
.collect();
let pedersan_leaves: Vec<(schema::OwnedRightType, MerkleNode)> = pedersen_variant
.to_value_assignments()
.iter()
.map(|assignment| {
(
type2,
MerkleNode::hash(&CommitEncode::commit_serialize(assignment)),
)
})
.collect();
let hash_leaves: Vec<(schema::OwnedRightType, MerkleNode)> = hash_variant
.to_data_assignments()
.iter()
.map(|assignment| {
(
type3,
MerkleNode::hash(&CommitEncode::commit_serialize(assignment)),
)
})
.collect();
let all_leaves = [declarative_leaves, pedersan_leaves, hash_leaves].concat();
let nodes: Vec<MerkleNode> = all_leaves
.iter()
.map(|item| MerkleNode::hash(&CommitEncode::commit_serialize(item)))
.collect();
let (root, _) = merklize("owned_right", nodes);
let handmade_encoding = root.commit_serialize();
assert_eq!(original_encoding, handmade_encoding);
}
}