reth_trie_sparse/trie.rs
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 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
use crate::blinded::{BlindedProvider, DefaultBlindedProvider};
use alloy_primitives::{
hex, keccak256,
map::{Entry, HashMap, HashSet},
B256,
};
use alloy_rlp::Decodable;
use reth_execution_errors::{SparseTrieError, SparseTrieErrorKind, SparseTrieResult};
use reth_tracing::tracing::trace;
use reth_trie_common::{
prefix_set::{PrefixSet, PrefixSetMut},
BranchNodeCompact, BranchNodeRef, ExtensionNodeRef, LeafNodeRef, Nibbles, RlpNode, TrieMask,
TrieNode, CHILD_INDEX_RANGE, EMPTY_ROOT_HASH,
};
use smallvec::SmallVec;
use std::{borrow::Cow, fmt};
/// Inner representation of the sparse trie.
/// Sparse trie is blind by default until nodes are revealed.
#[derive(PartialEq, Eq)]
pub enum SparseTrie<P = DefaultBlindedProvider> {
/// None of the trie nodes are known.
Blind,
/// The trie nodes have been revealed.
Revealed(Box<RevealedSparseTrie<P>>),
}
impl<P> fmt::Debug for SparseTrie<P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Blind => write!(f, "Blind"),
Self::Revealed(revealed) => write!(f, "Revealed({revealed:?})"),
}
}
}
impl<P> Default for SparseTrie<P> {
fn default() -> Self {
Self::Blind
}
}
impl SparseTrie {
/// Creates new blind trie.
pub const fn blind() -> Self {
Self::Blind
}
/// Creates new revealed empty trie.
pub fn revealed_empty() -> Self {
Self::Revealed(Box::default())
}
/// Reveals the root node if the trie is blinded.
///
/// # Returns
///
/// Mutable reference to [`RevealedSparseTrie`].
pub fn reveal_root(
&mut self,
root: TrieNode,
hash_mask: Option<TrieMask>,
retain_updates: bool,
) -> SparseTrieResult<&mut RevealedSparseTrie> {
self.reveal_root_with_provider(Default::default(), root, hash_mask, retain_updates)
}
}
impl<P> SparseTrie<P> {
/// Returns `true` if the sparse trie has no revealed nodes.
pub const fn is_blind(&self) -> bool {
matches!(self, Self::Blind)
}
/// Returns mutable reference to revealed sparse trie if the trie is not blind.
pub fn as_revealed_mut(&mut self) -> Option<&mut RevealedSparseTrie<P>> {
if let Self::Revealed(revealed) = self {
Some(revealed)
} else {
None
}
}
/// Reveals the root node if the trie is blinded.
///
/// # Returns
///
/// Mutable reference to [`RevealedSparseTrie`].
pub fn reveal_root_with_provider(
&mut self,
provider: P,
root: TrieNode,
hash_mask: Option<TrieMask>,
retain_updates: bool,
) -> SparseTrieResult<&mut RevealedSparseTrie<P>> {
if self.is_blind() {
*self = Self::Revealed(Box::new(RevealedSparseTrie::from_provider_and_root(
provider,
root,
hash_mask,
retain_updates,
)?))
}
Ok(self.as_revealed_mut().unwrap())
}
/// Wipe the trie, removing all values and nodes, and replacing the root with an empty node.
pub fn wipe(&mut self) -> SparseTrieResult<()> {
let revealed = self.as_revealed_mut().ok_or(SparseTrieErrorKind::Blind)?;
revealed.wipe();
Ok(())
}
/// Calculates and returns the trie root if the trie has been revealed.
pub fn root(&mut self) -> Option<B256> {
Some(self.as_revealed_mut()?.root())
}
/// Calculates the hashes of the nodes below the provided level.
pub fn calculate_below_level(&mut self, level: usize) {
self.as_revealed_mut().unwrap().update_rlp_node_level(level);
}
}
impl<P> SparseTrie<P>
where
P: BlindedProvider,
SparseTrieError: From<P::Error>,
{
/// Update the leaf node.
pub fn update_leaf(&mut self, path: Nibbles, value: Vec<u8>) -> SparseTrieResult<()> {
let revealed = self.as_revealed_mut().ok_or(SparseTrieErrorKind::Blind)?;
revealed.update_leaf(path, value)?;
Ok(())
}
/// Remove the leaf node.
pub fn remove_leaf(&mut self, path: &Nibbles) -> SparseTrieResult<()> {
let revealed = self.as_revealed_mut().ok_or(SparseTrieErrorKind::Blind)?;
revealed.remove_leaf(path)?;
Ok(())
}
}
/// The representation of revealed sparse trie.
///
/// ## Invariants
///
/// - The root node is always present in `nodes` collection.
/// - Each leaf entry in `nodes` collection must have a corresponding entry in `values` collection.
/// The opposite is also true.
/// - All keys in `values` collection are full leaf paths.
#[derive(Clone, PartialEq, Eq)]
pub struct RevealedSparseTrie<P = DefaultBlindedProvider> {
/// Blinded node provider.
provider: P,
/// All trie nodes.
nodes: HashMap<Nibbles, SparseNode>,
/// All branch node hash masks.
branch_node_hash_masks: HashMap<Nibbles, TrieMask>,
/// All leaf values.
values: HashMap<Nibbles, Vec<u8>>,
/// Prefix set.
prefix_set: PrefixSetMut,
/// Retained trie updates.
updates: Option<SparseTrieUpdates>,
/// Reusable buffer for RLP encoding of nodes.
rlp_buf: Vec<u8>,
}
impl<P> fmt::Debug for RevealedSparseTrie<P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RevealedSparseTrie")
.field("nodes", &self.nodes)
.field("branch_hash_masks", &self.branch_node_hash_masks)
.field("values", &self.values)
.field("prefix_set", &self.prefix_set)
.field("updates", &self.updates)
.field("rlp_buf", &hex::encode(&self.rlp_buf))
.finish_non_exhaustive()
}
}
impl Default for RevealedSparseTrie {
fn default() -> Self {
Self {
provider: Default::default(),
nodes: HashMap::from_iter([(Nibbles::default(), SparseNode::Empty)]),
branch_node_hash_masks: HashMap::default(),
values: HashMap::default(),
prefix_set: PrefixSetMut::default(),
updates: None,
rlp_buf: Vec::new(),
}
}
}
impl RevealedSparseTrie {
/// Create new revealed sparse trie from the given root node.
pub fn from_root(
node: TrieNode,
hash_mask: Option<TrieMask>,
retain_updates: bool,
) -> SparseTrieResult<Self> {
let mut this = Self {
provider: Default::default(),
nodes: HashMap::default(),
branch_node_hash_masks: HashMap::default(),
values: HashMap::default(),
prefix_set: PrefixSetMut::default(),
rlp_buf: Vec::new(),
updates: None,
}
.with_updates(retain_updates);
this.reveal_node(Nibbles::default(), node, hash_mask)?;
Ok(this)
}
}
impl<P> RevealedSparseTrie<P> {
/// Create new revealed sparse trie from the given root node.
pub fn from_provider_and_root(
provider: P,
node: TrieNode,
hash_mask: Option<TrieMask>,
retain_updates: bool,
) -> SparseTrieResult<Self> {
let mut this = Self {
provider,
nodes: HashMap::default(),
branch_node_hash_masks: HashMap::default(),
values: HashMap::default(),
prefix_set: PrefixSetMut::default(),
rlp_buf: Vec::new(),
updates: None,
}
.with_updates(retain_updates);
this.reveal_node(Nibbles::default(), node, hash_mask)?;
Ok(this)
}
/// Set new blinded node provider on sparse trie.
pub fn with_provider<BP>(self, provider: BP) -> RevealedSparseTrie<BP> {
RevealedSparseTrie {
provider,
nodes: self.nodes,
branch_node_hash_masks: self.branch_node_hash_masks,
values: self.values,
prefix_set: self.prefix_set,
updates: self.updates,
rlp_buf: self.rlp_buf,
}
}
/// Set the retention of branch node updates and deletions.
pub fn with_updates(mut self, retain_updates: bool) -> Self {
if retain_updates {
self.updates = Some(SparseTrieUpdates::default());
}
self
}
/// Returns a reference to the retained sparse node updates without taking them.
pub fn updates_ref(&self) -> Cow<'_, SparseTrieUpdates> {
self.updates.as_ref().map_or(Cow::Owned(SparseTrieUpdates::default()), Cow::Borrowed)
}
/// Returns a reference to the leaf value if present.
pub fn get_leaf_value(&self, path: &Nibbles) -> Option<&Vec<u8>> {
self.values.get(path)
}
/// Takes and returns the retained sparse node updates
pub fn take_updates(&mut self) -> SparseTrieUpdates {
self.updates.take().unwrap_or_default()
}
/// Reveal the trie node only if it was not known already.
pub fn reveal_node(
&mut self,
path: Nibbles,
node: TrieNode,
hash_mask: Option<TrieMask>,
) -> SparseTrieResult<()> {
if let Some(hash_mask) = hash_mask {
self.branch_node_hash_masks.insert(path.clone(), hash_mask);
}
match node {
TrieNode::EmptyRoot => {
debug_assert!(path.is_empty());
self.nodes.insert(path, SparseNode::Empty);
}
TrieNode::Branch(branch) => {
let mut stack_ptr = branch.as_ref().first_child_index();
for idx in CHILD_INDEX_RANGE {
if branch.state_mask.is_bit_set(idx) {
let mut child_path = path.clone();
child_path.push_unchecked(idx);
self.reveal_node_or_hash(child_path, &branch.stack[stack_ptr])?;
stack_ptr += 1;
}
}
match self.nodes.entry(path) {
Entry::Occupied(mut entry) => match entry.get() {
// Blinded nodes can be replaced.
SparseNode::Hash(hash) => {
entry.insert(SparseNode::Branch {
state_mask: branch.state_mask,
// Memoize the hash of a previously blinded node in a new branch
// node.
hash: Some(*hash),
store_in_db_trie: None,
});
}
// Branch node already exists, or an extension node was placed where a
// branch node was before.
SparseNode::Branch { .. } | SparseNode::Extension { .. } => {}
// All other node types can't be handled.
node @ (SparseNode::Empty | SparseNode::Leaf { .. }) => {
return Err(SparseTrieErrorKind::Reveal {
path: entry.key().clone(),
node: Box::new(node.clone()),
}
.into())
}
},
Entry::Vacant(entry) => {
entry.insert(SparseNode::new_branch(branch.state_mask));
}
}
}
TrieNode::Extension(ext) => match self.nodes.entry(path) {
Entry::Occupied(mut entry) => match entry.get() {
SparseNode::Hash(hash) => {
let mut child_path = entry.key().clone();
child_path.extend_from_slice_unchecked(&ext.key);
entry.insert(SparseNode::Extension {
key: ext.key,
// Memoize the hash of a previously blinded node in a new extension
// node.
hash: Some(*hash),
});
self.reveal_node_or_hash(child_path, &ext.child)?;
}
// Extension node already exists, or an extension node was placed where a branch
// node was before.
SparseNode::Extension { .. } | SparseNode::Branch { .. } => {}
// All other node types can't be handled.
node @ (SparseNode::Empty | SparseNode::Leaf { .. }) => {
return Err(SparseTrieErrorKind::Reveal {
path: entry.key().clone(),
node: Box::new(node.clone()),
}
.into())
}
},
Entry::Vacant(entry) => {
let mut child_path = entry.key().clone();
child_path.extend_from_slice_unchecked(&ext.key);
entry.insert(SparseNode::new_ext(ext.key));
self.reveal_node_or_hash(child_path, &ext.child)?;
}
},
TrieNode::Leaf(leaf) => match self.nodes.entry(path) {
Entry::Occupied(mut entry) => match entry.get() {
SparseNode::Hash(hash) => {
let mut full = entry.key().clone();
full.extend_from_slice_unchecked(&leaf.key);
self.values.insert(full, leaf.value);
entry.insert(SparseNode::Leaf {
key: leaf.key,
// Memoize the hash of a previously blinded node in a new leaf
// node.
hash: Some(*hash),
});
}
// Left node already exists.
SparseNode::Leaf { .. } => {}
// All other node types can't be handled.
node @ (SparseNode::Empty |
SparseNode::Extension { .. } |
SparseNode::Branch { .. }) => {
return Err(SparseTrieErrorKind::Reveal {
path: entry.key().clone(),
node: Box::new(node.clone()),
}
.into())
}
},
Entry::Vacant(entry) => {
let mut full = entry.key().clone();
full.extend_from_slice_unchecked(&leaf.key);
entry.insert(SparseNode::new_leaf(leaf.key));
self.values.insert(full, leaf.value);
}
},
}
Ok(())
}
fn reveal_node_or_hash(&mut self, path: Nibbles, child: &[u8]) -> SparseTrieResult<()> {
if child.len() == B256::len_bytes() + 1 {
let hash = B256::from_slice(&child[1..]);
match self.nodes.entry(path) {
Entry::Occupied(entry) => match entry.get() {
// Hash node with a different hash can't be handled.
SparseNode::Hash(previous_hash) if previous_hash != &hash => {
return Err(SparseTrieErrorKind::Reveal {
path: entry.key().clone(),
node: Box::new(SparseNode::Hash(hash)),
}
.into())
}
_ => {}
},
Entry::Vacant(entry) => {
entry.insert(SparseNode::Hash(hash));
}
}
return Ok(())
}
self.reveal_node(path, TrieNode::decode(&mut &child[..])?, None)
}
/// Traverse trie nodes down to the leaf node and collect all nodes along the path.
fn take_nodes_for_path(&mut self, path: &Nibbles) -> SparseTrieResult<Vec<RemovedSparseNode>> {
let mut current = Nibbles::default(); // Start traversal from the root
let mut nodes = Vec::new(); // Collect traversed nodes
while let Some(node) = self.nodes.remove(¤t) {
match &node {
SparseNode::Empty => return Err(SparseTrieErrorKind::Blind.into()),
&SparseNode::Hash(hash) => {
return Err(SparseTrieErrorKind::BlindedNode { path: current, hash }.into())
}
SparseNode::Leaf { key: _key, .. } => {
// Leaf node is always the one that we're deleting, and no other leaf nodes can
// be found during traversal.
#[cfg(debug_assertions)]
{
let mut current = current.clone();
current.extend_from_slice_unchecked(_key);
assert_eq!(¤t, path);
}
nodes.push(RemovedSparseNode {
path: current.clone(),
node,
unset_branch_nibble: None,
});
break
}
SparseNode::Extension { key, .. } => {
#[cfg(debug_assertions)]
{
let mut current = current.clone();
current.extend_from_slice_unchecked(key);
assert!(
path.starts_with(¤t),
"path: {:?}, current: {:?}, key: {:?}",
path,
current,
key
);
}
let path = current.clone();
current.extend_from_slice_unchecked(key);
nodes.push(RemovedSparseNode { path, node, unset_branch_nibble: None });
}
SparseNode::Branch { state_mask, .. } => {
let nibble = path[current.len()];
debug_assert!(
state_mask.is_bit_set(nibble),
"current: {:?}, path: {:?}, nibble: {:?}, state_mask: {:?}",
current,
path,
nibble,
state_mask
);
// If the branch node has a child that is a leaf node that we're removing,
// we need to unset this nibble.
// Any other branch nodes will not require unsetting the nibble, because
// deleting one leaf node can not remove the whole path
// where the branch node is located.
let mut child_path =
Nibbles::from_nibbles([current.as_slice(), &[nibble]].concat());
let unset_branch_nibble = self
.nodes
.get(&child_path)
.is_some_and(move |node| match node {
SparseNode::Leaf { key, .. } => {
// Get full path of the leaf node
child_path.extend_from_slice_unchecked(key);
&child_path == path
}
_ => false,
})
.then_some(nibble);
nodes.push(RemovedSparseNode {
path: current.clone(),
node,
unset_branch_nibble,
});
current.push_unchecked(nibble);
}
}
}
Ok(nodes)
}
/// Wipe the trie, removing all values and nodes, and replacing the root with an empty node.
pub fn wipe(&mut self) {
self.nodes = HashMap::from_iter([(Nibbles::default(), SparseNode::Empty)]);
self.values = HashMap::default();
self.prefix_set = PrefixSetMut::all();
self.updates = self.updates.is_some().then(SparseTrieUpdates::wiped);
}
/// Return the root of the sparse trie.
/// Updates all remaining dirty nodes before calculating the root.
pub fn root(&mut self) -> B256 {
// take the current prefix set.
let mut prefix_set = std::mem::take(&mut self.prefix_set).freeze();
let rlp_node = self.rlp_node_allocate(Nibbles::default(), &mut prefix_set);
if let Some(root_hash) = rlp_node.as_hash() {
root_hash
} else {
keccak256(rlp_node)
}
}
/// Update hashes of the nodes that are located at a level deeper than or equal to the provided
/// depth. Root node has a level of 0.
pub fn update_rlp_node_level(&mut self, depth: usize) {
let mut prefix_set = self.prefix_set.clone().freeze();
let mut buffers = RlpNodeBuffers::default();
let targets = self.get_changed_nodes_at_depth(&mut prefix_set, depth);
for target in targets {
buffers.path_stack.push((target, Some(true)));
self.rlp_node(&mut prefix_set, &mut buffers);
}
}
/// Returns a list of paths to the nodes that were changed according to the prefix set and are
/// located at the provided depth when counting from the root node. If there's a leaf at a
/// depth less than the provided depth, it will be included in the result.
fn get_changed_nodes_at_depth(&self, prefix_set: &mut PrefixSet, depth: usize) -> Vec<Nibbles> {
let mut paths = Vec::from([(Nibbles::default(), 0)]);
let mut targets = Vec::new();
while let Some((mut path, level)) = paths.pop() {
match self.nodes.get(&path).unwrap() {
SparseNode::Empty | SparseNode::Hash(_) => {}
SparseNode::Leaf { hash, .. } => {
if hash.is_some() && !prefix_set.contains(&path) {
continue
}
targets.push(path);
}
SparseNode::Extension { key, hash } => {
if hash.is_some() && !prefix_set.contains(&path) {
continue
}
if level >= depth {
targets.push(path);
} else {
path.extend_from_slice_unchecked(key);
paths.push((path, level + 1));
}
}
SparseNode::Branch { state_mask, hash, .. } => {
if hash.is_some() && !prefix_set.contains(&path) {
continue
}
if level >= depth {
targets.push(path);
} else {
for bit in CHILD_INDEX_RANGE.rev() {
if state_mask.is_bit_set(bit) {
let mut child_path = path.clone();
child_path.push_unchecked(bit);
paths.push((child_path, level + 1));
}
}
}
}
}
}
targets
}
fn rlp_node_allocate(&mut self, path: Nibbles, prefix_set: &mut PrefixSet) -> RlpNode {
let mut buffers = RlpNodeBuffers::new_with_path(path);
self.rlp_node(prefix_set, &mut buffers)
}
fn rlp_node(&mut self, prefix_set: &mut PrefixSet, buffers: &mut RlpNodeBuffers) -> RlpNode {
'main: while let Some((path, mut is_in_prefix_set)) = buffers.path_stack.pop() {
// Check if the path is in the prefix set.
// First, check the cached value. If it's `None`, then check the prefix set, and update
// the cached value.
let mut prefix_set_contains =
|path: &Nibbles| *is_in_prefix_set.get_or_insert_with(|| prefix_set.contains(path));
let (rlp_node, calculated, node_type) = match self.nodes.get_mut(&path).unwrap() {
SparseNode::Empty => {
(RlpNode::word_rlp(&EMPTY_ROOT_HASH), false, SparseNodeType::Empty)
}
SparseNode::Hash(hash) => (RlpNode::word_rlp(hash), false, SparseNodeType::Hash),
SparseNode::Leaf { key, hash } => {
let mut path = path.clone();
path.extend_from_slice_unchecked(key);
if let Some(hash) = hash.filter(|_| !prefix_set_contains(&path)) {
(RlpNode::word_rlp(&hash), false, SparseNodeType::Leaf)
} else {
let value = self.values.get(&path).unwrap();
self.rlp_buf.clear();
let rlp_node = LeafNodeRef { key, value }.rlp(&mut self.rlp_buf);
*hash = rlp_node.as_hash();
(rlp_node, true, SparseNodeType::Leaf)
}
}
SparseNode::Extension { key, hash } => {
let mut child_path = path.clone();
child_path.extend_from_slice_unchecked(key);
if let Some(hash) = hash.filter(|_| !prefix_set_contains(&path)) {
(
RlpNode::word_rlp(&hash),
false,
SparseNodeType::Extension { store_in_db_trie: true },
)
} else if buffers.rlp_node_stack.last().is_some_and(|e| e.0 == child_path) {
let (_, child, _, node_type) = buffers.rlp_node_stack.pop().unwrap();
self.rlp_buf.clear();
let rlp_node = ExtensionNodeRef::new(key, &child).rlp(&mut self.rlp_buf);
*hash = rlp_node.as_hash();
(
rlp_node,
true,
SparseNodeType::Extension {
// Inherit the `store_in_db_trie` flag from the child node, which is
// always the branch node
store_in_db_trie: node_type.store_in_db_trie(),
},
)
} else {
// need to get rlp node for child first
buffers.path_stack.extend([(path, is_in_prefix_set), (child_path, None)]);
continue
}
}
SparseNode::Branch { state_mask, hash, store_in_db_trie } => {
if let Some((hash, store_in_db_trie)) =
hash.zip(*store_in_db_trie).filter(|_| !prefix_set_contains(&path))
{
buffers.rlp_node_stack.push((
path,
RlpNode::word_rlp(&hash),
false,
SparseNodeType::Branch { store_in_db_trie },
));
continue
}
let retain_updates = self.updates.is_some() && prefix_set_contains(&path);
buffers.branch_child_buf.clear();
// Walk children in a reverse order from `f` to `0`, so we pop the `0` first
// from the stack and keep walking in the sorted order.
for bit in CHILD_INDEX_RANGE.rev() {
if state_mask.is_bit_set(bit) {
let mut child = path.clone();
child.push_unchecked(bit);
buffers.branch_child_buf.push(child);
}
}
buffers
.branch_value_stack_buf
.resize(buffers.branch_child_buf.len(), Default::default());
let mut added_children = false;
// TODO(alexey): set the `TrieMask` bits directly
let mut tree_mask_values = Vec::new();
let mut hash_mask_values = Vec::new();
let mut hashes = Vec::new();
for (i, child_path) in buffers.branch_child_buf.iter().enumerate() {
if buffers.rlp_node_stack.last().is_some_and(|e| &e.0 == child_path) {
let (_, child, calculated, node_type) =
buffers.rlp_node_stack.pop().unwrap();
// Update the masks only if we need to retain trie updates
if retain_updates {
// Set the trie mask
let tree_mask_value = if node_type.store_in_db_trie() {
// A branch or an extension node explicitly set the
// `store_in_db_trie` flag
true
} else {
// Set the flag according to whether a child node was
// pre-calculated (`calculated = false`), meaning that it wasn't
// in the database
!calculated
};
tree_mask_values.push(tree_mask_value);
// Set the hash mask. If a child node is a revealed branch node OR
// is a blinded node that has its hash mask bit set according to the
// database, set the hash mask bit and save the hash.
let hash = child.as_hash().filter(|_| {
node_type.is_branch() ||
(node_type.is_hash() &&
self.branch_node_hash_masks
.get(&path)
.is_some_and(|mask| {
mask.is_bit_set(child_path.last().unwrap())
}))
});
let hash_mask_value = hash.is_some();
hash_mask_values.push(hash_mask_value);
if let Some(hash) = hash {
hashes.push(hash);
}
trace!(
target: "trie::sparse",
?path,
?child_path,
?tree_mask_value,
?hash_mask_value,
"Updating branch node child masks"
);
}
// Insert children in the resulting buffer in a normal order,
// because initially we iterated in reverse.
buffers.branch_value_stack_buf
[buffers.branch_child_buf.len() - i - 1] = child;
added_children = true;
} else {
debug_assert!(!added_children);
buffers.path_stack.push((path, is_in_prefix_set));
buffers
.path_stack
.extend(buffers.branch_child_buf.drain(..).map(|p| (p, None)));
continue 'main
}
}
self.rlp_buf.clear();
let branch_node_ref =
BranchNodeRef::new(&buffers.branch_value_stack_buf, *state_mask);
let rlp_node = branch_node_ref.rlp(&mut self.rlp_buf);
*hash = rlp_node.as_hash();
// Save a branch node update only if it's not a root node, and we need to
// persist updates.
let store_in_db_trie_value = if let Some(updates) =
self.updates.as_mut().filter(|_| retain_updates && !path.is_empty())
{
let mut tree_mask_values = tree_mask_values.into_iter().rev();
let mut hash_mask_values = hash_mask_values.into_iter().rev();
let mut tree_mask = TrieMask::default();
let mut hash_mask = TrieMask::default();
for (i, child) in branch_node_ref.children() {
if child.is_some() {
if hash_mask_values.next().unwrap() {
hash_mask.set_bit(i);
}
if tree_mask_values.next().unwrap() {
tree_mask.set_bit(i);
}
}
}
// Store in DB trie if there are either any children that are stored in the
// DB trie, or any children represent hashed values
let store_in_db_trie = !tree_mask.is_empty() || !hash_mask.is_empty();
if store_in_db_trie {
hashes.reverse();
let branch_node = BranchNodeCompact::new(
*state_mask,
tree_mask,
hash_mask,
hashes,
hash.filter(|_| path.len() == 0),
);
updates.updated_nodes.insert(path.clone(), branch_node);
}
store_in_db_trie
} else {
false
};
*store_in_db_trie = Some(store_in_db_trie_value);
(
rlp_node,
true,
SparseNodeType::Branch { store_in_db_trie: store_in_db_trie_value },
)
}
};
buffers.rlp_node_stack.push((path, rlp_node, calculated, node_type));
}
debug_assert_eq!(buffers.rlp_node_stack.len(), 1);
buffers.rlp_node_stack.pop().unwrap().1
}
}
impl<P> RevealedSparseTrie<P>
where
P: BlindedProvider,
SparseTrieError: From<P::Error>,
{
/// Update the leaf node with provided value.
pub fn update_leaf(&mut self, path: Nibbles, value: Vec<u8>) -> SparseTrieResult<()> {
self.prefix_set.insert(path.clone());
let existing = self.values.insert(path.clone(), value);
if existing.is_some() {
// trie structure unchanged, return immediately
return Ok(())
}
let mut current = Nibbles::default();
while let Some(node) = self.nodes.get_mut(¤t) {
match node {
SparseNode::Empty => {
*node = SparseNode::new_leaf(path);
break
}
&mut SparseNode::Hash(hash) => {
return Err(SparseTrieErrorKind::BlindedNode { path: current, hash }.into())
}
SparseNode::Leaf { key: current_key, .. } => {
current.extend_from_slice_unchecked(current_key);
// this leaf is being updated
if current == path {
unreachable!("we already checked leaf presence in the beginning");
}
// find the common prefix
let common = current.common_prefix_length(&path);
// update existing node
let new_ext_key = current.slice(current.len() - current_key.len()..common);
*node = SparseNode::new_ext(new_ext_key);
// create a branch node and corresponding leaves
self.nodes.reserve(3);
self.nodes.insert(
current.slice(..common),
SparseNode::new_split_branch(current[common], path[common]),
);
self.nodes.insert(
path.slice(..=common),
SparseNode::new_leaf(path.slice(common + 1..)),
);
self.nodes.insert(
current.slice(..=common),
SparseNode::new_leaf(current.slice(common + 1..)),
);
break;
}
SparseNode::Extension { key, .. } => {
current.extend_from_slice(key);
if !path.starts_with(¤t) {
// find the common prefix
let common = current.common_prefix_length(&path);
*key = current.slice(current.len() - key.len()..common);
// If branch node updates retention is enabled, we need to query the
// extension node child to later set the hash mask for a parent branch node
// correctly.
if self.updates.is_some() {
// Check if the extension node child is a hash that needs to be revealed
if self.nodes.get(¤t).unwrap().is_hash() {
if let Some(node) = self.provider.blinded_node(¤t)? {
let decoded = TrieNode::decode(&mut &node[..])?;
trace!(target: "trie::sparse", ?current, ?decoded, "Revealing extension node child");
// We'll never have to update the revealed child node, only
// remove or do nothing, so
// we can safely ignore the hash mask here and
// pass `None`.
self.reveal_node(current.clone(), decoded, None)?;
}
}
}
// create state mask for new branch node
// NOTE: this might overwrite the current extension node
self.nodes.reserve(3);
let branch = SparseNode::new_split_branch(current[common], path[common]);
self.nodes.insert(current.slice(..common), branch);
// create new leaf
let new_leaf = SparseNode::new_leaf(path.slice(common + 1..));
self.nodes.insert(path.slice(..=common), new_leaf);
// recreate extension to previous child if needed
let key = current.slice(common + 1..);
if !key.is_empty() {
self.nodes.insert(current.slice(..=common), SparseNode::new_ext(key));
}
break;
}
}
SparseNode::Branch { state_mask, .. } => {
let nibble = path[current.len()];
current.push_unchecked(nibble);
if !state_mask.is_bit_set(nibble) {
state_mask.set_bit(nibble);
let new_leaf = SparseNode::new_leaf(path.slice(current.len()..));
self.nodes.insert(current, new_leaf);
break;
}
}
};
}
Ok(())
}
/// Remove leaf node from the trie.
pub fn remove_leaf(&mut self, path: &Nibbles) -> SparseTrieResult<()> {
if self.values.remove(path).is_none() {
if let Some(&SparseNode::Hash(hash)) = self.nodes.get(path) {
// Leaf is present in the trie, but it's blinded.
return Err(SparseTrieErrorKind::BlindedNode { path: path.clone(), hash }.into())
}
// Leaf is not present in the trie.
return Ok(())
}
self.prefix_set.insert(path.clone());
// If the path wasn't present in `values`, we still need to walk the trie and ensure that
// there is no node at the path. When a leaf node is a blinded `Hash`, it will have an entry
// in `nodes`, but not in the `values`.
let mut removed_nodes = self.take_nodes_for_path(path)?;
trace!(target: "trie::sparse", ?path, ?removed_nodes, "Removed nodes for path");
// Pop the first node from the stack which is the leaf node we want to remove.
let mut child = removed_nodes.pop().expect("leaf exists");
#[cfg(debug_assertions)]
{
let mut child_path = child.path.clone();
let SparseNode::Leaf { key, .. } = &child.node else { panic!("expected leaf node") };
child_path.extend_from_slice_unchecked(key);
assert_eq!(&child_path, path);
}
// If we don't have any other removed nodes, insert an empty node at the root.
if removed_nodes.is_empty() {
debug_assert!(self.nodes.is_empty());
self.nodes.insert(Nibbles::default(), SparseNode::Empty);
return Ok(())
}
// Walk the stack of removed nodes from the back and re-insert them back into the trie,
// adjusting the node type as needed.
while let Some(removed_node) = removed_nodes.pop() {
let removed_path = removed_node.path;
let new_node = match &removed_node.node {
SparseNode::Empty => return Err(SparseTrieErrorKind::Blind.into()),
&SparseNode::Hash(hash) => {
return Err(SparseTrieErrorKind::BlindedNode { path: removed_path, hash }.into())
}
SparseNode::Leaf { .. } => {
unreachable!("we already popped the leaf node")
}
SparseNode::Extension { key, .. } => {
// If the node is an extension node, we need to look at its child to see if we
// need to merge them.
match &child.node {
SparseNode::Empty => return Err(SparseTrieErrorKind::Blind.into()),
&SparseNode::Hash(hash) => {
return Err(
SparseTrieErrorKind::BlindedNode { path: child.path, hash }.into()
)
}
// For a leaf node, we collapse the extension node into a leaf node,
// extending the key. While it's impossible to encounter an extension node
// followed by a leaf node in a complete trie, it's possible here because we
// could have downgraded the extension node's child into a leaf node from
// another node type.
SparseNode::Leaf { key: leaf_key, .. } => {
self.nodes.remove(&child.path);
let mut new_key = key.clone();
new_key.extend_from_slice_unchecked(leaf_key);
SparseNode::new_leaf(new_key)
}
// For an extension node, we collapse them into one extension node,
// extending the key
SparseNode::Extension { key: extension_key, .. } => {
self.nodes.remove(&child.path);
let mut new_key = key.clone();
new_key.extend_from_slice_unchecked(extension_key);
SparseNode::new_ext(new_key)
}
// For a branch node, we just leave the extension node as-is.
SparseNode::Branch { .. } => removed_node.node,
}
}
SparseNode::Branch { mut state_mask, hash: _, store_in_db_trie: _ } => {
// If the node is a branch node, we need to check the number of children left
// after deleting the child at the given nibble.
if let Some(removed_nibble) = removed_node.unset_branch_nibble {
state_mask.unset_bit(removed_nibble);
}
// If only one child is left set in the branch node, we need to collapse it.
if state_mask.count_bits() == 1 {
let child_nibble =
state_mask.first_set_bit_index().expect("state mask is not empty");
// Get full path of the only child node left.
let mut child_path = removed_path.clone();
child_path.push_unchecked(child_nibble);
trace!(target: "trie::sparse", ?removed_path, ?child_path, ?child, "Branch node has only one child");
if self.nodes.get(&child_path).unwrap().is_hash() {
trace!(target: "trie::sparse", ?child_path, "Retrieving remaining blinded branch child");
if let Some(node) = self.provider.blinded_node(&child_path)? {
let decoded = TrieNode::decode(&mut &node[..])?;
trace!(target: "trie::sparse", ?child_path, ?decoded, "Revealing remaining blinded branch child");
// We'll never have to update the revealed branch node, only remove
// or do nothing, so we can safely ignore the hash mask here and
// pass `None`.
self.reveal_node(child_path.clone(), decoded, None)?;
}
}
// Get the only child node.
let child = self.nodes.get(&child_path).unwrap();
let mut delete_child = false;
let new_node = match child {
SparseNode::Empty => return Err(SparseTrieErrorKind::Blind.into()),
&SparseNode::Hash(hash) => {
return Err(SparseTrieErrorKind::BlindedNode {
path: child_path,
hash,
}
.into())
}
// If the only child is a leaf node, we downgrade the branch node into a
// leaf node, prepending the nibble to the key, and delete the old
// child.
SparseNode::Leaf { key, .. } => {
delete_child = true;
let mut new_key = Nibbles::from_nibbles_unchecked([child_nibble]);
new_key.extend_from_slice_unchecked(key);
SparseNode::new_leaf(new_key)
}
// If the only child node is an extension node, we downgrade the branch
// node into an even longer extension node, prepending the nibble to the
// key, and delete the old child.
SparseNode::Extension { key, .. } => {
delete_child = true;
let mut new_key = Nibbles::from_nibbles_unchecked([child_nibble]);
new_key.extend_from_slice_unchecked(key);
SparseNode::new_ext(new_key)
}
// If the only child is a branch node, we downgrade the current branch
// node into a one-nibble extension node.
SparseNode::Branch { .. } => {
SparseNode::new_ext(Nibbles::from_nibbles_unchecked([child_nibble]))
}
};
if delete_child {
self.nodes.remove(&child_path);
}
if let Some(updates) = self.updates.as_mut() {
updates.removed_nodes.insert(removed_path.clone());
}
new_node
}
// If more than one child is left set in the branch, we just re-insert it
// as-is.
else {
SparseNode::new_branch(state_mask)
}
}
};
child = RemovedSparseNode {
path: removed_path.clone(),
node: new_node.clone(),
unset_branch_nibble: None,
};
trace!(target: "trie::sparse", ?removed_path, ?new_node, "Re-inserting the node");
self.nodes.insert(removed_path, new_node);
}
Ok(())
}
}
/// Enum representing sparse trie node type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SparseNodeType {
/// Empty trie node.
Empty,
/// The hash of the node that was not revealed.
Hash,
/// Sparse leaf node.
Leaf,
/// Sparse extension node.
Extension {
/// A flag indicating whether the extension node should be stored in the database.
store_in_db_trie: bool,
},
/// Sparse branch node.
Branch {
/// A flag indicating whether the branch node should be stored in the database.
store_in_db_trie: bool,
},
}
impl SparseNodeType {
const fn is_hash(&self) -> bool {
matches!(self, Self::Hash)
}
const fn is_branch(&self) -> bool {
matches!(self, Self::Branch { .. })
}
const fn store_in_db_trie(&self) -> bool {
match *self {
Self::Extension { store_in_db_trie } | Self::Branch { store_in_db_trie } => {
store_in_db_trie
}
_ => false,
}
}
}
/// Enum representing trie nodes in sparse trie.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SparseNode {
/// Empty trie node.
Empty,
/// The hash of the node that was not revealed.
Hash(B256),
/// Sparse leaf node with remaining key suffix.
Leaf {
/// Remaining key suffix for the leaf node.
key: Nibbles,
/// Pre-computed hash of the sparse node.
/// Can be reused unless this trie path has been updated.
hash: Option<B256>,
},
/// Sparse extension node with key.
Extension {
/// The key slice stored by this extension node.
key: Nibbles,
/// Pre-computed hash of the sparse node.
/// Can be reused unless this trie path has been updated.
hash: Option<B256>,
},
/// Sparse branch node with state mask.
Branch {
/// The bitmask representing children present in the branch node.
state_mask: TrieMask,
/// Pre-computed hash of the sparse node.
/// Can be reused unless this trie path has been updated.
hash: Option<B256>,
/// Pre-computed flag indicating whether the trie node should be stored in the database.
/// Can be reused unless this trie path has been updated.
store_in_db_trie: Option<bool>,
},
}
impl SparseNode {
/// Create new sparse node from [`TrieNode`].
pub fn from_node(node: TrieNode) -> Self {
match node {
TrieNode::EmptyRoot => Self::Empty,
TrieNode::Leaf(leaf) => Self::new_leaf(leaf.key),
TrieNode::Extension(ext) => Self::new_ext(ext.key),
TrieNode::Branch(branch) => Self::new_branch(branch.state_mask),
}
}
/// Create new [`SparseNode::Branch`] from state mask.
pub const fn new_branch(state_mask: TrieMask) -> Self {
Self::Branch { state_mask, hash: None, store_in_db_trie: None }
}
/// Create new [`SparseNode::Branch`] with two bits set.
pub const fn new_split_branch(bit_a: u8, bit_b: u8) -> Self {
let state_mask = TrieMask::new(
// set bits for both children
(1u16 << bit_a) | (1u16 << bit_b),
);
Self::Branch { state_mask, hash: None, store_in_db_trie: None }
}
/// Create new [`SparseNode::Extension`] from the key slice.
pub const fn new_ext(key: Nibbles) -> Self {
Self::Extension { key, hash: None }
}
/// Create new [`SparseNode::Leaf`] from leaf key and value.
pub const fn new_leaf(key: Nibbles) -> Self {
Self::Leaf { key, hash: None }
}
/// Returns `true` if the node is a hash node.
pub const fn is_hash(&self) -> bool {
matches!(self, Self::Hash(_))
}
}
#[derive(Debug)]
struct RemovedSparseNode {
path: Nibbles,
node: SparseNode,
unset_branch_nibble: Option<u8>,
}
/// Collection of reusable buffers for [`RevealedSparseTrie::rlp_node`].
#[derive(Debug, Default)]
struct RlpNodeBuffers {
/// Stack of paths we need rlp nodes for and whether the path is in the prefix set.
path_stack: Vec<(Nibbles, Option<bool>)>,
/// Stack of rlp nodes
rlp_node_stack: Vec<(Nibbles, RlpNode, bool, SparseNodeType)>,
/// Reusable branch child path
branch_child_buf: SmallVec<[Nibbles; 16]>,
/// Reusable branch value stack
branch_value_stack_buf: SmallVec<[RlpNode; 16]>,
}
impl RlpNodeBuffers {
/// Creates a new instance of buffers with the given path on the stack.
fn new_with_path(path: Nibbles) -> Self {
Self {
path_stack: vec![(path, None)],
rlp_node_stack: Vec::new(),
branch_child_buf: SmallVec::<[Nibbles; 16]>::new_const(),
branch_value_stack_buf: SmallVec::<[RlpNode; 16]>::new_const(),
}
}
}
/// The aggregation of sparse trie updates.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SparseTrieUpdates {
pub(crate) updated_nodes: HashMap<Nibbles, BranchNodeCompact>,
pub(crate) removed_nodes: HashSet<Nibbles>,
pub(crate) wiped: bool,
}
impl SparseTrieUpdates {
/// Create new wiped sparse trie updates.
pub fn wiped() -> Self {
Self { wiped: true, ..Default::default() }
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloy_primitives::{
map::{B256HashSet, HashSet},
U256,
};
use alloy_rlp::Encodable;
use assert_matches::assert_matches;
use itertools::Itertools;
use prop::sample::SizeRange;
use proptest::prelude::*;
use proptest_arbitrary_interop::arb;
use rand::seq::IteratorRandom;
use reth_primitives_traits::Account;
use reth_trie::{
hashed_cursor::{noop::NoopHashedAccountCursor, HashedPostStateAccountCursor},
node_iter::{TrieElement, TrieNodeIter},
trie_cursor::noop::NoopAccountTrieCursor,
updates::TrieUpdates,
walker::TrieWalker,
BranchNode, ExtensionNode, HashedPostState, LeafNode,
};
use reth_trie_common::{
proof::{ProofNodes, ProofRetainer},
HashBuilder,
};
use std::collections::BTreeMap;
/// Pad nibbles to the length of a B256 hash with zeros on the left.
fn pad_nibbles_left(nibbles: Nibbles) -> Nibbles {
let mut base =
Nibbles::from_nibbles_unchecked(vec![0; B256::len_bytes() * 2 - nibbles.len()]);
base.extend_from_slice_unchecked(&nibbles);
base
}
/// Pad nibbles to the length of a B256 hash with zeros on the right.
fn pad_nibbles_right(mut nibbles: Nibbles) -> Nibbles {
nibbles.extend_from_slice_unchecked(&vec![0; B256::len_bytes() * 2 - nibbles.len()]);
nibbles
}
/// Calculate the state root by feeding the provided state to the hash builder and retaining the
/// proofs for the provided targets.
///
/// Returns the state root and the retained proof nodes.
fn run_hash_builder(
state: impl IntoIterator<Item = (Nibbles, Account)> + Clone,
destroyed_accounts: B256HashSet,
proof_targets: impl IntoIterator<Item = Nibbles>,
) -> (B256, TrieUpdates, ProofNodes, HashMap<Nibbles, TrieMask>) {
let mut account_rlp = Vec::new();
let mut hash_builder = HashBuilder::default()
.with_updates(true)
.with_proof_retainer(ProofRetainer::from_iter(proof_targets));
let mut prefix_set = PrefixSetMut::default();
prefix_set.extend_keys(state.clone().into_iter().map(|(nibbles, _)| nibbles));
let walker = TrieWalker::new(NoopAccountTrieCursor::default(), prefix_set.freeze())
.with_deletions_retained(true);
let hashed_post_state = HashedPostState::default()
.with_accounts(state.into_iter().map(|(nibbles, account)| {
(nibbles.pack().into_inner().unwrap().into(), Some(account))
}))
.into_sorted();
let mut node_iter = TrieNodeIter::new(
walker,
HashedPostStateAccountCursor::new(
NoopHashedAccountCursor::default(),
hashed_post_state.accounts(),
),
);
while let Some(node) = node_iter.try_next().unwrap() {
match node {
TrieElement::Branch(branch) => {
hash_builder.add_branch(branch.key, branch.value, branch.children_are_in_trie);
}
TrieElement::Leaf(key, account) => {
let account = account.into_trie_account(EMPTY_ROOT_HASH);
account.encode(&mut account_rlp);
hash_builder.add_leaf(Nibbles::unpack(key), &account_rlp);
account_rlp.clear();
}
}
}
let root = hash_builder.root();
let proof_nodes = hash_builder.take_proof_nodes();
let branch_node_hash_masks = hash_builder
.updated_branch_nodes
.clone()
.unwrap_or_default()
.iter()
.map(|(path, node)| (path.clone(), node.hash_mask))
.collect();
let mut trie_updates = TrieUpdates::default();
let removed_keys = node_iter.walker.take_removed_keys();
trie_updates.finalize(hash_builder, removed_keys, destroyed_accounts);
(root, trie_updates, proof_nodes, branch_node_hash_masks)
}
/// Assert that the sparse trie nodes and the proof nodes from the hash builder are equal.
fn assert_eq_sparse_trie_proof_nodes(
sparse_trie: &RevealedSparseTrie,
proof_nodes: ProofNodes,
) {
let proof_nodes = proof_nodes
.into_nodes_sorted()
.into_iter()
.map(|(path, node)| (path, TrieNode::decode(&mut node.as_ref()).unwrap()));
let sparse_nodes = sparse_trie.nodes.iter().sorted_by_key(|(path, _)| *path);
for ((proof_node_path, proof_node), (sparse_node_path, sparse_node)) in
proof_nodes.zip(sparse_nodes)
{
assert_eq!(&proof_node_path, sparse_node_path);
let equals = match (&proof_node, &sparse_node) {
// Both nodes are empty
(TrieNode::EmptyRoot, SparseNode::Empty) => true,
// Both nodes are branches and have the same state mask
(
TrieNode::Branch(BranchNode { state_mask: proof_state_mask, .. }),
SparseNode::Branch { state_mask: sparse_state_mask, .. },
) => proof_state_mask == sparse_state_mask,
// Both nodes are extensions and have the same key
(
TrieNode::Extension(ExtensionNode { key: proof_key, .. }),
SparseNode::Extension { key: sparse_key, .. },
) |
// Both nodes are leaves and have the same key
(
TrieNode::Leaf(LeafNode { key: proof_key, .. }),
SparseNode::Leaf { key: sparse_key, .. },
) => proof_key == sparse_key,
// Empty and hash nodes are specific to the sparse trie, skip them
(_, SparseNode::Empty | SparseNode::Hash(_)) => continue,
_ => false,
};
assert!(equals, "proof node: {:?}, sparse node: {:?}", proof_node, sparse_node);
}
}
#[test]
fn sparse_trie_is_blind() {
assert!(SparseTrie::blind().is_blind());
assert!(!SparseTrie::revealed_empty().is_blind());
}
#[test]
fn sparse_trie_empty_update_one() {
let key = Nibbles::unpack(B256::with_last_byte(42));
let value = || Account::default();
let value_encoded = || {
let mut account_rlp = Vec::new();
value().into_trie_account(EMPTY_ROOT_HASH).encode(&mut account_rlp);
account_rlp
};
let (hash_builder_root, hash_builder_updates, hash_builder_proof_nodes, _) =
run_hash_builder([(key.clone(), value())], Default::default(), [key.clone()]);
let mut sparse = RevealedSparseTrie::default().with_updates(true);
sparse.update_leaf(key, value_encoded()).unwrap();
let sparse_root = sparse.root();
let sparse_updates = sparse.take_updates();
assert_eq!(sparse_root, hash_builder_root);
assert_eq!(sparse_updates.updated_nodes, hash_builder_updates.account_nodes);
assert_eq_sparse_trie_proof_nodes(&sparse, hash_builder_proof_nodes);
}
#[test]
fn sparse_trie_empty_update_multiple_lower_nibbles() {
reth_tracing::init_test_tracing();
let paths = (0..=16).map(|b| Nibbles::unpack(B256::with_last_byte(b))).collect::<Vec<_>>();
let value = || Account::default();
let value_encoded = || {
let mut account_rlp = Vec::new();
value().into_trie_account(EMPTY_ROOT_HASH).encode(&mut account_rlp);
account_rlp
};
let (hash_builder_root, hash_builder_updates, hash_builder_proof_nodes, _) =
run_hash_builder(
paths.iter().cloned().zip(std::iter::repeat_with(value)),
Default::default(),
paths.clone(),
);
let mut sparse = RevealedSparseTrie::default().with_updates(true);
for path in &paths {
sparse.update_leaf(path.clone(), value_encoded()).unwrap();
}
let sparse_root = sparse.root();
let sparse_updates = sparse.take_updates();
assert_eq!(sparse_root, hash_builder_root);
assert_eq!(sparse_updates.updated_nodes, hash_builder_updates.account_nodes);
assert_eq_sparse_trie_proof_nodes(&sparse, hash_builder_proof_nodes);
}
#[test]
fn sparse_trie_empty_update_multiple_upper_nibbles() {
let paths = (239..=255).map(|b| Nibbles::unpack(B256::repeat_byte(b))).collect::<Vec<_>>();
let value = || Account::default();
let value_encoded = || {
let mut account_rlp = Vec::new();
value().into_trie_account(EMPTY_ROOT_HASH).encode(&mut account_rlp);
account_rlp
};
let (hash_builder_root, hash_builder_updates, hash_builder_proof_nodes, _) =
run_hash_builder(
paths.iter().cloned().zip(std::iter::repeat_with(value)),
Default::default(),
paths.clone(),
);
let mut sparse = RevealedSparseTrie::default().with_updates(true);
for path in &paths {
sparse.update_leaf(path.clone(), value_encoded()).unwrap();
}
let sparse_root = sparse.root();
let sparse_updates = sparse.take_updates();
assert_eq!(sparse_root, hash_builder_root);
assert_eq!(sparse_updates.updated_nodes, hash_builder_updates.account_nodes);
assert_eq_sparse_trie_proof_nodes(&sparse, hash_builder_proof_nodes);
}
#[test]
fn sparse_trie_empty_update_multiple() {
let paths = (0..=255)
.map(|b| {
Nibbles::unpack(if b % 2 == 0 {
B256::repeat_byte(b)
} else {
B256::with_last_byte(b)
})
})
.collect::<Vec<_>>();
let value = || Account::default();
let value_encoded = || {
let mut account_rlp = Vec::new();
value().into_trie_account(EMPTY_ROOT_HASH).encode(&mut account_rlp);
account_rlp
};
let (hash_builder_root, hash_builder_updates, hash_builder_proof_nodes, _) =
run_hash_builder(
paths.iter().sorted_unstable().cloned().zip(std::iter::repeat_with(value)),
Default::default(),
paths.clone(),
);
let mut sparse = RevealedSparseTrie::default().with_updates(true);
for path in &paths {
sparse.update_leaf(path.clone(), value_encoded()).unwrap();
}
let sparse_root = sparse.root();
let sparse_updates = sparse.take_updates();
assert_eq!(sparse_root, hash_builder_root);
pretty_assertions::assert_eq!(
BTreeMap::from_iter(sparse_updates.updated_nodes),
BTreeMap::from_iter(hash_builder_updates.account_nodes)
);
assert_eq_sparse_trie_proof_nodes(&sparse, hash_builder_proof_nodes);
}
#[test]
fn sparse_trie_empty_update_repeated() {
let paths = (0..=255).map(|b| Nibbles::unpack(B256::repeat_byte(b))).collect::<Vec<_>>();
let old_value = Account { nonce: 1, ..Default::default() };
let old_value_encoded = {
let mut account_rlp = Vec::new();
old_value.into_trie_account(EMPTY_ROOT_HASH).encode(&mut account_rlp);
account_rlp
};
let new_value = Account { nonce: 2, ..Default::default() };
let new_value_encoded = {
let mut account_rlp = Vec::new();
new_value.into_trie_account(EMPTY_ROOT_HASH).encode(&mut account_rlp);
account_rlp
};
let (hash_builder_root, hash_builder_updates, hash_builder_proof_nodes, _) =
run_hash_builder(
paths.iter().cloned().zip(std::iter::repeat_with(|| old_value)),
Default::default(),
paths.clone(),
);
let mut sparse = RevealedSparseTrie::default().with_updates(true);
for path in &paths {
sparse.update_leaf(path.clone(), old_value_encoded.clone()).unwrap();
}
let sparse_root = sparse.root();
let sparse_updates = sparse.updates_ref();
assert_eq!(sparse_root, hash_builder_root);
assert_eq!(sparse_updates.updated_nodes, hash_builder_updates.account_nodes);
assert_eq_sparse_trie_proof_nodes(&sparse, hash_builder_proof_nodes);
let (hash_builder_root, hash_builder_updates, hash_builder_proof_nodes, _) =
run_hash_builder(
paths.iter().cloned().zip(std::iter::repeat_with(|| new_value)),
Default::default(),
paths.clone(),
);
for path in &paths {
sparse.update_leaf(path.clone(), new_value_encoded.clone()).unwrap();
}
let sparse_root = sparse.root();
let sparse_updates = sparse.take_updates();
assert_eq!(sparse_root, hash_builder_root);
assert_eq!(sparse_updates.updated_nodes, hash_builder_updates.account_nodes);
assert_eq_sparse_trie_proof_nodes(&sparse, hash_builder_proof_nodes);
}
#[test]
fn sparse_trie_remove_leaf() {
reth_tracing::init_test_tracing();
let mut sparse = RevealedSparseTrie::default();
let value = alloy_rlp::encode_fixed_size(&U256::ZERO).to_vec();
sparse
.update_leaf(Nibbles::from_nibbles([0x5, 0x0, 0x2, 0x3, 0x1]), value.clone())
.unwrap();
sparse
.update_leaf(Nibbles::from_nibbles([0x5, 0x0, 0x2, 0x3, 0x3]), value.clone())
.unwrap();
sparse
.update_leaf(Nibbles::from_nibbles([0x5, 0x2, 0x0, 0x1, 0x3]), value.clone())
.unwrap();
sparse
.update_leaf(Nibbles::from_nibbles([0x5, 0x3, 0x1, 0x0, 0x2]), value.clone())
.unwrap();
sparse
.update_leaf(Nibbles::from_nibbles([0x5, 0x3, 0x3, 0x0, 0x2]), value.clone())
.unwrap();
sparse.update_leaf(Nibbles::from_nibbles([0x5, 0x3, 0x3, 0x2, 0x0]), value).unwrap();
// Extension (Key = 5)
// └── Branch (Mask = 1011)
// ├── 0 -> Extension (Key = 23)
// │ └── Branch (Mask = 0101)
// │ ├── 1 -> Leaf (Key = 1, Path = 50231)
// │ └── 3 -> Leaf (Key = 3, Path = 50233)
// ├── 2 -> Leaf (Key = 013, Path = 52013)
// └── 3 -> Branch (Mask = 0101)
// ├── 1 -> Leaf (Key = 3102, Path = 53102)
// └── 3 -> Branch (Mask = 1010)
// ├── 0 -> Leaf (Key = 3302, Path = 53302)
// └── 2 -> Leaf (Key = 3320, Path = 53320)
pretty_assertions::assert_eq!(
sparse.nodes.clone().into_iter().collect::<BTreeMap<_, _>>(),
BTreeMap::from_iter([
(Nibbles::default(), SparseNode::new_ext(Nibbles::from_nibbles([0x5]))),
(Nibbles::from_nibbles([0x5]), SparseNode::new_branch(0b1101.into())),
(
Nibbles::from_nibbles([0x5, 0x0]),
SparseNode::new_ext(Nibbles::from_nibbles([0x2, 0x3]))
),
(
Nibbles::from_nibbles([0x5, 0x0, 0x2, 0x3]),
SparseNode::new_branch(0b1010.into())
),
(
Nibbles::from_nibbles([0x5, 0x0, 0x2, 0x3, 0x1]),
SparseNode::new_leaf(Nibbles::default())
),
(
Nibbles::from_nibbles([0x5, 0x0, 0x2, 0x3, 0x3]),
SparseNode::new_leaf(Nibbles::default())
),
(
Nibbles::from_nibbles([0x5, 0x2]),
SparseNode::new_leaf(Nibbles::from_nibbles([0x0, 0x1, 0x3]))
),
(Nibbles::from_nibbles([0x5, 0x3]), SparseNode::new_branch(0b1010.into())),
(
Nibbles::from_nibbles([0x5, 0x3, 0x1]),
SparseNode::new_leaf(Nibbles::from_nibbles([0x0, 0x2]))
),
(Nibbles::from_nibbles([0x5, 0x3, 0x3]), SparseNode::new_branch(0b0101.into())),
(
Nibbles::from_nibbles([0x5, 0x3, 0x3, 0x0]),
SparseNode::new_leaf(Nibbles::from_nibbles([0x2]))
),
(
Nibbles::from_nibbles([0x5, 0x3, 0x3, 0x2]),
SparseNode::new_leaf(Nibbles::from_nibbles([0x0]))
)
])
);
sparse.remove_leaf(&Nibbles::from_nibbles([0x5, 0x2, 0x0, 0x1, 0x3])).unwrap();
// Extension (Key = 5)
// └── Branch (Mask = 1001)
// ├── 0 -> Extension (Key = 23)
// │ └── Branch (Mask = 0101)
// │ ├── 1 -> Leaf (Key = 0231, Path = 50231)
// │ └── 3 -> Leaf (Key = 0233, Path = 50233)
// └── 3 -> Branch (Mask = 0101)
// ├── 1 -> Leaf (Key = 3102, Path = 53102)
// └── 3 -> Branch (Mask = 1010)
// ├── 0 -> Leaf (Key = 3302, Path = 53302)
// └── 2 -> Leaf (Key = 3320, Path = 53320)
pretty_assertions::assert_eq!(
sparse.nodes.clone().into_iter().collect::<BTreeMap<_, _>>(),
BTreeMap::from_iter([
(Nibbles::default(), SparseNode::new_ext(Nibbles::from_nibbles([0x5]))),
(Nibbles::from_nibbles([0x5]), SparseNode::new_branch(0b1001.into())),
(
Nibbles::from_nibbles([0x5, 0x0]),
SparseNode::new_ext(Nibbles::from_nibbles([0x2, 0x3]))
),
(
Nibbles::from_nibbles([0x5, 0x0, 0x2, 0x3]),
SparseNode::new_branch(0b1010.into())
),
(
Nibbles::from_nibbles([0x5, 0x0, 0x2, 0x3, 0x1]),
SparseNode::new_leaf(Nibbles::default())
),
(
Nibbles::from_nibbles([0x5, 0x0, 0x2, 0x3, 0x3]),
SparseNode::new_leaf(Nibbles::default())
),
(Nibbles::from_nibbles([0x5, 0x3]), SparseNode::new_branch(0b1010.into())),
(
Nibbles::from_nibbles([0x5, 0x3, 0x1]),
SparseNode::new_leaf(Nibbles::from_nibbles([0x0, 0x2]))
),
(Nibbles::from_nibbles([0x5, 0x3, 0x3]), SparseNode::new_branch(0b0101.into())),
(
Nibbles::from_nibbles([0x5, 0x3, 0x3, 0x0]),
SparseNode::new_leaf(Nibbles::from_nibbles([0x2]))
),
(
Nibbles::from_nibbles([0x5, 0x3, 0x3, 0x2]),
SparseNode::new_leaf(Nibbles::from_nibbles([0x0]))
)
])
);
sparse.remove_leaf(&Nibbles::from_nibbles([0x5, 0x0, 0x2, 0x3, 0x1])).unwrap();
// Extension (Key = 5)
// └── Branch (Mask = 1001)
// ├── 0 -> Leaf (Key = 0233, Path = 50233)
// └── 3 -> Branch (Mask = 0101)
// ├── 1 -> Leaf (Key = 3102, Path = 53102)
// └── 3 -> Branch (Mask = 1010)
// ├── 0 -> Leaf (Key = 3302, Path = 53302)
// └── 2 -> Leaf (Key = 3320, Path = 53320)
pretty_assertions::assert_eq!(
sparse.nodes.clone().into_iter().collect::<BTreeMap<_, _>>(),
BTreeMap::from_iter([
(Nibbles::default(), SparseNode::new_ext(Nibbles::from_nibbles([0x5]))),
(Nibbles::from_nibbles([0x5]), SparseNode::new_branch(0b1001.into())),
(
Nibbles::from_nibbles([0x5, 0x0]),
SparseNode::new_leaf(Nibbles::from_nibbles([0x2, 0x3, 0x3]))
),
(Nibbles::from_nibbles([0x5, 0x3]), SparseNode::new_branch(0b1010.into())),
(
Nibbles::from_nibbles([0x5, 0x3, 0x1]),
SparseNode::new_leaf(Nibbles::from_nibbles([0x0, 0x2]))
),
(Nibbles::from_nibbles([0x5, 0x3, 0x3]), SparseNode::new_branch(0b0101.into())),
(
Nibbles::from_nibbles([0x5, 0x3, 0x3, 0x0]),
SparseNode::new_leaf(Nibbles::from_nibbles([0x2]))
),
(
Nibbles::from_nibbles([0x5, 0x3, 0x3, 0x2]),
SparseNode::new_leaf(Nibbles::from_nibbles([0x0]))
)
])
);
sparse.remove_leaf(&Nibbles::from_nibbles([0x5, 0x3, 0x1, 0x0, 0x2])).unwrap();
// Extension (Key = 5)
// └── Branch (Mask = 1001)
// ├── 0 -> Leaf (Key = 0233, Path = 50233)
// └── 3 -> Branch (Mask = 1010)
// ├── 0 -> Leaf (Key = 3302, Path = 53302)
// └── 2 -> Leaf (Key = 3320, Path = 53320)
pretty_assertions::assert_eq!(
sparse.nodes.clone().into_iter().collect::<BTreeMap<_, _>>(),
BTreeMap::from_iter([
(Nibbles::default(), SparseNode::new_ext(Nibbles::from_nibbles([0x5]))),
(Nibbles::from_nibbles([0x5]), SparseNode::new_branch(0b1001.into())),
(
Nibbles::from_nibbles([0x5, 0x0]),
SparseNode::new_leaf(Nibbles::from_nibbles([0x2, 0x3, 0x3]))
),
(
Nibbles::from_nibbles([0x5, 0x3]),
SparseNode::new_ext(Nibbles::from_nibbles([0x3]))
),
(Nibbles::from_nibbles([0x5, 0x3, 0x3]), SparseNode::new_branch(0b0101.into())),
(
Nibbles::from_nibbles([0x5, 0x3, 0x3, 0x0]),
SparseNode::new_leaf(Nibbles::from_nibbles([0x2]))
),
(
Nibbles::from_nibbles([0x5, 0x3, 0x3, 0x2]),
SparseNode::new_leaf(Nibbles::from_nibbles([0x0]))
)
])
);
sparse.remove_leaf(&Nibbles::from_nibbles([0x5, 0x3, 0x3, 0x2, 0x0])).unwrap();
// Extension (Key = 5)
// └── Branch (Mask = 1001)
// ├── 0 -> Leaf (Key = 0233, Path = 50233)
// └── 3 -> Leaf (Key = 3302, Path = 53302)
pretty_assertions::assert_eq!(
sparse.nodes.clone().into_iter().collect::<BTreeMap<_, _>>(),
BTreeMap::from_iter([
(Nibbles::default(), SparseNode::new_ext(Nibbles::from_nibbles([0x5]))),
(Nibbles::from_nibbles([0x5]), SparseNode::new_branch(0b1001.into())),
(
Nibbles::from_nibbles([0x5, 0x0]),
SparseNode::new_leaf(Nibbles::from_nibbles([0x2, 0x3, 0x3]))
),
(
Nibbles::from_nibbles([0x5, 0x3]),
SparseNode::new_leaf(Nibbles::from_nibbles([0x3, 0x0, 0x2]))
),
])
);
sparse.remove_leaf(&Nibbles::from_nibbles([0x5, 0x0, 0x2, 0x3, 0x3])).unwrap();
// Leaf (Key = 53302)
pretty_assertions::assert_eq!(
sparse.nodes.clone().into_iter().collect::<BTreeMap<_, _>>(),
BTreeMap::from_iter([(
Nibbles::default(),
SparseNode::new_leaf(Nibbles::from_nibbles([0x5, 0x3, 0x3, 0x0, 0x2]))
),])
);
sparse.remove_leaf(&Nibbles::from_nibbles([0x5, 0x3, 0x3, 0x0, 0x2])).unwrap();
// Empty
pretty_assertions::assert_eq!(
sparse.nodes.clone().into_iter().collect::<BTreeMap<_, _>>(),
BTreeMap::from_iter([(Nibbles::default(), SparseNode::Empty)])
);
}
#[test]
fn sparse_trie_remove_leaf_blinded() {
let leaf = LeafNode::new(
Nibbles::default(),
alloy_rlp::encode_fixed_size(&U256::from(1)).to_vec(),
);
let branch = TrieNode::Branch(BranchNode::new(
vec![
RlpNode::word_rlp(&B256::repeat_byte(1)),
RlpNode::from_raw_rlp(&alloy_rlp::encode(leaf.clone())).unwrap(),
],
TrieMask::new(0b11),
));
let mut sparse =
RevealedSparseTrie::from_root(branch.clone(), Some(TrieMask::new(0b01)), false)
.unwrap();
// Reveal a branch node and one of its children
//
// Branch (Mask = 11)
// ├── 0 -> Hash (Path = 0)
// └── 1 -> Leaf (Path = 1)
sparse.reveal_node(Nibbles::default(), branch, Some(TrieMask::new(0b01))).unwrap();
sparse.reveal_node(Nibbles::from_nibbles([0x1]), TrieNode::Leaf(leaf), None).unwrap();
// Removing a blinded leaf should result in an error
assert_matches!(
sparse.remove_leaf(&Nibbles::from_nibbles([0x0])).map_err(|e| e.into_kind()),
Err(SparseTrieErrorKind::BlindedNode { path, hash }) if path == Nibbles::from_nibbles([0x0]) && hash == B256::repeat_byte(1)
);
}
#[test]
fn sparse_trie_remove_leaf_non_existent() {
let leaf = LeafNode::new(
Nibbles::default(),
alloy_rlp::encode_fixed_size(&U256::from(1)).to_vec(),
);
let branch = TrieNode::Branch(BranchNode::new(
vec![
RlpNode::word_rlp(&B256::repeat_byte(1)),
RlpNode::from_raw_rlp(&alloy_rlp::encode(leaf.clone())).unwrap(),
],
TrieMask::new(0b11),
));
let mut sparse =
RevealedSparseTrie::from_root(branch.clone(), Some(TrieMask::new(0b01)), false)
.unwrap();
// Reveal a branch node and one of its children
//
// Branch (Mask = 11)
// ├── 0 -> Hash (Path = 0)
// └── 1 -> Leaf (Path = 1)
sparse.reveal_node(Nibbles::default(), branch, Some(TrieMask::new(0b01))).unwrap();
sparse.reveal_node(Nibbles::from_nibbles([0x1]), TrieNode::Leaf(leaf), None).unwrap();
// Removing a non-existent leaf should be a noop
let sparse_old = sparse.clone();
assert_matches!(sparse.remove_leaf(&Nibbles::from_nibbles([0x2])), Ok(()));
assert_eq!(sparse, sparse_old);
}
#[allow(clippy::type_complexity)]
#[test]
fn sparse_trie_fuzz() {
// Having only the first 3 nibbles set, we narrow down the range of keys
// to 4096 different hashes. It allows us to generate collisions more likely
// to test the sparse trie updates.
const KEY_NIBBLES_LEN: usize = 3;
fn test(updates: Vec<(HashMap<Nibbles, Account>, HashSet<Nibbles>)>) {
{
let mut state = BTreeMap::default();
let mut sparse = RevealedSparseTrie::default().with_updates(true);
for (update, keys_to_delete) in updates {
// Insert state updates into the sparse trie and calculate the root
for (key, account) in update.clone() {
let account = account.into_trie_account(EMPTY_ROOT_HASH);
let mut account_rlp = Vec::new();
account.encode(&mut account_rlp);
sparse.update_leaf(key, account_rlp).unwrap();
}
// We need to clone the sparse trie, so that all updated branch nodes are
// preserved, and not only those that were changed after the last call to
// `root()`.
let mut updated_sparse = sparse.clone();
let sparse_root = updated_sparse.root();
let sparse_updates = updated_sparse.take_updates();
// Insert state updates into the hash builder and calculate the root
state.extend(update);
let (hash_builder_root, hash_builder_updates, hash_builder_proof_nodes, _) =
run_hash_builder(
state.clone(),
Default::default(),
state.keys().cloned().collect::<Vec<_>>(),
);
// Assert that the sparse trie root matches the hash builder root
assert_eq!(sparse_root, hash_builder_root);
// Assert that the sparse trie updates match the hash builder updates
pretty_assertions::assert_eq!(
sparse_updates.updated_nodes,
hash_builder_updates.account_nodes
);
// Assert that the sparse trie nodes match the hash builder proof nodes
assert_eq_sparse_trie_proof_nodes(&updated_sparse, hash_builder_proof_nodes);
// Delete some keys from both the hash builder and the sparse trie and check
// that the sparse trie root still matches the hash builder root
for key in keys_to_delete {
state.remove(&key).unwrap();
sparse.remove_leaf(&key).unwrap();
}
// We need to clone the sparse trie, so that all updated branch nodes are
// preserved, and not only those that were changed after the last call to
// `root()`.
let mut updated_sparse = sparse.clone();
let sparse_root = updated_sparse.root();
let sparse_updates = updated_sparse.take_updates();
let (hash_builder_root, hash_builder_updates, hash_builder_proof_nodes, _) =
run_hash_builder(
state.clone(),
Default::default(),
state.keys().cloned().collect::<Vec<_>>(),
);
// Assert that the sparse trie root matches the hash builder root
assert_eq!(sparse_root, hash_builder_root);
// Assert that the sparse trie updates match the hash builder updates
pretty_assertions::assert_eq!(
sparse_updates.updated_nodes,
hash_builder_updates.account_nodes
);
// Assert that the sparse trie nodes match the hash builder proof nodes
assert_eq_sparse_trie_proof_nodes(&updated_sparse, hash_builder_proof_nodes);
}
}
}
fn transform_updates(
updates: Vec<HashMap<Nibbles, Account>>,
mut rng: impl Rng,
) -> Vec<(HashMap<Nibbles, Account>, HashSet<Nibbles>)> {
let mut keys = HashSet::new();
updates
.into_iter()
.map(|update| {
keys.extend(update.keys().cloned());
let keys_to_delete_len = update.len() / 2;
let keys_to_delete = (0..keys_to_delete_len)
.map(|_| {
let key = keys.iter().choose(&mut rng).unwrap().clone();
keys.take(&key).unwrap()
})
.collect();
(update, keys_to_delete)
})
.collect::<Vec<_>>()
}
proptest!(ProptestConfig::with_cases(10), |(
updates in proptest::collection::vec(
proptest::collection::hash_map(
any_with::<Nibbles>(SizeRange::new(KEY_NIBBLES_LEN..=KEY_NIBBLES_LEN)).prop_map(pad_nibbles_right),
arb::<Account>(),
1..100,
).prop_map(HashMap::from_iter),
1..100,
).prop_perturb(transform_updates)
)| {
test(updates)
});
}
/// We have three leaves that share the same prefix: 0x00, 0x01 and 0x02. Hash builder trie has
/// only nodes 0x00 and 0x01, and we have proofs for them. Node B is new and inserted in the
/// sparse trie first.
///
/// 1. Reveal the hash builder proof to leaf 0x00 in the sparse trie.
/// 2. Insert leaf 0x01 into the sparse trie.
/// 3. Reveal the hash builder proof to leaf 0x02 in the sparse trie.
///
/// The hash builder proof to the leaf 0x02 didn't have the leaf 0x01 at the corresponding
/// nibble of the branch node, so we need to adjust the branch node instead of fully
/// replacing it.
#[test]
fn sparse_trie_reveal_node_1() {
let key1 = || pad_nibbles_right(Nibbles::from_nibbles_unchecked([0x00]));
let key2 = || pad_nibbles_right(Nibbles::from_nibbles_unchecked([0x01]));
let key3 = || pad_nibbles_right(Nibbles::from_nibbles_unchecked([0x02]));
let value = || Account::default();
let value_encoded = || {
let mut account_rlp = Vec::new();
value().into_trie_account(EMPTY_ROOT_HASH).encode(&mut account_rlp);
account_rlp
};
// Generate the proof for the root node and initialize the sparse trie with it
let (_, _, hash_builder_proof_nodes, branch_node_hash_masks) = run_hash_builder(
[(key1(), value()), (key3(), value())],
Default::default(),
[Nibbles::default()],
);
let mut sparse = RevealedSparseTrie::from_root(
TrieNode::decode(&mut &hash_builder_proof_nodes.nodes_sorted()[0].1[..]).unwrap(),
branch_node_hash_masks.get(&Nibbles::default()).copied(),
false,
)
.unwrap();
// Generate the proof for the first key and reveal it in the sparse trie
let (_, _, hash_builder_proof_nodes, branch_node_hash_masks) =
run_hash_builder([(key1(), value()), (key3(), value())], Default::default(), [key1()]);
for (path, node) in hash_builder_proof_nodes.nodes_sorted() {
let hash_mask = branch_node_hash_masks.get(&path).copied();
sparse.reveal_node(path, TrieNode::decode(&mut &node[..]).unwrap(), hash_mask).unwrap();
}
// Check that the branch node exists with only two nibbles set
assert_eq!(
sparse.nodes.get(&Nibbles::default()),
Some(&SparseNode::new_branch(0b101.into()))
);
// Insert the leaf for the second key
sparse.update_leaf(key2(), value_encoded()).unwrap();
// Check that the branch node was updated and another nibble was set
assert_eq!(
sparse.nodes.get(&Nibbles::default()),
Some(&SparseNode::new_branch(0b111.into()))
);
// Generate the proof for the third key and reveal it in the sparse trie
let (_, _, hash_builder_proof_nodes, branch_node_hash_masks) =
run_hash_builder([(key1(), value()), (key3(), value())], Default::default(), [key3()]);
for (path, node) in hash_builder_proof_nodes.nodes_sorted() {
let hash_mask = branch_node_hash_masks.get(&path).copied();
sparse.reveal_node(path, TrieNode::decode(&mut &node[..]).unwrap(), hash_mask).unwrap();
}
// Check that nothing changed in the branch node
assert_eq!(
sparse.nodes.get(&Nibbles::default()),
Some(&SparseNode::new_branch(0b111.into()))
);
// Generate the nodes for the full trie with all three key using the hash builder, and
// compare them to the sparse trie
let (_, _, hash_builder_proof_nodes, _) = run_hash_builder(
[(key1(), value()), (key2(), value()), (key3(), value())],
Default::default(),
[key1(), key2(), key3()],
);
assert_eq_sparse_trie_proof_nodes(&sparse, hash_builder_proof_nodes);
}
/// We have three leaves: 0x0000, 0x0101, and 0x0102. Hash builder trie has all nodes, and we
/// have proofs for them.
///
/// 1. Reveal the hash builder proof to leaf 0x00 in the sparse trie.
/// 2. Remove leaf 0x00 from the sparse trie (that will remove the branch node and create an
/// extension node with the key 0x0000).
/// 3. Reveal the hash builder proof to leaf 0x0101 in the sparse trie.
///
/// The hash builder proof to the leaf 0x0101 had a branch node in the path, but we turned it
/// into an extension node, so it should ignore this node.
#[test]
fn sparse_trie_reveal_node_2() {
let key1 = || pad_nibbles_right(Nibbles::from_nibbles_unchecked([0x00, 0x00]));
let key2 = || pad_nibbles_right(Nibbles::from_nibbles_unchecked([0x01, 0x01]));
let key3 = || pad_nibbles_right(Nibbles::from_nibbles_unchecked([0x01, 0x02]));
let value = || Account::default();
// Generate the proof for the root node and initialize the sparse trie with it
let (_, _, hash_builder_proof_nodes, branch_node_hash_masks) = run_hash_builder(
[(key1(), value()), (key2(), value()), (key3(), value())],
Default::default(),
[Nibbles::default()],
);
let mut sparse = RevealedSparseTrie::from_root(
TrieNode::decode(&mut &hash_builder_proof_nodes.nodes_sorted()[0].1[..]).unwrap(),
branch_node_hash_masks.get(&Nibbles::default()).copied(),
false,
)
.unwrap();
// Generate the proof for the children of the root branch node and reveal it in the sparse
// trie
let (_, _, hash_builder_proof_nodes, branch_node_hash_masks) = run_hash_builder(
[(key1(), value()), (key2(), value()), (key3(), value())],
Default::default(),
[key1(), Nibbles::from_nibbles_unchecked([0x01])],
);
for (path, node) in hash_builder_proof_nodes.nodes_sorted() {
let hash_mask = branch_node_hash_masks.get(&path).copied();
sparse.reveal_node(path, TrieNode::decode(&mut &node[..]).unwrap(), hash_mask).unwrap();
}
// Check that the branch node exists
assert_eq!(
sparse.nodes.get(&Nibbles::default()),
Some(&SparseNode::new_branch(0b11.into()))
);
// Remove the leaf for the first key
sparse.remove_leaf(&key1()).unwrap();
// Check that the branch node was turned into an extension node
assert_eq!(
sparse.nodes.get(&Nibbles::default()),
Some(&SparseNode::new_ext(Nibbles::from_nibbles_unchecked([0x01])))
);
// Generate the proof for the third key and reveal it in the sparse trie
let (_, _, hash_builder_proof_nodes, branch_node_hash_masks) = run_hash_builder(
[(key1(), value()), (key2(), value()), (key3(), value())],
Default::default(),
[key2()],
);
for (path, node) in hash_builder_proof_nodes.nodes_sorted() {
let hash_mask = branch_node_hash_masks.get(&path).copied();
sparse.reveal_node(path, TrieNode::decode(&mut &node[..]).unwrap(), hash_mask).unwrap();
}
// Check that nothing changed in the extension node
assert_eq!(
sparse.nodes.get(&Nibbles::default()),
Some(&SparseNode::new_ext(Nibbles::from_nibbles_unchecked([0x01])))
);
}
/// We have two leaves that share the same prefix: 0x0001 and 0x0002, and a leaf with a
/// different prefix: 0x0100. Hash builder trie has only the first two leaves, and we have
/// proofs for them.
///
/// 1. Insert the leaf 0x0100 into the sparse trie, and check that the root extensino node was
/// turned into a branch node.
/// 2. Reveal the leaf 0x0001 in the sparse trie, and check that the root branch node wasn't
/// overwritten with the extension node from the proof.
#[test]
fn sparse_trie_reveal_node_3() {
let key1 = || pad_nibbles_right(Nibbles::from_nibbles_unchecked([0x00, 0x01]));
let key2 = || pad_nibbles_right(Nibbles::from_nibbles_unchecked([0x00, 0x02]));
let key3 = || pad_nibbles_right(Nibbles::from_nibbles_unchecked([0x01, 0x00]));
let value = || Account::default();
let value_encoded = || {
let mut account_rlp = Vec::new();
value().into_trie_account(EMPTY_ROOT_HASH).encode(&mut account_rlp);
account_rlp
};
// Generate the proof for the root node and initialize the sparse trie with it
let (_, _, hash_builder_proof_nodes, branch_node_hash_masks) = run_hash_builder(
[(key1(), value()), (key2(), value())],
Default::default(),
[Nibbles::default()],
);
let mut sparse = RevealedSparseTrie::from_root(
TrieNode::decode(&mut &hash_builder_proof_nodes.nodes_sorted()[0].1[..]).unwrap(),
branch_node_hash_masks.get(&Nibbles::default()).copied(),
false,
)
.unwrap();
// Check that the root extension node exists
assert_matches!(
sparse.nodes.get(&Nibbles::default()),
Some(SparseNode::Extension { key, hash: None }) if *key == Nibbles::from_nibbles([0x00])
);
// Insert the leaf with a different prefix
sparse.update_leaf(key3(), value_encoded()).unwrap();
// Check that the extension node was turned into a branch node
assert_matches!(
sparse.nodes.get(&Nibbles::default()),
Some(SparseNode::Branch { state_mask, hash: None, store_in_db_trie: None }) if *state_mask == TrieMask::new(0b11)
);
// Generate the proof for the first key and reveal it in the sparse trie
let (_, _, hash_builder_proof_nodes, branch_node_hash_masks) =
run_hash_builder([(key1(), value()), (key2(), value())], Default::default(), [key1()]);
for (path, node) in hash_builder_proof_nodes.nodes_sorted() {
let hash_mask = branch_node_hash_masks.get(&path).copied();
sparse.reveal_node(path, TrieNode::decode(&mut &node[..]).unwrap(), hash_mask).unwrap();
}
// Check that the branch node wasn't overwritten by the extension node in the proof
assert_matches!(
sparse.nodes.get(&Nibbles::default()),
Some(SparseNode::Branch { state_mask, hash: None, store_in_db_trie: None }) if *state_mask == TrieMask::new(0b11)
);
}
#[test]
fn sparse_trie_get_changed_nodes_at_depth() {
let mut sparse = RevealedSparseTrie::default();
let value = alloy_rlp::encode_fixed_size(&U256::ZERO).to_vec();
// Extension (Key = 5) – Level 0
// └── Branch (Mask = 1011) – Level 1
// ├── 0 -> Extension (Key = 23) – Level 2
// │ └── Branch (Mask = 0101) – Level 3
// │ ├── 1 -> Leaf (Key = 1, Path = 50231) – Level 4
// │ └── 3 -> Leaf (Key = 3, Path = 50233) – Level 4
// ├── 2 -> Leaf (Key = 013, Path = 52013) – Level 2
// └── 3 -> Branch (Mask = 0101) – Level 2
// ├── 1 -> Leaf (Key = 3102, Path = 53102) – Level 3
// └── 3 -> Branch (Mask = 1010) – Level 3
// ├── 0 -> Leaf (Key = 3302, Path = 53302) – Level 4
// └── 2 -> Leaf (Key = 3320, Path = 53320) – Level 4
sparse
.update_leaf(Nibbles::from_nibbles([0x5, 0x0, 0x2, 0x3, 0x1]), value.clone())
.unwrap();
sparse
.update_leaf(Nibbles::from_nibbles([0x5, 0x0, 0x2, 0x3, 0x3]), value.clone())
.unwrap();
sparse
.update_leaf(Nibbles::from_nibbles([0x5, 0x2, 0x0, 0x1, 0x3]), value.clone())
.unwrap();
sparse
.update_leaf(Nibbles::from_nibbles([0x5, 0x3, 0x1, 0x0, 0x2]), value.clone())
.unwrap();
sparse
.update_leaf(Nibbles::from_nibbles([0x5, 0x3, 0x3, 0x0, 0x2]), value.clone())
.unwrap();
sparse.update_leaf(Nibbles::from_nibbles([0x5, 0x3, 0x3, 0x2, 0x0]), value).unwrap();
assert_eq!(
sparse.get_changed_nodes_at_depth(&mut PrefixSet::default(), 0),
vec![Nibbles::default()]
);
assert_eq!(
sparse.get_changed_nodes_at_depth(&mut PrefixSet::default(), 1),
vec![Nibbles::from_nibbles_unchecked([0x5])]
);
assert_eq!(
sparse.get_changed_nodes_at_depth(&mut PrefixSet::default(), 2),
vec![
Nibbles::from_nibbles_unchecked([0x5, 0x0]),
Nibbles::from_nibbles_unchecked([0x5, 0x2]),
Nibbles::from_nibbles_unchecked([0x5, 0x3])
]
);
assert_eq!(
sparse.get_changed_nodes_at_depth(&mut PrefixSet::default(), 3),
vec![
Nibbles::from_nibbles_unchecked([0x5, 0x0, 0x2, 0x3]),
Nibbles::from_nibbles_unchecked([0x5, 0x2]),
Nibbles::from_nibbles_unchecked([0x5, 0x3, 0x1]),
Nibbles::from_nibbles_unchecked([0x5, 0x3, 0x3])
]
);
assert_eq!(
sparse.get_changed_nodes_at_depth(&mut PrefixSet::default(), 4),
vec![
Nibbles::from_nibbles_unchecked([0x5, 0x0, 0x2, 0x3, 0x1]),
Nibbles::from_nibbles_unchecked([0x5, 0x0, 0x2, 0x3, 0x3]),
Nibbles::from_nibbles_unchecked([0x5, 0x2]),
Nibbles::from_nibbles_unchecked([0x5, 0x3, 0x1]),
Nibbles::from_nibbles_unchecked([0x5, 0x3, 0x3, 0x0]),
Nibbles::from_nibbles_unchecked([0x5, 0x3, 0x3, 0x2])
]
);
}
#[test]
fn hash_builder_branch_hash_mask() {
let key1 = || pad_nibbles_left(Nibbles::from_nibbles_unchecked([0x00]));
let key2 = || pad_nibbles_left(Nibbles::from_nibbles_unchecked([0x01]));
let value = || Account { bytecode_hash: Some(B256::repeat_byte(1)), ..Default::default() };
let value_encoded = || {
let mut account_rlp = Vec::new();
value().into_trie_account(EMPTY_ROOT_HASH).encode(&mut account_rlp);
account_rlp
};
let (hash_builder_root, hash_builder_updates, _, _) = run_hash_builder(
[(key1(), value()), (key2(), value())],
Default::default(),
[Nibbles::default()],
);
let mut sparse = RevealedSparseTrie::default();
sparse.update_leaf(key1(), value_encoded()).unwrap();
sparse.update_leaf(key2(), value_encoded()).unwrap();
let sparse_root = sparse.root();
let sparse_updates = sparse.take_updates();
assert_eq!(sparse_root, hash_builder_root);
assert_eq!(sparse_updates.updated_nodes, hash_builder_updates.account_nodes);
}
#[test]
fn sparse_trie_wipe() {
let mut sparse = RevealedSparseTrie::default().with_updates(true);
let value = alloy_rlp::encode_fixed_size(&U256::ZERO).to_vec();
// Extension (Key = 5) – Level 0
// └── Branch (Mask = 1011) – Level 1
// ├── 0 -> Extension (Key = 23) – Level 2
// │ └── Branch (Mask = 0101) – Level 3
// │ ├── 1 -> Leaf (Key = 1, Path = 50231) – Level 4
// │ └── 3 -> Leaf (Key = 3, Path = 50233) – Level 4
// ├── 2 -> Leaf (Key = 013, Path = 52013) – Level 2
// └── 3 -> Branch (Mask = 0101) – Level 2
// ├── 1 -> Leaf (Key = 3102, Path = 53102) – Level 3
// └── 3 -> Branch (Mask = 1010) – Level 3
// ├── 0 -> Leaf (Key = 3302, Path = 53302) – Level 4
// └── 2 -> Leaf (Key = 3320, Path = 53320) – Level 4
sparse
.update_leaf(Nibbles::from_nibbles([0x5, 0x0, 0x2, 0x3, 0x1]), value.clone())
.unwrap();
sparse
.update_leaf(Nibbles::from_nibbles([0x5, 0x0, 0x2, 0x3, 0x3]), value.clone())
.unwrap();
sparse
.update_leaf(Nibbles::from_nibbles([0x5, 0x2, 0x0, 0x1, 0x3]), value.clone())
.unwrap();
sparse
.update_leaf(Nibbles::from_nibbles([0x5, 0x3, 0x1, 0x0, 0x2]), value.clone())
.unwrap();
sparse
.update_leaf(Nibbles::from_nibbles([0x5, 0x3, 0x3, 0x0, 0x2]), value.clone())
.unwrap();
sparse.update_leaf(Nibbles::from_nibbles([0x5, 0x3, 0x3, 0x2, 0x0]), value).unwrap();
sparse.wipe();
assert_eq!(sparse.root(), EMPTY_ROOT_HASH);
}
}