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
//! Effects subsystem.
//!
//! Effects describe things that the creator of the effect intends to happen, producing a value upon
//! completion (they actually are boxed futures).
//!
//! A pinned, boxed future returning an event is called an effect and typed as an `Effect<Ev>`,
//! where `Ev` is the event's type, as every effect must have its return value either wrapped in an
//! event through [`EffectExt::event`](crate::effect::EffectExt::event) or ignored using
//! [`EffectExt::ignore`](crate::effect::EffectExt::ignore). As an example, the
//! [`handle_event`](crate::components::Component::handle_event) function of a component always
//! returns `Effect<Self::Event>`.
//!
//! # A primer on events
//!
//! There are three distinct groups of events found around the node:
//!
//! * (unbound) events: These events are not associated with a particular reactor or component and
//! represent information or requests by themselves. An example is the
//! [`PeerBehaviorAnnouncement`](`crate::effect::announcements::PeerBehaviorAnnouncement`), it can
//! be emitted through an effect by different components and contains the ID of a peer that should
//! be shunned. It is not associated with a particular reactor or component though.
//!
//! While the node is running, these unbound events cannot exist on their own, instead they are
//! typically converted into a concrete reactor event by the effect builder as soon as they are
//! created.
//!
//! * reactor events: A running reactor has a single event type that encompasses all possible
//! unbound events that can occur during its operation and all component events of components it
//! is made of. Usually they are implemented as one large `enum` with only newtype-variants.
//!
//! * component events: Every component defines its own set of events, typically for internal use.
//! If the component is able to process unbound events like announcements or requests, it will
//! have a `From` implementation that allows converting them into a suitable component event.
//!
//! Component events are also created from the return values of effects: While effects do not
//! return events themselves when called, their return values are turned first into component
//! events through the [`event`](crate::effect::EffectExt) method. In a second step, inside the
//! reactors routing code, `wrap_effect` will then convert from component to reactor event.
//!
//! # Using effects
//!
//! To create an effect, an `EffectBuilder` will be passed in by the calling reactor runner. For
//! example, given an effect builder `effect_builder`, we can create a `set_timeout` future and turn
//! it into an effect:
//!
//! ```ignore
//! use std::time::Duration;
//! use casper_node::effect::EffectExt;
//!
//! // Note: This is our "component" event.
//! enum Event {
//! ThreeSecondsElapsed(Duration)
//! }
//!
//! effect_builder
//! .set_timeout(Duration::from_secs(3))
//! .event(Event::ThreeSecondsElapsed);
//! ```
//!
//! This example will produce an effect that, after three seconds, creates an
//! `Event::ThreeSecondsElapsed`. Note that effects do nothing on their own, they need to be passed
//! to a [`reactor`](../reactor/index.html) to be executed.
//!
//! # Arbitrary effects
//!
//! While it is technically possible to turn any future into an effect, it is in general advisable
//! to only use the methods on [`EffectBuilder`] or short, anonymous futures to create effects.
//!
//! # Announcements and requests
//!
//! Events are usually classified into either announcements or requests, although these properties
//! are not reflected in the type system.
//!
//! **Announcements** are events that are essentially "fire-and-forget"; the component that created
//! the effect resulting in the creation of the announcement will never expect an "answer".
//! Announcements are often dispatched to multiple components by the reactor; since that usually
//! involves a [`clone`](`Clone::clone`), they should be kept light.
//!
//! A good example is the arrival of a new deploy passed in by a client. Depending on the setup it
//! may be stored, buffered or, in certain testing setups, just discarded. None of this is a concern
//! of the component that talks to the client and deserializes the incoming deploy though, instead
//! it simply returns an effect that produces an announcement.
//!
//! **Requests** are complex events that are used when a component needs something from other
//! components. Typically, an effect (which uses [`EffectBuilder::make_request`] in its
//! implementation) is called resulting in the actual request being scheduled and handled. In
//! contrast to announcements, requests must always be handled by exactly one component.
//!
//! Every request has a [`Responder`]-typed field, which a handler of a request calls to produce
//! another effect that will send the return value to the original requesting component. Failing to
//! call the [`Responder::respond`] function will result in a runtime warning.
pub(crate) mod announcements;
pub(crate) mod diagnostics_port;
pub(crate) mod incoming;
pub(crate) mod requests;
use std::{
any::type_name,
borrow::Cow,
collections::{BTreeMap, HashMap, HashSet},
fmt::{self, Debug, Display, Formatter},
future::Future,
mem,
sync::Arc,
time::{Duration, Instant},
};
use datasize::DataSize;
use futures::{channel::oneshot, future::BoxFuture, FutureExt};
use once_cell::sync::Lazy;
use serde::{Serialize, Serializer};
use smallvec::{smallvec, SmallVec};
use tokio::{sync::Semaphore, time};
use tracing::{debug, error, warn};
use casper_execution_engine::{
core::engine_state::{
self, era_validators::GetEraValidatorsError, BalanceRequest, BalanceResult, GetBidsRequest,
GetBidsResult, QueryRequest, QueryResult,
},
shared::execution_journal::ExecutionJournal,
storage::trie::TrieRaw,
};
use casper_hashing::Digest;
use casper_types::{
account::Account, bytesrepr::Bytes, system::auction::EraValidators, Contract, ContractPackage,
EraId, ExecutionEffect, ExecutionResult, Key, PublicKey, TimeDiff, Timestamp, Transfer, URef,
U512,
};
use crate::{
components::{
block_synchronizer::{
BlockSynchronizerStatus, GlobalStateSynchronizerError, GlobalStateSynchronizerResponse,
TrieAccumulatorError, TrieAccumulatorResponse,
},
consensus::{ClContext, EraDump, ProposedBlock, ValidatorChange},
contract_runtime::{ContractRuntimeError, EraValidatorsRequest},
deploy_acceptor,
diagnostics_port::StopAtSpec,
fetcher::{FetchItem, FetchResult},
gossiper::GossipItem,
network::{blocklist::BlocklistJustification, FromIncoming, NetworkInsights},
upgrade_watcher::NextUpgrade,
},
contract_runtime::SpeculativeExecutionState,
failpoints::FailpointActivation,
reactor::{main_reactor::ReactorState, EventQueueHandle, QueueKind},
types::{
appendable_block::AppendableBlock, ApprovalsHashes, AvailableBlockRange, Block,
BlockExecutionResultsOrChunk, BlockExecutionResultsOrChunkId, BlockHash, BlockHeader,
BlockSignatures, BlockWithMetadata, ChainspecRawBytes, Deploy, DeployHash, DeployHeader,
DeployId, DeployMetadataExt, DeployWithFinalizedApprovals, FinalitySignature,
FinalitySignatureId, FinalizedApprovals, FinalizedBlock, LegacyDeploy, MetaBlock,
MetaBlockState, NodeId, TrieOrChunk, TrieOrChunkId,
},
utils::{fmt_limit::FmtLimit, SharedFlag, Source},
};
use announcements::{
BlockAccumulatorAnnouncement, ConsensusAnnouncement, ContractRuntimeAnnouncement,
ControlAnnouncement, DeployAcceptorAnnouncement, DeployBufferAnnouncement, FatalAnnouncement,
FetchedNewBlockAnnouncement, FetchedNewFinalitySignatureAnnouncement, GossiperAnnouncement,
MetaBlockAnnouncement, PeerBehaviorAnnouncement, QueueDumpFormat, UnexecutedBlockAnnouncement,
UpgradeWatcherAnnouncement,
};
use diagnostics_port::DumpConsensusStateRequest;
use requests::{
AcceptDeployRequest, BeginGossipRequest, BlockAccumulatorRequest, BlockSynchronizerRequest,
BlockValidationRequest, ChainspecRawBytesRequest, ConsensusRequest, ContractRuntimeRequest,
DeployBufferRequest, FetcherRequest, MakeBlockExecutableRequest, MarkBlockCompletedRequest,
MetricsRequest, NetworkInfoRequest, NetworkRequest, ReactorStatusRequest, SetNodeStopRequest,
StorageRequest, SyncGlobalStateRequest, TrieAccumulatorRequest, UpgradeWatcherRequest,
};
/// A resource that will never be available, thus trying to acquire it will wait forever.
static UNOBTAINABLE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(0));
/// A pinned, boxed future that produces one or more events.
pub(crate) type Effect<Ev> = BoxFuture<'static, Multiple<Ev>>;
/// Multiple effects in a container.
pub(crate) type Effects<Ev> = Multiple<Effect<Ev>>;
/// A small collection of rarely more than two items.
///
/// Stored in a `SmallVec` to avoid allocations in case there are less than three items grouped. The
/// size of two items is chosen because one item is the most common use case, and large items are
/// typically boxed. In the latter case two pointers and one enum variant discriminator is almost
/// the same size as an empty vec, which is two pointers.
pub(crate) type Multiple<T> = SmallVec<[T; 2]>;
/// The type of peers that should receive the gossip message.
#[derive(Debug, Serialize, PartialEq, Eq, Hash, Copy, Clone, DataSize)]
pub(crate) enum GossipTarget {
/// Both validators and non validators.
Mixed(EraId),
/// All peers.
All,
}
impl Display for GossipTarget {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
GossipTarget::Mixed(era_id) => write!(formatter, "gossip target mixed for {}", era_id),
GossipTarget::All => write!(formatter, "gossip target all"),
}
}
}
/// A responder satisfying a request.
#[must_use]
#[derive(DataSize)]
pub(crate) struct Responder<T> {
/// Sender through which the response ultimately should be sent.
sender: Option<oneshot::Sender<T>>,
/// Reactor flag indicating shutdown.
is_shutting_down: SharedFlag,
}
/// A responder that will automatically send a `None` on drop.
#[must_use]
#[derive(DataSize, Debug)]
pub(crate) struct AutoClosingResponder<T>(Responder<Option<T>>);
impl<T> AutoClosingResponder<T> {
/// Creates a new auto closing responder from a responder of `Option<T>`.
pub(crate) fn from_opt_responder(responder: Responder<Option<T>>) -> Self {
AutoClosingResponder(responder)
}
/// Extracts the inner responder.
fn into_inner(mut self) -> Responder<Option<T>> {
let is_shutting_down = self.0.is_shutting_down;
mem::replace(
&mut self.0,
Responder {
sender: None,
is_shutting_down,
},
)
}
}
impl<T: Debug> AutoClosingResponder<T> {
/// Send `Some(data)` to the origin of the request.
pub(crate) async fn respond(self, data: T) {
self.into_inner().respond(Some(data)).await
}
/// Send `None` to the origin of the request.
pub(crate) async fn respond_none(self) {
self.into_inner().respond(None).await
}
}
impl<T> Drop for AutoClosingResponder<T> {
fn drop(&mut self) {
if let Some(sender) = self.0.sender.take() {
debug!(
sending_value = %self.0,
"responding None by dropping auto-close responder"
);
// We still haven't answered, send an answer.
if let Err(_unsent_value) = sender.send(None) {
debug!(
unsent_value = %self.0,
"failed to auto-close responder, ignoring"
)
}
}
}
}
impl<T: 'static + Send> Responder<T> {
/// Creates a new `Responder`.
#[inline]
fn new(sender: oneshot::Sender<T>, is_shutting_down: SharedFlag) -> Self {
Responder {
sender: Some(sender),
is_shutting_down,
}
}
/// Helper method for tests.
///
/// Allows creating a responder manually, without observing the shutdown flag. This function
/// should not be used, unless you are writing alternative infrastructure, e.g. for tests.
#[cfg(test)]
#[inline]
pub(crate) fn without_shutdown(sender: oneshot::Sender<T>) -> Self {
Responder::new(sender, SharedFlag::global_shared())
}
}
impl<T: Debug> Responder<T> {
/// Send `data` to the origin of the request.
pub(crate) async fn respond(mut self, data: T) {
if let Some(sender) = self.sender.take() {
if let Err(data) = sender.send(data) {
// If we cannot send a response down the channel, it means the original requester is
// no longer interested in our response. This typically happens during shutdowns, or
// in cases where an originating external request has been cancelled.
debug!(
data=?FmtLimit::new(1000, &data),
"ignored failure to send response to request down oneshot channel"
);
}
} else {
error!(
data=?FmtLimit::new(1000, &data),
"tried to send a value down a responder channel, but it was already used"
);
}
}
}
impl<T> Debug for Responder<T> {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
write!(formatter, "Responder<{}>", type_name::<T>(),)
}
}
impl<T> Display for Responder<T> {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
write!(formatter, "responder({})", type_name::<T>(),)
}
}
impl<T> Drop for Responder<T> {
fn drop(&mut self) {
if self.sender.is_some() {
if self.is_shutting_down.is_set() {
debug!(
responder=?self,
"ignored dropping of responder during shutdown"
);
} else {
// This is usually a very serious error, as another component will now be stuck.
//
// See the code `make_request` for more details.
error!(
responder=?self,
"dropped without being responded to outside of shutdown"
);
}
}
}
}
impl<T> Serialize for Responder<T> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&format!("{:?}", self))
}
}
impl<T> Serialize for AutoClosingResponder<T> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.0.serialize(serializer)
}
}
/// Effect extension for futures, used to convert futures into actual effects.
pub(crate) trait EffectExt: Future + Send {
/// Finalizes a future into an effect that returns a single event.
///
/// The function `f` is used to translate the returned value from an effect into an event.
fn event<U, F>(self, f: F) -> Effects<U>
where
F: FnOnce(Self::Output) -> U + 'static + Send,
U: 'static,
Self: Sized;
/// Finalizes a future into an effect that returns an iterator of events.
///
/// The function `f` is used to translate the returned value from an effect into an iterator of
/// events.
fn events<U, F, I>(self, f: F) -> Effects<U>
where
F: FnOnce(Self::Output) -> I + 'static + Send,
U: 'static,
I: Iterator<Item = U>,
Self: Sized;
/// Finalizes a future into an effect that runs but drops the result.
fn ignore<Ev>(self) -> Effects<Ev>;
}
/// Effect extension for futures, used to convert futures returning a `Result` into two different
/// effects.
pub(crate) trait EffectResultExt {
/// The type the future will return if `Ok`.
type Value;
/// The type the future will return if `Err`.
type Error;
/// Finalizes a future returning a `Result` into two different effects.
///
/// The function `f_ok` is used to translate the returned value from an effect into an event,
/// while the function `f_err` does the same for a potential error.
fn result<U, F, G>(self, f_ok: F, f_err: G) -> Effects<U>
where
F: FnOnce(Self::Value) -> U + 'static + Send,
G: FnOnce(Self::Error) -> U + 'static + Send,
U: 'static;
}
/// Effect extension for futures, used to convert futures returning an `Option` into two different
/// effects.
pub(crate) trait EffectOptionExt {
/// The type the future will return if `Some`.
type Value;
/// Finalizes a future returning an `Option` into two different effects.
///
/// The function `f_some` is used to translate the returned value from an effect into an event,
/// while the function `f_none` does the same for a returned `None`.
fn map_or_else<U, F, G>(self, f_some: F, f_none: G) -> Effects<U>
where
F: FnOnce(Self::Value) -> U + 'static + Send,
G: FnOnce() -> U + 'static + Send,
U: 'static;
/// Finalizes a future returning an `Option` into two different effects.
///
/// The function `f` is used to translate the returned value from an effect into an event,
/// In the case of `None`, empty vector of effects is returned.
fn map_some<U, F>(self, f: F) -> Effects<U>
where
F: FnOnce(Self::Value) -> U + 'static + Send,
U: 'static;
}
impl<T: ?Sized> EffectExt for T
where
T: Future + Send + 'static + Sized,
{
fn event<U, F>(self, f: F) -> Effects<U>
where
F: FnOnce(Self::Output) -> U + 'static + Send,
U: 'static,
{
smallvec![self.map(f).map(|item| smallvec![item]).boxed()]
}
fn events<U, F, I>(self, f: F) -> Effects<U>
where
F: FnOnce(Self::Output) -> I + 'static + Send,
U: 'static,
I: Iterator<Item = U>,
{
smallvec![self.map(f).map(|iter| iter.collect()).boxed()]
}
fn ignore<Ev>(self) -> Effects<Ev> {
smallvec![self.map(|_| Multiple::new()).boxed()]
}
}
impl<T, V, E> EffectResultExt for T
where
T: Future<Output = Result<V, E>> + Send + 'static + Sized,
T: ?Sized,
{
type Value = V;
type Error = E;
fn result<U, F, G>(self, f_ok: F, f_err: G) -> Effects<U>
where
F: FnOnce(V) -> U + 'static + Send,
G: FnOnce(E) -> U + 'static + Send,
U: 'static,
{
smallvec![self
.map(|result| result.map_or_else(f_err, f_ok))
.map(|item| smallvec![item])
.boxed()]
}
}
impl<T, V> EffectOptionExt for T
where
T: Future<Output = Option<V>> + Send + 'static + Sized,
T: ?Sized,
{
type Value = V;
fn map_or_else<U, F, G>(self, f_some: F, f_none: G) -> Effects<U>
where
F: FnOnce(V) -> U + 'static + Send,
G: FnOnce() -> U + 'static + Send,
U: 'static,
{
smallvec![self
.map(|option| option.map_or_else(f_none, f_some))
.map(|item| smallvec![item])
.boxed()]
}
/// Finalizes a future returning an `Option`.
///
/// The function `f` is used to translate the returned value from an effect into an event,
/// In the case of `None`, empty vector is returned.
fn map_some<U, F>(self, f: F) -> Effects<U>
where
F: FnOnce(Self::Value) -> U + 'static + Send,
U: 'static,
{
smallvec![self
.map(|option| option
.map(|el| smallvec![f(el)])
.unwrap_or_else(|| smallvec![]))
.boxed()]
}
}
/// A builder for [`Effect`](type.Effect.html)s.
///
/// Provides methods allowing the creation of effects which need to be scheduled on the reactor's
/// event queue, without giving direct access to this queue.
///
/// The `REv` type parameter indicates which reactor event effects created by this builder will
/// produce as side-effects.
#[derive(Debug)]
pub(crate) struct EffectBuilder<REv: 'static> {
/// A handle to the referenced event queue.
event_queue: EventQueueHandle<REv>,
}
// Implement `Clone` and `Copy` manually, as `derive` will make it depend on `REv` otherwise.
impl<REv> Clone for EffectBuilder<REv> {
fn clone(&self) -> Self {
*self
}
}
impl<REv> Copy for EffectBuilder<REv> {}
impl<REv> EffectBuilder<REv> {
/// Creates a new effect builder.
pub(crate) fn new(event_queue: EventQueueHandle<REv>) -> Self {
EffectBuilder { event_queue }
}
/// Extract the event queue handle out of the effect builder.
pub(crate) fn into_inner(self) -> EventQueueHandle<REv> {
self.event_queue
}
/// Performs a request.
///
/// Given a request `Q`, that when completed will yield a result of `T`, produces a future that
/// will
///
/// 1. create an event to send the request to the respective component (thus `Q: Into<REv>`),
/// 2. wait for a response and return it.
///
/// This function is usually only used internally by effects implemented on the effects builder,
/// but IO components may also make use of it.
///
/// # Cancellation safety
///
/// This future is cancellation safe: If it is dropped without being polled, it merely indicates
/// the original requester is not longer interested in the result, which will be discarded.
pub(crate) async fn make_request<T, Q, F>(self, f: F, queue_kind: QueueKind) -> T
where
T: Send + 'static,
Q: Into<REv>,
F: FnOnce(Responder<T>) -> Q,
{
let (event, wait_future) = self.create_request_parts(f);
// Schedule the request before awaiting the response.
self.event_queue.schedule(event, queue_kind).await;
wait_future.await
}
/// Creates the part necessary to make a request.
///
/// A request usually consists of two parts: The request event that needs to be scheduled on the
/// reactor queue and associated future that allows waiting for the response. This function
/// creates both of them without processing or spawning either.
///
/// Usually you will want to call the higher level `make_request` function.
pub(crate) fn create_request_parts<T, Q, F>(self, f: F) -> (REv, impl Future<Output = T>)
where
T: Send + 'static,
Q: Into<REv>,
F: FnOnce(Responder<T>) -> Q,
{
// Prepare a channel.
let (sender, receiver) = oneshot::channel();
// Create response function.
let responder = Responder::new(sender, self.event_queue.shutdown_flag());
// Now inject the request event into the event loop.
let request_event = f(responder).into();
let fut = async move {
match receiver.await {
Ok(value) => value,
Err(err) => {
// The channel should usually not be closed except during shutdowns, as it
// indicates a panic or disappearance of the remote that is
// supposed to process the request.
//
// If it does happen, we pretend nothing happened instead of crashing.
if self.event_queue.shutdown_flag().is_set() {
debug!(%err, channel=?type_name::<T>(), "ignoring closed channel due to shutdown")
} else {
error!(%err, channel=?type_name::<T>(), "request for channel closed, this may be a bug? \
check if a component is stuck from now on");
}
// We cannot produce any value to satisfy the request, so we just abandon this
// task by waiting on a resource we can never acquire.
let _ = UNOBTAINABLE.acquire().await;
panic!("should never obtain unobtainable semaphore");
}
}
};
(request_event, fut)
}
/// Run and end effect immediately.
///
/// Can be used to trigger events from effects when combined with `.event`. Do not use this to
/// "do nothing", as it will still cause a task to be spawned.
#[inline(always)]
#[allow(clippy::manual_async_fn)]
pub(crate) fn immediately(self) -> impl Future<Output = ()> + Send {
// Note: This function is implemented manually without `async` sugar because the `Send`
// inference seems to not work in all cases otherwise.
async {}
}
/// Reports a fatal error. Normally called via the `crate::fatal!()` macro.
///
/// Usually causes the node to cease operations quickly and exit/crash.
pub(crate) async fn fatal(self, file: &'static str, line: u32, msg: String)
where
REv: From<FatalAnnouncement>,
{
self.event_queue
.schedule(FatalAnnouncement { file, line, msg }, QueueKind::Control)
.await
}
/// Sets a timeout.
pub(crate) async fn set_timeout(self, timeout: Duration) -> Duration {
let then = Instant::now();
time::sleep(timeout).await;
Instant::now() - then
}
/// Retrieve a snapshot of the nodes current metrics formatted as string.
///
/// If an error occurred producing the metrics, `None` is returned.
pub(crate) async fn get_metrics(self) -> Option<String>
where
REv: From<MetricsRequest>,
{
self.make_request(
|responder| MetricsRequest::RenderNodeMetricsText { responder },
QueueKind::Api,
)
.await
}
/// Sends a network message.
///
/// The message is queued and sent, but no delivery guaranteed. Will return after the message
/// has been buffered in the outgoing kernel buffer and thus is subject to backpressure.
pub(crate) async fn send_message<P>(self, dest: NodeId, payload: P)
where
REv: From<NetworkRequest<P>>,
{
self.make_request(
|responder| NetworkRequest::SendMessage {
dest: Box::new(dest),
payload: Box::new(payload),
respond_after_queueing: false,
auto_closing_responder: AutoClosingResponder::from_opt_responder(responder),
},
QueueKind::Network,
)
.await;
}
/// Enqueues a network message.
///
/// The message is queued in "fire-and-forget" fashion, there is no guarantee that the peer
/// will receive it. Returns as soon as the message is queued inside the networking component.
pub(crate) async fn enqueue_message<P>(self, dest: NodeId, payload: P)
where
REv: From<NetworkRequest<P>>,
{
self.make_request(
|responder| NetworkRequest::SendMessage {
dest: Box::new(dest),
payload: Box::new(payload),
respond_after_queueing: true,
auto_closing_responder: AutoClosingResponder::from_opt_responder(responder),
},
QueueKind::Network,
)
.await;
}
/// Broadcasts a network message to validator peers in the given era.
pub(crate) async fn broadcast_message_to_validators<P>(self, payload: P, era_id: EraId)
where
REv: From<NetworkRequest<P>>,
{
self.make_request(
|responder| {
debug!("validator broadcast for {}", era_id);
NetworkRequest::ValidatorBroadcast {
payload: Box::new(payload),
era_id,
auto_closing_responder: AutoClosingResponder::from_opt_responder(responder),
}
},
QueueKind::Network,
)
.await;
}
/// Gossips a network message.
///
/// A low-level "gossip" function, selects `count` randomly chosen nodes on the network,
/// excluding the indicated ones, and sends each a copy of the message.
///
/// Returns the IDs of the chosen nodes.
pub(crate) async fn gossip_message<P>(
self,
payload: P,
gossip_target: GossipTarget,
count: usize,
exclude: HashSet<NodeId>,
) -> HashSet<NodeId>
where
REv: From<NetworkRequest<P>>,
P: Send,
{
self.make_request(
|responder| NetworkRequest::Gossip {
payload: Box::new(payload),
gossip_target,
count,
exclude,
auto_closing_responder: AutoClosingResponder::from_opt_responder(responder),
},
QueueKind::Network,
)
.await
.unwrap_or_default()
}
/// Gets a structure describing the current network status.
pub(crate) async fn get_network_insights(self) -> NetworkInsights
where
REv: From<NetworkInfoRequest>,
{
self.make_request(
|responder| NetworkInfoRequest::Insight { responder },
QueueKind::Regular,
)
.await
}
/// Gets a map of the current network peers to their socket addresses.
pub(crate) async fn network_peers(self) -> BTreeMap<NodeId, String>
where
REv: From<NetworkInfoRequest>,
{
self.make_request(
|responder| NetworkInfoRequest::Peers { responder },
QueueKind::Api,
)
.await
}
/// Gets up to `count` fully-connected network peers in random order.
pub async fn get_fully_connected_peers(self, count: usize) -> Vec<NodeId>
where
REv: From<NetworkInfoRequest>,
{
self.make_request(
|responder| NetworkInfoRequest::FullyConnectedPeers { count, responder },
QueueKind::NetworkInfo,
)
.await
}
/// Announces which deploys have expired.
pub(crate) async fn announce_expired_deploys(self, hashes: Vec<DeployHash>)
where
REv: From<DeployBufferAnnouncement>,
{
self.event_queue
.schedule(
DeployBufferAnnouncement::DeploysExpired(hashes),
QueueKind::Validation,
)
.await;
}
/// Announces an incoming network message.
pub(crate) async fn announce_incoming<P>(self, sender: NodeId, payload: P)
where
REv: FromIncoming<P>,
{
self.event_queue
.schedule(
<REv as FromIncoming<P>>::from_incoming(sender, payload),
QueueKind::NetworkIncoming,
)
.await
}
/// Announces that a gossiper has received a new item, where the item's ID is the complete item.
pub(crate) async fn announce_complete_item_received_via_gossip<T: GossipItem>(self, item: T::Id)
where
REv: From<GossiperAnnouncement<T>>,
{
assert!(
T::ID_IS_COMPLETE_ITEM,
"{} must be an item where the ID _is_ the complete item",
item
);
self.event_queue
.schedule(
GossiperAnnouncement::NewCompleteItem(item),
QueueKind::Gossip,
)
.await;
}
/// Announces that a gossiper has received a full item, where the item's ID is NOT the complete
/// item.
pub(crate) async fn announce_item_body_received_via_gossip<T: GossipItem>(
self,
item: Box<T>,
sender: NodeId,
) where
REv: From<GossiperAnnouncement<T>>,
{
self.event_queue
.schedule(
GossiperAnnouncement::NewItemBody { item, sender },
QueueKind::Gossip,
)
.await;
}
/// Announces that the block accumulator has received and stored a new finality signature.
pub(crate) async fn announce_finality_signature_accepted(
self,
finality_signature: Box<FinalitySignature>,
) where
REv: From<BlockAccumulatorAnnouncement>,
{
self.event_queue
.schedule(
BlockAccumulatorAnnouncement::AcceptedNewFinalitySignature { finality_signature },
QueueKind::FinalitySignature,
)
.await;
}
/// Request that a block be made executable (i.e. produce a FinalizedBlock plus any Deploys),
/// if able to.
///
/// Completion means that the block can be enqueued for processing by the execution engine via
/// the contract_runtime component.
pub(crate) async fn make_block_executable(
self,
block_hash: BlockHash,
) -> Option<(FinalizedBlock, Vec<Deploy>)>
where
REv: From<MakeBlockExecutableRequest>,
{
self.make_request(
|responder| MakeBlockExecutableRequest {
block_hash,
responder,
},
QueueKind::FromStorage,
)
.await
}
/// Request that a block with a specific height be marked completed.
///
/// Completion means that the block itself (along with its header) and all of its deploys have
/// been persisted to storage and its global state root hash is missing no dependencies in the
/// global state.
pub(crate) async fn mark_block_completed(self, block_height: u64) -> bool
where
REv: From<MarkBlockCompletedRequest>,
{
self.make_request(
|responder| MarkBlockCompletedRequest {
block_height,
responder,
},
QueueKind::FromStorage,
)
.await
}
/// Try to accept a deploy received from the JSON-RPC server.
pub(crate) async fn try_accept_deploy(
self,
deploy: Arc<Deploy>,
speculative_exec_at_block: Option<Box<BlockHeader>>,
) -> Result<(), deploy_acceptor::Error>
where
REv: From<AcceptDeployRequest>,
{
self.make_request(
|responder| AcceptDeployRequest {
deploy,
speculative_exec_at_block,
responder,
},
QueueKind::Api,
)
.await
}
/// Announces that a deploy not previously stored has now been accepted and stored.
pub(crate) fn announce_new_deploy_accepted(
self,
deploy: Arc<Deploy>,
source: Source,
) -> impl Future<Output = ()>
where
REv: From<DeployAcceptorAnnouncement>,
{
self.event_queue.schedule(
DeployAcceptorAnnouncement::AcceptedNewDeploy { deploy, source },
QueueKind::Validation,
)
}
/// Announces that we have received a gossip message from this peer,
/// implying the peer holds the indicated item.
pub(crate) async fn announce_gossip_received<T>(self, item_id: T::Id, sender: NodeId)
where
REv: From<GossiperAnnouncement<T>>,
T: GossipItem,
{
self.event_queue
.schedule(
GossiperAnnouncement::GossipReceived { item_id, sender },
QueueKind::Gossip,
)
.await;
}
/// Announces that we have finished gossiping the indicated item.
pub(crate) async fn announce_finished_gossiping<T>(self, item_id: T::Id)
where
REv: From<GossiperAnnouncement<T>>,
T: GossipItem,
{
self.event_queue
.schedule(
GossiperAnnouncement::FinishedGossiping(item_id),
QueueKind::Gossip,
)
.await;
}
/// Announces that an invalid deploy has been received.
pub(crate) fn announce_invalid_deploy(
self,
deploy: Arc<Deploy>,
source: Source,
) -> impl Future<Output = ()>
where
REv: From<DeployAcceptorAnnouncement>,
{
self.event_queue.schedule(
DeployAcceptorAnnouncement::InvalidDeploy { deploy, source },
QueueKind::Validation,
)
}
/// Announces upgrade activation point read.
pub(crate) async fn upgrade_watcher_announcement(self, maybe_next_upgrade: Option<NextUpgrade>)
where
REv: From<UpgradeWatcherAnnouncement>,
{
self.event_queue
.schedule(
UpgradeWatcherAnnouncement(maybe_next_upgrade),
QueueKind::Control,
)
.await
}
/// Announces a committed Step success.
pub(crate) async fn announce_commit_step_success(
self,
era_id: EraId,
execution_journal: ExecutionJournal,
) where
REv: From<ContractRuntimeAnnouncement>,
{
self.event_queue
.schedule(
ContractRuntimeAnnouncement::CommitStepSuccess {
era_id,
execution_effect: ExecutionEffect::from(&execution_journal),
},
QueueKind::ContractRuntime,
)
.await
}
/// Announces validators for upcoming era.
pub(crate) async fn announce_upcoming_era_validators(
self,
era_that_is_ending: EraId,
upcoming_era_validators: BTreeMap<EraId, BTreeMap<PublicKey, U512>>,
) where
REv: From<ContractRuntimeAnnouncement>,
{
self.event_queue
.schedule(
ContractRuntimeAnnouncement::UpcomingEraValidators {
era_that_is_ending,
upcoming_era_validators,
},
QueueKind::ContractRuntime,
)
.await
}
/// Begins gossiping an item.
pub(crate) async fn begin_gossip<T>(self, item_id: T::Id, source: Source, target: GossipTarget)
where
T: GossipItem,
REv: From<BeginGossipRequest<T>>,
{
self.make_request(
|responder| BeginGossipRequest {
item_id,
source,
target,
responder,
},
QueueKind::Gossip,
)
.await
}
/// Puts the given block into the linear block store.
pub(crate) async fn put_block_to_storage(self, block: Arc<Block>) -> bool
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::PutBlock { block, responder },
QueueKind::ToStorage,
)
.await
}
/// Puts the given approvals hashes into the linear block store.
pub(crate) async fn put_approvals_hashes_to_storage(
self,
approvals_hashes: Box<ApprovalsHashes>,
) -> bool
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::PutApprovalsHashes {
approvals_hashes,
responder,
},
QueueKind::ToStorage,
)
.await
}
/// Puts the given block and approvals hashes into the linear block store.
pub(crate) async fn put_executed_block_to_storage(
self,
block: Arc<Block>,
approvals_hashes: Box<ApprovalsHashes>,
execution_results: HashMap<DeployHash, ExecutionResult>,
) -> bool
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::PutExecutedBlock {
block,
approvals_hashes,
execution_results,
responder,
},
QueueKind::ToStorage,
)
.await
}
/// Gets the requested block from the linear block store.
pub(crate) async fn get_block_from_storage(self, block_hash: BlockHash) -> Option<Block>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetBlock {
block_hash,
responder,
},
QueueKind::FromStorage,
)
.await
}
pub(crate) async fn is_block_stored(self, block_hash: BlockHash) -> bool
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::IsBlockStored {
block_hash,
responder,
},
QueueKind::FromStorage,
)
.await
}
/// Gets the requested `ApprovalsHashes` from storage.
pub(crate) async fn get_approvals_hashes_from_storage(
self,
block_hash: BlockHash,
) -> Option<ApprovalsHashes>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetApprovalsHashes {
block_hash,
responder,
},
QueueKind::FromStorage,
)
.await
}
/// Gets the requested block header from the linear block store.
pub(crate) async fn get_block_header_from_storage(
self,
block_hash: BlockHash,
only_from_available_block_range: bool,
) -> Option<BlockHeader>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetBlockHeader {
block_hash,
only_from_available_block_range,
responder,
},
QueueKind::FromStorage,
)
.await
}
pub(crate) async fn get_block_header_at_height_from_storage(
self,
block_height: u64,
only_from_available_block_range: bool,
) -> Option<BlockHeader>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetBlockHeaderByHeight {
block_height,
only_from_available_block_range,
responder,
},
QueueKind::FromStorage,
)
.await
}
/// Gets the requested signature for a given block hash.
pub(crate) async fn get_signature_from_storage(
self,
block_hash: BlockHash,
public_key: PublicKey,
) -> Option<FinalitySignature>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetBlockSignature {
block_hash,
public_key: Box::new(public_key),
responder,
},
QueueKind::FromStorage,
)
.await
}
pub(crate) async fn get_execution_results_from_storage(
self,
block_hash: BlockHash,
) -> Option<Vec<(DeployHash, DeployHeader, ExecutionResult)>>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetExecutionResults {
block_hash,
responder,
},
QueueKind::FromStorage,
)
.await
}
/// Puts a block header to storage.
pub(crate) async fn put_block_header_to_storage(self, block_header: Box<BlockHeader>) -> bool
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::PutBlockHeader {
block_header,
responder,
},
QueueKind::ToStorage,
)
.await
}
/// Puts the requested block signatures into storage.
///
/// If `signatures.proofs` is empty, no attempt to store will be made, an error will be logged,
/// and this function will return `false`.
pub(crate) async fn put_signatures_to_storage(self, signatures: BlockSignatures) -> bool
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::PutBlockSignatures {
signatures,
responder,
},
QueueKind::ToStorage,
)
.await
}
pub(crate) async fn put_finality_signature_to_storage(
self,
signature: FinalitySignature,
) -> bool
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::PutFinalitySignature {
signature: Box::new(signature),
responder,
},
QueueKind::ToStorage,
)
.await
}
/// Gets the requested block's transfers from storage.
pub(crate) async fn get_block_transfers_from_storage(
self,
block_hash: BlockHash,
) -> Option<Vec<Transfer>>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetBlockTransfers {
block_hash,
responder,
},
QueueKind::FromStorage,
)
.await
}
/// Returns the era IDs of the blocks in which the given deploys were executed. If none of the
/// deploys have been executed yet, an empty set will be returned.
pub(crate) async fn get_deploys_era_ids(
self,
deploy_hashes: HashSet<DeployHash>,
) -> HashSet<EraId>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetDeploysEraIds {
deploy_hashes,
responder,
},
QueueKind::FromStorage,
)
.await
}
/// Requests the highest complete block.
pub(crate) async fn get_highest_complete_block_from_storage(self) -> Option<Block>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetHighestCompleteBlock { responder },
QueueKind::FromStorage,
)
.await
}
/// Requests the highest complete block header.
pub(crate) async fn get_highest_complete_block_header_from_storage(self) -> Option<BlockHeader>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetHighestCompleteBlockHeader { responder },
QueueKind::FromStorage,
)
.await
}
/// Requests the height range of fully available blocks (not just block headers).
pub(crate) async fn get_available_block_range_from_storage(self) -> AvailableBlockRange
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetAvailableBlockRange { responder },
QueueKind::FromStorage,
)
.await
}
/// Synchronize global state under the given root hash.
pub(crate) async fn sync_global_state(
self,
block_hash: BlockHash,
state_root_hash: Digest,
) -> Result<GlobalStateSynchronizerResponse, GlobalStateSynchronizerError>
where
REv: From<SyncGlobalStateRequest>,
{
self.make_request(
|responder| SyncGlobalStateRequest {
block_hash,
state_root_hash,
responder,
},
QueueKind::SyncGlobalState,
)
.await
}
/// Get a trie or chunk by its ID.
pub(crate) async fn get_trie(
self,
trie_or_chunk_id: TrieOrChunkId,
) -> Result<Option<TrieOrChunk>, ContractRuntimeError>
where
REv: From<ContractRuntimeRequest>,
{
self.make_request(
|responder| ContractRuntimeRequest::GetTrie {
trie_or_chunk_id,
responder,
},
QueueKind::ContractRuntime,
)
.await
}
pub(crate) async fn get_reactor_status(self) -> (ReactorState, Timestamp)
where
REv: From<ReactorStatusRequest>,
{
self.make_request(ReactorStatusRequest, QueueKind::Regular)
.await
}
pub(crate) async fn get_block_synchronizer_status(self) -> BlockSynchronizerStatus
where
REv: From<BlockSynchronizerRequest>,
{
self.make_request(
|responder| BlockSynchronizerRequest::Status { responder },
QueueKind::Regular,
)
.await
}
/// Get a trie by its hash key.
pub(crate) async fn get_trie_full(
self,
trie_key: Digest,
) -> Result<Option<Bytes>, engine_state::Error>
where
REv: From<ContractRuntimeRequest>,
{
self.make_request(
|responder| ContractRuntimeRequest::GetTrieFull {
trie_key,
responder,
},
QueueKind::ContractRuntime,
)
.await
}
/// Puts a trie into the trie store; succeeds only if all the children of the trie are already
/// present in the store.
/// Returns the digest under which the trie was stored if successful.
pub(crate) async fn put_trie_if_all_children_present(
self,
trie_bytes: TrieRaw,
) -> Result<Digest, engine_state::Error>
where
REv: From<ContractRuntimeRequest>,
{
self.make_request(
|responder| ContractRuntimeRequest::PutTrie {
trie_bytes,
responder,
},
QueueKind::ContractRuntime,
)
.await
}
/// Puts the given deploy into the deploy store.
pub(crate) async fn put_deploy_to_storage(self, deploy: Arc<Deploy>) -> bool
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::PutDeploy { deploy, responder },
QueueKind::ToStorage,
)
.await
}
/// Gets the requested deploys from the deploy store.
///
/// Returns the "original" deploys, which are the first received by the node, along with a
/// potentially different set of approvals used during execution of the recorded block.
pub(crate) async fn get_deploys_from_storage(
self,
deploy_hashes: Vec<DeployHash>,
) -> SmallVec<[Option<DeployWithFinalizedApprovals>; 1]>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetDeploys {
deploy_hashes,
responder,
},
QueueKind::FromStorage,
)
.await
}
/// Gets the requested deploy from the deploy store by DeployHash only.
///
/// Returns the legacy deploy containing the set of approvals used during execution of the
/// recorded block, if known.
pub(crate) async fn get_stored_legacy_deploy(
self,
deploy_hash: DeployHash,
) -> Option<LegacyDeploy>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetLegacyDeploy {
deploy_hash,
responder,
},
QueueKind::FromStorage,
)
.await
}
/// Gets the requested deploy from the deploy store by DeployId.
///
/// Returns the "original" deploy, which are the first received by the node, along with a
/// potentially different set of approvals used during execution of the recorded block.
pub(crate) async fn get_stored_deploy(self, deploy_id: DeployId) -> Option<Deploy>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetDeploy {
deploy_id,
responder,
},
QueueKind::FromStorage,
)
.await
}
pub(crate) async fn is_deploy_stored(self, deploy_id: DeployId) -> bool
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::IsDeployStored {
deploy_id,
responder,
},
QueueKind::FromStorage,
)
.await
}
/// Stores the given execution results for the deploys in the given block in the linear block
/// store.
pub(crate) async fn put_execution_results_to_storage(
self,
block_hash: BlockHash,
execution_results: HashMap<DeployHash, ExecutionResult>,
) where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::PutExecutionResults {
block_hash: Box::new(block_hash),
execution_results,
responder,
},
QueueKind::ToStorage,
)
.await
}
/// Gets the requested deploys from the deploy store.
pub(crate) async fn get_deploy_and_metadata_from_storage(
self,
deploy_hash: DeployHash,
) -> Option<(DeployWithFinalizedApprovals, DeployMetadataExt)>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetDeployAndMetadata {
deploy_hash,
responder,
},
QueueKind::FromStorage,
)
.await
}
/// Gets the requested block and its finality signatures.
pub(crate) async fn get_block_at_height_with_metadata_from_storage(
self,
block_height: u64,
only_from_available_block_range: bool,
) -> Option<BlockWithMetadata>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetBlockAndMetadataByHeight {
block_height,
only_from_available_block_range,
responder,
},
QueueKind::FromStorage,
)
.await
}
/// Gets the requested finality signature from storage.
pub(crate) async fn get_finality_signature_from_storage(
self,
id: Box<FinalitySignatureId>,
) -> Option<FinalitySignature>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetFinalitySignature { id, responder },
QueueKind::FromStorage,
)
.await
}
pub(crate) async fn is_finality_signature_stored(self, id: Box<FinalitySignatureId>) -> bool
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::IsFinalitySignatureStored { id, responder },
QueueKind::FromStorage,
)
.await
}
/// Gets the requested block by hash with its associated metadata.
pub(crate) async fn get_block_with_metadata_from_storage(
self,
block_hash: BlockHash,
only_from_available_block_range: bool,
) -> Option<BlockWithMetadata>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetBlockAndMetadataByHash {
block_hash,
only_from_available_block_range,
responder,
},
QueueKind::FromStorage,
)
.await
}
/// Gets the highest block with its associated metadata.
pub(crate) async fn get_highest_block_with_metadata_from_storage(
self,
only_from_available_block_range: bool,
) -> Option<BlockWithMetadata>
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::GetHighestBlockWithMetadata {
only_from_available_block_range,
responder,
},
QueueKind::FromStorage,
)
.await
}
/// Fetches an item from a fetcher.
pub(crate) async fn fetch<T>(
self,
id: T::Id,
peer: NodeId,
validation_metadata: Box<T::ValidationMetadata>,
) -> FetchResult<T>
where
REv: From<FetcherRequest<T>>,
T: FetchItem + 'static,
{
self.make_request(
|responder| FetcherRequest {
id,
peer,
validation_metadata,
responder,
},
QueueKind::Fetch,
)
.await
}
pub(crate) async fn fetch_trie(
self,
hash: Digest,
peers: Vec<NodeId>,
) -> Result<TrieAccumulatorResponse, TrieAccumulatorError>
where
REv: From<TrieAccumulatorRequest>,
{
self.make_request(
|responder| TrieAccumulatorRequest {
hash,
peers,
responder,
},
QueueKind::SyncGlobalState,
)
.await
}
/// Passes the timestamp of a future block for which deploys are to be proposed.
pub(crate) async fn request_appendable_block(
self,
timestamp: Timestamp,
request_expiry: Timestamp,
) -> AppendableBlock
where
REv: From<DeployBufferRequest>,
{
self.make_request(
|responder| DeployBufferRequest::GetAppendableBlock {
timestamp,
request_expiry,
responder,
},
QueueKind::Consensus,
)
.await
}
/// Enqueues a finalized block execution.
pub(crate) async fn enqueue_block_for_execution(
self,
finalized_block: FinalizedBlock,
deploys: Vec<Deploy>,
meta_block_state: MetaBlockState,
) where
REv: From<StorageRequest> + From<ContractRuntimeRequest>,
{
// Get the key block height for the current protocol version's activation point, i.e. the
// height of the final block of the previous protocol version.
let key_block_height_for_activation_point = self
.make_request(
|responder| StorageRequest::GetKeyBlockHeightForActivationPoint { responder },
QueueKind::FromStorage,
)
.await
.unwrap_or_else(|| {
warn!("key block height for current activation point unknown");
0
});
self.event_queue
.schedule(
ContractRuntimeRequest::EnqueueBlockForExecution {
finalized_block,
deploys,
key_block_height_for_activation_point,
meta_block_state,
},
QueueKind::ContractRuntime,
)
.await
}
/// Checks whether the deploys included in the block exist on the network and the block is
/// valid.
pub(crate) async fn validate_block(
self,
sender: NodeId,
block: ProposedBlock<ClContext>,
) -> bool
where
REv: From<BlockValidationRequest>,
{
self.make_request(
|responder| BlockValidationRequest {
block,
sender,
responder,
},
QueueKind::Regular,
)
.await
}
/// Announces that a block has been proposed.
pub(crate) async fn announce_proposed_block(self, proposed_block: ProposedBlock<ClContext>)
where
REv: From<ConsensusAnnouncement>,
{
self.event_queue
.schedule(
ConsensusAnnouncement::Proposed(Box::new(proposed_block)),
QueueKind::Consensus,
)
.await
}
/// Announces that a block has been finalized.
pub(crate) async fn announce_finalized_block(self, finalized_block: FinalizedBlock)
where
REv: From<ConsensusAnnouncement>,
{
self.event_queue
.schedule(
ConsensusAnnouncement::Finalized(Box::new(finalized_block)),
QueueKind::Consensus,
)
.await
}
/// Announces that a meta block has been created or its state has changed.
pub(crate) async fn announce_meta_block(self, meta_block: MetaBlock)
where
REv: From<MetaBlockAnnouncement>,
{
self.event_queue
.schedule(MetaBlockAnnouncement(meta_block), QueueKind::Regular)
.await
}
/// Announces that a finalized block has been created, but it was not
/// executed.
pub(crate) async fn announce_unexecuted_block(self, block_height: u64)
where
REv: From<UnexecutedBlockAnnouncement>,
{
self.event_queue
.schedule(
UnexecutedBlockAnnouncement(block_height),
QueueKind::Regular,
)
.await
}
/// An equivocation has been detected.
pub(crate) async fn announce_fault_event(
self,
era_id: EraId,
public_key: PublicKey,
timestamp: Timestamp,
) where
REv: From<ConsensusAnnouncement>,
{
self.event_queue
.schedule(
ConsensusAnnouncement::Fault {
era_id,
public_key: Box::new(public_key),
timestamp,
},
QueueKind::Consensus,
)
.await
}
/// Blocks a specific peer due to a transgression.
///
/// This function will also emit a log message for the block.
pub(crate) async fn announce_block_peer_with_justification(
self,
offender: NodeId,
justification: BlocklistJustification,
) where
REv: From<PeerBehaviorAnnouncement>,
{
warn!(%offender, %justification, "banning peer");
self.event_queue
.schedule(
PeerBehaviorAnnouncement::OffenseCommitted {
offender: Box::new(offender),
justification: Box::new(justification),
},
QueueKind::NetworkInfo,
)
.await
}
/// Gets the next scheduled upgrade, if any.
pub(crate) async fn get_next_upgrade(self) -> Option<NextUpgrade>
where
REv: From<UpgradeWatcherRequest> + Send,
{
self.make_request(UpgradeWatcherRequest, QueueKind::Control)
.await
}
/// Requests a query be executed on the Contract Runtime component.
pub(crate) async fn query_global_state(
self,
query_request: QueryRequest,
) -> Result<QueryResult, engine_state::Error>
where
REv: From<ContractRuntimeRequest>,
{
self.make_request(
|responder| ContractRuntimeRequest::Query {
query_request,
responder,
},
QueueKind::ContractRuntime,
)
.await
}
/// Retrieves an `Account` from global state if present.
pub(crate) async fn get_account_from_global_state(
self,
state_root_hash: Digest,
account_key: Key,
) -> Option<Account>
where
REv: From<ContractRuntimeRequest>,
{
let query_request = QueryRequest::new(state_root_hash, account_key, vec![]);
match self.query_global_state(query_request).await {
Ok(QueryResult::Success { value, .. }) => value.as_account().cloned(),
Ok(_) | Err(_) => None,
}
}
/// Retrieves the balance of a purse, returns `None` if no purse is present.
pub(crate) async fn check_purse_balance(
self,
state_root_hash: Digest,
main_purse: URef,
) -> Option<U512>
where
REv: From<ContractRuntimeRequest>,
{
let balance_request = BalanceRequest::new(state_root_hash, main_purse);
match self.get_balance(balance_request).await {
Ok(balance_result) => {
if let Some(motes) = balance_result.motes() {
return Some(*motes);
}
None
}
Err(_) => None,
}
}
/// Retrieves an `Contract` from global state if present.
pub(crate) async fn get_contract_for_validation(
self,
state_root_hash: Digest,
query_key: Key,
path: Vec<String>,
) -> Option<Box<Contract>>
where
REv: From<ContractRuntimeRequest>,
{
let query_request = QueryRequest::new(state_root_hash, query_key, path);
match self.query_global_state(query_request).await {
Ok(QueryResult::Success { value, .. }) => {
// TODO: Extending `StoredValue` with an `into_contract` would reduce cloning here.
value.as_contract().map(|c| Box::new(c.clone()))
}
Ok(_) | Err(_) => None,
}
}
/// Retrieves an `ContractPackage` from global state if present.
pub(crate) async fn get_contract_package_for_validation(
self,
state_root_hash: Digest,
query_key: Key,
path: Vec<String>,
) -> Option<Box<ContractPackage>>
where
REv: From<ContractRuntimeRequest>,
{
let query_request = QueryRequest::new(state_root_hash, query_key, path);
match self.query_global_state(query_request).await {
Ok(QueryResult::Success { value, .. }) => {
value.as_contract_package().map(|pkg| Box::new(pkg.clone()))
}
Ok(_) | Err(_) => None,
}
}
/// Requests a query be executed on the Contract Runtime component.
pub(crate) async fn get_balance(
self,
balance_request: BalanceRequest,
) -> Result<BalanceResult, engine_state::Error>
where
REv: From<ContractRuntimeRequest>,
{
self.make_request(
|responder| ContractRuntimeRequest::GetBalance {
balance_request,
responder,
},
QueueKind::ContractRuntime,
)
.await
}
/// Returns a map of validators weights for all eras as known from `root_hash`.
///
/// This operation is read only.
pub(crate) async fn get_era_validators_from_contract_runtime(
self,
request: EraValidatorsRequest,
) -> Result<EraValidators, GetEraValidatorsError>
where
REv: From<ContractRuntimeRequest>,
{
self.make_request(
|responder| ContractRuntimeRequest::GetEraValidators { request, responder },
QueueKind::ContractRuntime,
)
.await
}
/// Requests a query be executed on the Contract Runtime component.
pub(crate) async fn get_bids(
self,
get_bids_request: GetBidsRequest,
) -> Result<GetBidsResult, engine_state::Error>
where
REv: From<ContractRuntimeRequest>,
{
self.make_request(
|responder| ContractRuntimeRequest::GetBids {
get_bids_request,
responder,
},
QueueKind::ContractRuntime,
)
.await
}
/// Returns the value of the execution results checksum stored in the ChecksumRegistry for the
/// given state root hash.
pub(crate) async fn get_execution_results_checksum(
self,
state_root_hash: Digest,
) -> Result<Option<Digest>, engine_state::Error>
where
REv: From<ContractRuntimeRequest>,
{
self.make_request(
|responder| ContractRuntimeRequest::GetExecutionResultsChecksum {
state_root_hash,
responder,
},
QueueKind::ContractRuntime,
)
.await
}
/// Get our public key from consensus, and if we're a validator, the next round length.
pub(crate) async fn consensus_status(self) -> Option<(PublicKey, Option<TimeDiff>)>
where
REv: From<ConsensusRequest>,
{
self.make_request(ConsensusRequest::Status, QueueKind::Consensus)
.await
}
/// Returns a list of validator status changes, by public key.
pub(crate) async fn get_consensus_validator_changes(
self,
) -> BTreeMap<PublicKey, Vec<(EraId, ValidatorChange)>>
where
REv: From<ConsensusRequest>,
{
self.make_request(ConsensusRequest::ValidatorChanges, QueueKind::Consensus)
.await
}
/// Dump consensus state for a specific era, using the supplied function to serialize the
/// output.
pub(crate) async fn diagnostics_port_dump_consensus_state(
self,
era_id: Option<EraId>,
serialize: fn(&EraDump<'_>) -> Result<Vec<u8>, Cow<'static, str>>,
) -> Result<Vec<u8>, Cow<'static, str>>
where
REv: From<DumpConsensusStateRequest>,
{
self.make_request(
|responder| DumpConsensusStateRequest {
era_id,
serialize,
responder,
},
QueueKind::Control,
)
.await
}
/// Dump the event queue contents to the diagnostics port, using the given serializer.
pub(crate) async fn diagnostics_port_dump_queue(self, dump_format: QueueDumpFormat)
where
REv: From<ControlAnnouncement>,
{
self.make_request(
|responder| ControlAnnouncement::QueueDumpRequest {
dump_format,
finished: responder,
},
QueueKind::Control,
)
.await
}
/// Activates/deactivates a failpoint from a given activation.
pub(crate) async fn activate_failpoint(self, activation: FailpointActivation)
where
REv: From<ControlAnnouncement>,
{
self.event_queue
.schedule(
ControlAnnouncement::ActivateFailpoint { activation },
QueueKind::Control,
)
.await;
}
/// Announce that the node be shut down due to a request from a user.
pub(crate) async fn announce_user_shutdown_request(self)
where
REv: From<ControlAnnouncement>,
{
self.event_queue
.schedule(
ControlAnnouncement::ShutdownDueToUserRequest,
QueueKind::Control,
)
.await;
}
/// Announce that a block which wasn't previously stored on this node has been fetched and
/// stored.
pub(crate) async fn announce_fetched_new_block(self, block: Arc<Block>, peer: NodeId)
where
REv: From<FetchedNewBlockAnnouncement>,
{
self.event_queue
.schedule(
FetchedNewBlockAnnouncement { block, peer },
QueueKind::Fetch,
)
.await;
}
/// Announce that a finality signature which wasn't previously stored on this node has been
/// fetched and stored.
pub(crate) async fn announce_fetched_new_finality_signature(
self,
finality_signature: Box<FinalitySignature>,
peer: NodeId,
) where
REv: From<FetchedNewFinalitySignatureAnnouncement>,
{
self.event_queue
.schedule(
FetchedNewFinalitySignatureAnnouncement {
finality_signature,
peer,
},
QueueKind::Fetch,
)
.await;
}
/// Get the bytes for the chainspec file and genesis_accounts
/// and global_state bytes if the files are present.
pub(crate) async fn get_chainspec_raw_bytes(self) -> Arc<ChainspecRawBytes>
where
REv: From<ChainspecRawBytesRequest> + Send,
{
self.make_request(
ChainspecRawBytesRequest::GetChainspecRawBytes,
QueueKind::NetworkInfo,
)
.await
}
/// Stores a set of given finalized approvals in storage.
///
/// Any previously stored finalized approvals for the given hash are quietly overwritten
pub(crate) async fn store_finalized_approvals(
self,
deploy_hash: DeployHash,
finalized_approvals: FinalizedApprovals,
) -> bool
where
REv: From<StorageRequest>,
{
self.make_request(
|responder| StorageRequest::StoreFinalizedApprovals {
deploy_hash,
finalized_approvals,
responder,
},
QueueKind::ToStorage,
)
.await
}
/// Requests execution of a single deploy, without commiting its effects.
/// Inteded to be used for debugging & discovery purposes.
pub(crate) async fn speculative_execute_deploy(
self,
execution_prestate: SpeculativeExecutionState,
deploy: Arc<Deploy>,
) -> Result<Option<ExecutionResult>, engine_state::Error>
where
REv: From<ContractRuntimeRequest>,
{
self.make_request(
|responder| ContractRuntimeRequest::SpeculativeDeployExecution {
execution_prestate,
deploy,
responder,
},
QueueKind::ContractRuntime,
)
.await
}
/// Reads block execution results (or chunk) from Storage component.
pub(crate) async fn get_block_execution_results_or_chunk_from_storage(
self,
id: BlockExecutionResultsOrChunkId,
) -> Option<BlockExecutionResultsOrChunk>
where
REv: From<StorageRequest>, // TODO: Extract to a separate component for caching.
{
self.make_request(
|responder| StorageRequest::GetBlockExecutionResultsOrChunk { id, responder },
QueueKind::FromStorage,
)
.await
}
/// Gets peers for a given block from the block accumulator.
pub(crate) async fn get_block_accumulated_peers(
self,
block_hash: BlockHash,
) -> Option<Vec<NodeId>>
where
REv: From<BlockAccumulatorRequest>,
{
self.make_request(
|responder| BlockAccumulatorRequest::GetPeersForBlock {
block_hash,
responder,
},
QueueKind::NetworkInfo,
)
.await
}
/// Set a new stopping point for the node.
///
/// Returns a potentially previously set stop-at spec.
pub(crate) async fn set_node_stop_at(self, stop_at: Option<StopAtSpec>) -> Option<StopAtSpec>
where
REv: From<SetNodeStopRequest>,
{
self.make_request(
|responder| SetNodeStopRequest { stop_at, responder },
QueueKind::Control,
)
.await
}
}
/// Construct a fatal error effect.
///
/// This macro is a convenient wrapper around `EffectBuilder::fatal` that inserts the `file!()` and
/// `line!()` number automatically.
#[macro_export]
macro_rules! fatal {
($effect_builder:expr, $($arg:tt)*) => {
$effect_builder.fatal(file!(), line!(), format!($($arg)*))
};
}