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
//! Lightwallet service RPC implementations.
use futures::StreamExt;
use hex::FromHex;
use tokio::time::timeout;
use tokio_stream::wrappers::ReceiverStream;
use crate::{rpc::GrpcClient, utils::get_build_info};
use zaino_fetch::{
chain::{
block::{get_block_from_node, get_nullifiers_from_node},
mempool::Mempool,
transaction::FullTransaction,
utils::ParseFromSlice,
},
jsonrpc::{connector::JsonRpcConnector, response::{GetBlockResponse, GetTransactionResponse}},
};
use zaino_proto::proto::{
compact_formats::{CompactBlock, CompactTx},
service::{
compact_tx_streamer_server::CompactTxStreamer, Address, AddressList, Balance, BlockId,
BlockRange, ChainSpec, Duration, Empty, Exclude, GetAddressUtxosArg, GetAddressUtxosReply,
GetAddressUtxosReplyList, GetSubtreeRootsArg, LightdInfo, PingResponse, RawTransaction,
SendResponse, ShieldedProtocol, SubtreeRoot, TransparentAddressBlockFilter, TreeState,
TxFilter
},
};
/// T Address Regex
static TADDR_REGEX: lazy_regex::Lazy<lazy_regex::regex::Regex> =
lazy_regex::lazy_regex!(r"^t[a-zA-Z0-9]{34}$");
/// Checks for valid t Address.
///
/// Returns Some(taddress) if address is valid else none.
fn check_taddress(taddr: &str) -> Option<&str> {
if TADDR_REGEX.is_match(taddr) {
Some(taddr)
} else {
None
}
}
/// Stream of RawTransactions, output type of get_taddress_txids.
pub struct RawTransactionStream {
inner: ReceiverStream<Result<RawTransaction, tonic::Status>>,
}
impl RawTransactionStream {
/// Returns new instanse of RawTransactionStream.
pub fn new(rx: tokio::sync::mpsc::Receiver<Result<RawTransaction, tonic::Status>>) -> Self {
RawTransactionStream {
inner: ReceiverStream::new(rx),
}
}
}
impl futures::Stream for RawTransactionStream {
type Item = Result<RawTransaction, tonic::Status>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
let poll = std::pin::Pin::new(&mut self.inner).poll_next(cx);
match poll {
std::task::Poll::Ready(Some(Ok(raw_tx))) => std::task::Poll::Ready(Some(Ok(raw_tx))),
std::task::Poll::Ready(Some(Err(e))) => std::task::Poll::Ready(Some(Err(e))),
std::task::Poll::Ready(None) => std::task::Poll::Ready(None),
std::task::Poll::Pending => std::task::Poll::Pending,
}
}
}
/// Stream of RawTransactions, output type of get_taddress_txids.
pub struct CompactTransactionStream {
inner: ReceiverStream<Result<CompactTx, tonic::Status>>,
}
impl CompactTransactionStream {
/// Returns new instanse of RawTransactionStream.
pub fn new(rx: tokio::sync::mpsc::Receiver<Result<CompactTx, tonic::Status>>) -> Self {
CompactTransactionStream {
inner: ReceiverStream::new(rx),
}
}
}
impl futures::Stream for CompactTransactionStream {
type Item = Result<CompactTx, tonic::Status>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
let poll = std::pin::Pin::new(&mut self.inner).poll_next(cx);
match poll {
std::task::Poll::Ready(Some(Ok(raw_tx))) => std::task::Poll::Ready(Some(Ok(raw_tx))),
std::task::Poll::Ready(Some(Err(e))) => std::task::Poll::Ready(Some(Err(e))),
std::task::Poll::Ready(None) => std::task::Poll::Ready(None),
std::task::Poll::Pending => std::task::Poll::Pending,
}
}
}
/// Stream of CompactBlocks, output type of get_block_range.
pub struct CompactBlockStream {
inner: ReceiverStream<Result<CompactBlock, tonic::Status>>,
}
impl CompactBlockStream {
/// Returns new instanse of CompactBlockStream.
pub fn new(rx: tokio::sync::mpsc::Receiver<Result<CompactBlock, tonic::Status>>) -> Self {
CompactBlockStream {
inner: ReceiverStream::new(rx),
}
}
}
impl futures::Stream for CompactBlockStream {
type Item = Result<CompactBlock, tonic::Status>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
let poll = std::pin::Pin::new(&mut self.inner).poll_next(cx);
match poll {
std::task::Poll::Ready(Some(Ok(raw_tx))) => std::task::Poll::Ready(Some(Ok(raw_tx))),
std::task::Poll::Ready(Some(Err(e))) => std::task::Poll::Ready(Some(Err(e))),
std::task::Poll::Ready(None) => std::task::Poll::Ready(None),
std::task::Poll::Pending => std::task::Poll::Pending,
}
}
}
/// Stream of CompactBlocks, output type of get_block_range.
pub struct UtxoReplyStream {
inner: ReceiverStream<Result<GetAddressUtxosReply, tonic::Status>>,
}
impl UtxoReplyStream {
/// Returns new instanse of CompactBlockStream.
pub fn new(
rx: tokio::sync::mpsc::Receiver<Result<GetAddressUtxosReply, tonic::Status>>,
) -> Self {
UtxoReplyStream {
inner: ReceiverStream::new(rx),
}
}
}
impl futures::Stream for UtxoReplyStream {
type Item = Result<GetAddressUtxosReply, tonic::Status>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
let poll = std::pin::Pin::new(&mut self.inner).poll_next(cx);
match poll {
std::task::Poll::Ready(Some(Ok(raw_tx))) => std::task::Poll::Ready(Some(Ok(raw_tx))),
std::task::Poll::Ready(Some(Err(e))) => std::task::Poll::Ready(Some(Err(e))),
std::task::Poll::Ready(None) => std::task::Poll::Ready(None),
std::task::Poll::Pending => std::task::Poll::Pending,
}
}
}
/// Stream of CompactBlocks, output type of get_block_range.
pub struct SubtreeRootReplyStream {
inner: ReceiverStream<Result<SubtreeRoot, tonic::Status>>,
}
impl SubtreeRootReplyStream {
/// Returns new instanse of CompactBlockStream.
pub fn new(
rx: tokio::sync::mpsc::Receiver<Result<SubtreeRoot, tonic::Status>>,
) -> Self {
SubtreeRootReplyStream {
inner: ReceiverStream::new(rx),
}
}
}
impl futures::Stream for SubtreeRootReplyStream {
type Item = Result<SubtreeRoot, tonic::Status>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
let poll = std::pin::Pin::new(&mut self.inner).poll_next(cx);
match poll {
std::task::Poll::Ready(Some(Ok(raw_tx))) => std::task::Poll::Ready(Some(Ok(raw_tx))),
std::task::Poll::Ready(Some(Err(e))) => std::task::Poll::Ready(Some(Err(e))),
std::task::Poll::Ready(None) => std::task::Poll::Ready(None),
std::task::Poll::Pending => std::task::Poll::Pending,
}
}
}
impl CompactTxStreamer for GrpcClient {
/// Return the height of the tip of the best chain.
fn get_latest_block<'life0, 'async_trait>(
&'life0 self,
_request: tonic::Request<ChainSpec>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<tonic::Response<BlockId>, tonic::Status>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of get_latest_block.");
Box::pin(async {
let blockchain_info = JsonRpcConnector::new(
self.zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?
.get_blockchain_info()
.await
.map_err(|e| e.to_grpc_status())?;
let block_id = BlockId {
height: blockchain_info.blocks.0 as u64,
hash: blockchain_info
.best_block_hash
.bytes_in_display_order()
.to_vec(),
};
Ok(tonic::Response::new(block_id))
})
}
/// Return the compact block corresponding to the given block identifier.
///
/// TODO: This implementation is slow. An internal block cache should be implemented that this rpc, along with the get_block rpc, can rely on.
/// - add get_block function that queries the block cache / internal state for block and calls get_block_from_node to fetch block if not present.
/// - use chain height held in internal state to validate block height being requested.
fn get_block<'life0, 'async_trait>(
&'life0 self,
request: tonic::Request<BlockId>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<tonic::Response<CompactBlock>, tonic::Status>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of get_block.");
Box::pin(async {
let zebrad_uri = self.zebrad_uri.clone();
let height: u32 = match request.into_inner().height.try_into() {
Ok(height) => height,
Err(_) => {
return Err(tonic::Status::invalid_argument(
"Error: Height out of range. Failed to convert to u32.",
));
}
};
match get_block_from_node(&zebrad_uri, &height).await {
Ok(block) => Ok(tonic::Response::new(block)),
Err(e) => {
let chain_height = JsonRpcConnector::new(
self.zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?
.get_blockchain_info()
.await
.map_err(|e| e.to_grpc_status())?
.blocks
.0;
if height >= chain_height {
return Err(tonic::Status::out_of_range(
format!(
"Error: Height out of range [{}]. Height requested is greater than the best chain tip [{}].",
height, chain_height,
)
));
} else {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
return Err(tonic::Status::unknown(format!(
"Error: Failed to retrieve block from node. Server Error: {}",
e.to_string(),
)));
};
}
}
})
}
/// Same as GetBlock except actions contain only nullifiers.
///
/// NOTE: This should be reimplemented with the introduction of the BlockCache.
/// - use chain height held in internal state to validate block height being requested.
fn get_block_nullifiers<'life0, 'async_trait>(
&'life0 self,
request: tonic::Request<BlockId>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<tonic::Response<CompactBlock>, tonic::Status>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of get_block_nullifiers.");
Box::pin(async {
let zebrad_uri = self.zebrad_uri.clone();
let height: u32 = match request.into_inner().height.try_into() {
Ok(height) => height,
Err(_) => {
return Err(tonic::Status::invalid_argument(
"Error: Height out of range. Failed to convert to u32.",
));
}
};
match get_nullifiers_from_node(&zebrad_uri, &height).await {
Ok(block) => Ok(tonic::Response::new(block)),
Err(e) => {
let chain_height = JsonRpcConnector::new(
self.zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?
.get_blockchain_info()
.await
.map_err(|e| e.to_grpc_status())?
.blocks
.0;
if height >= chain_height {
return Err(tonic::Status::out_of_range(
format!(
"Error: Height out of range [{}]. Height requested is greater than the best chain tip [{}].",
height, chain_height,
)
));
} else {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
return Err(tonic::Status::unknown(format!(
"Error: Failed to retrieve nullifiers from node. Server Error: {}",
e.to_string(),
)));
};
}
}
})
}
/// Server streaming response type for the GetBlockRange method.
#[doc = "Server streaming response type for the GetBlockRange method."]
type GetBlockRangeStream = std::pin::Pin<Box<CompactBlockStream>>;
/// Return a list of consecutive compact blocks.
///
/// TODO: This implementation is slow. An internal block cache should be implemented that this rpc, along with the get_block rpc, can rely on.
/// - add get_block function that queries the block cache for block and calls get_block_from_node to fetch block if not present.
/// - use chain height held in internal state to validate block height being requested.
fn get_block_range<'life0, 'async_trait>(
&'life0 self,
request: tonic::Request<BlockRange>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<
tonic::Response<Self::GetBlockRangeStream>,
tonic::Status,
>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of get_block_range.");
let zebrad_uri = self.zebrad_uri.clone();
Box::pin(async move {
let blockrange = request.into_inner();
let mut start: u32 = match blockrange.start {
Some(block_id) => match block_id.height.try_into() {
Ok(height) => height,
Err(_) => {
return Err(tonic::Status::invalid_argument(
"Error: Start height out of range. Failed to convert to u32.",
));
}
},
None => {
return Err(tonic::Status::invalid_argument(
"Error: No start height given.",
));
}
};
let mut end: u32 = match blockrange.end {
Some(block_id) => match block_id.height.try_into() {
Ok(height) => height,
Err(_) => {
return Err(tonic::Status::invalid_argument(
"Error: End height out of range. Failed to convert to u32.",
));
}
},
None => {
return Err(tonic::Status::invalid_argument(
"Error: No start height given.",
));
}
};
let rev_order = if start > end {
(start, end) = (end, start);
true
} else {
false
};
let chain_height = JsonRpcConnector::new(
self.zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?
.get_blockchain_info()
.await
.map_err(|e| e.to_grpc_status())?
.blocks
.0;
println!("[TEST] Fetching blocks in range: {}-{}.", start, end);
let (channel_tx, channel_rx) = tokio::sync::mpsc::channel(32);
tokio::spawn(async move {
// NOTE: This timeout is so slow due to the blockcache not being implemented. This should be reduced to 30s once functionality is in place.
// TODO: Make [rpc_timout] a configurable system variable with [default = 30s] and [mempool_rpc_timout = 4*rpc_timeout]
let timeout = timeout(std::time::Duration::from_secs(120), async {
for height in start..=end {
let height = if rev_order {
end - (height - start)
} else {
height
};
println!("[TEST] Fetching block at height: {}.", height);
match get_block_from_node(&zebrad_uri, &height).await {
Ok(block) => {
if channel_tx.send(Ok(block)).await.is_err() {
break;
}
}
Err(e) => {
if height >= chain_height {
match channel_tx
.send(Err(tonic::Status::out_of_range(format!(
"Error: Height out of range [{}]. Height requested is greater than the best chain tip [{}].",
height, chain_height,
))))
.await
{
Ok(_) => break,
Err(e) => {
eprintln!("Error: Channel closed unexpectedly: {}", e.to_string());
break;
}
}
} else {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
if channel_tx
.send(Err(tonic::Status::unknown(e.to_string())))
.await
.is_err()
{
break;
}
}
}
}
}
})
.await;
match timeout {
Ok(_) => {}
Err(_) => {
channel_tx
.send(Err(tonic::Status::deadline_exceeded(
"Error: get_block_range gRPC request timed out.",
)))
.await
.ok();
}
}
});
let output_stream = CompactBlockStream::new(channel_rx);
let stream_boxed = Box::pin(output_stream);
Ok(tonic::Response::new(stream_boxed))
})
}
/// Server streaming response type for the GetBlockRangeNullifiers method.
#[doc = " Server streaming response type for the GetBlockRangeNullifiers method."]
type GetBlockRangeNullifiersStream = std::pin::Pin<Box<CompactBlockStream>>;
/// Same as GetBlockRange except actions contain only nullifiers.
///
/// NOTE: This should be reimplemented with the introduction of the BlockCache.
/// - use chain height held in internal state to validate block height being requested.
fn get_block_range_nullifiers<'life0, 'async_trait>(
&'life0 self,
request: tonic::Request<BlockRange>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<
tonic::Response<Self::GetBlockRangeNullifiersStream>,
tonic::Status,
>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of get_block_range_nullifiers.");
let zebrad_uri = self.zebrad_uri.clone();
Box::pin(async move {
let blockrange = request.into_inner();
let mut start: u32 = match blockrange.start {
Some(block_id) => match block_id.height.try_into() {
Ok(height) => height,
Err(_) => {
return Err(tonic::Status::invalid_argument(
"Error: Start height out of range. Failed to convert to u32.",
));
}
},
None => {
return Err(tonic::Status::invalid_argument(
"Error: No start height given.",
));
}
};
let mut end: u32 = match blockrange.end {
Some(block_id) => match block_id.height.try_into() {
Ok(height) => height,
Err(_) => {
return Err(tonic::Status::invalid_argument(
"Error: End height out of range. Failed to convert to u32.",
));
}
},
None => {
return Err(tonic::Status::invalid_argument(
"Error: No end height given.",
));
}
};
let rev_order = if start > end {
(start, end) = (end, start);
true
} else {
false
};
let chain_height = JsonRpcConnector::new(
self.zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?
.get_blockchain_info()
.await
.map_err(|e| e.to_grpc_status())?
.blocks
.0;
let (channel_tx, channel_rx) = tokio::sync::mpsc::channel(32);
tokio::spawn(async move {
// NOTE: This timeout is so slow due to the blockcache not being implemented. This should be reduced to 30s once functionality is in place.
// TODO: Make [rpc_timout] a configurable system variable with [default = 30s] and [mempool_rpc_timout = 4*rpc_timeout]
let timeout = timeout(std::time::Duration::from_secs(120), async {
for height in start..=end {
let height = if rev_order {
end - (height - start)
} else {
height
};
let compact_block = get_nullifiers_from_node(&zebrad_uri, &height).await;
match compact_block {
Ok(block) => {
if channel_tx.send(Ok(block)).await.is_err() {
break;
}
}
Err(e) => {
if height >= chain_height {
match channel_tx
.send(Err(tonic::Status::out_of_range(format!(
"Error: Height out of range [{}]. Height requested is greater than the best chain tip [{}].",
height, chain_height,
))))
.await
{
Ok(_) => break,
Err(e) => {
eprintln!("Error: Channel closed unexpectedly: {}", e.to_string());
break;
}
}
} else {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
if channel_tx
.send(Err(tonic::Status::unknown(e.to_string())))
.await
.is_err()
{
break;
}
}
}
}
}
})
.await;
match timeout {
Ok(_) => {}
Err(_) => {
channel_tx
.send(Err(tonic::Status::deadline_exceeded(
"Error: get_block_range_nullifiers gRPC request timed out.",
)))
.await
.ok();
}
}
});
let output_stream = CompactBlockStream::new(channel_rx);
let stream_boxed = Box::pin(output_stream);
Ok(tonic::Response::new(stream_boxed))
})
}
/// Return the requested full (not compact) transaction (as from zcashd).
fn get_transaction<'life0, 'async_trait>(
&'life0 self,
request: tonic::Request<TxFilter>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<tonic::Response<RawTransaction>, tonic::Status>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of get_transaction.");
Box::pin(async {
let hash = request.into_inner().hash;
if hash.len() == 32 {
let reversed_hash = hash.iter().rev().copied().collect::<Vec<u8>>();
let hash_hex = hex::encode(reversed_hash);
let tx = JsonRpcConnector::new(
self.zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?
.get_raw_transaction(hash_hex, Some(1))
.await
.map_err(|e| e.to_grpc_status())?;
let (hex, height) = if let GetTransactionResponse::Object { hex, height, .. } = tx {
(hex, height)
} else {
return Err(tonic::Status::not_found("Error: Transaction not received"));
};
let height: u64 = height.try_into().map_err(|_e| {
tonic::Status::unknown(
"Error: Invalid response from server - Height conversion failed",
)
})?;
Ok(tonic::Response::new(RawTransaction {
data: hex.as_ref().to_vec(),
height,
}))
} else {
Err(tonic::Status::invalid_argument(
"Error: Transaction hash incorrect",
))
}
})
}
/// Submit the given transaction to the Zcash network.
fn send_transaction<'life0, 'async_trait>(
&'life0 self,
request: tonic::Request<RawTransaction>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<tonic::Response<SendResponse>, tonic::Status>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of send_transaction.");
Box::pin(async {
let hex_tx = hex::encode(request.into_inner().data);
let tx_output = JsonRpcConnector::new(
self.zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?
.send_raw_transaction(hex_tx)
.await
.map_err(|e| e.to_grpc_status())?;
Ok(tonic::Response::new(SendResponse {
error_code: 0,
error_message: tx_output.0.to_string(),
}))
})
}
/// Server streaming response type for the GetTaddressTxids method.
#[doc = "Server streaming response type for the GetTaddressTxids method."]
type GetTaddressTxidsStream = std::pin::Pin<Box<RawTransactionStream>>;
/// This name is misleading, returns the full transactions that have either inputs or outputs connected to the given transparent address.
fn get_taddress_txids<'life0, 'async_trait>(
&'life0 self,
request: tonic::Request<TransparentAddressBlockFilter>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<
tonic::Response<Self::GetTaddressTxidsStream>,
tonic::Status,
>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of get_taddress_txids.");
Box::pin(async move {
let zebrad_client = JsonRpcConnector::new(
self.zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?;
let chain_height = zebrad_client.get_blockchain_info().await?.blocks.0;
let block_filter = request.into_inner();
let (start, end) =
match block_filter.range {
Some(range) => match (range.start, range.end) {
(Some(start), Some(end)) => {
let start = match u32::try_from(start.height) {
Ok(height) => height.min(chain_height),
Err(_) => return Err(tonic::Status::invalid_argument(
"Error: Start height out of range. Failed to convert to u32.",
)),
};
let end =
match u32::try_from(end.height) {
Ok(height) => height.min(chain_height),
Err(_) => return Err(tonic::Status::invalid_argument(
"Error: End height out of range. Failed to convert to u32.",
)),
};
if start > end {
(end, start)
} else {
(start, end)
}
}
_ => {
return Err(tonic::Status::invalid_argument(
"Error: Incomplete block range given.",
))
}
},
None => {
return Err(tonic::Status::invalid_argument(
"Error: No block range given.",
))
}
};
let txids = zebrad_client
.get_address_txids(vec![block_filter.address], start, end)
.await
.map_err(|e| e.to_grpc_status())?;
let (channel_tx, channel_rx) = tokio::sync::mpsc::channel(32);
tokio::spawn(async move {
// NOTE: This timeout is so slow due to the blockcache not being implemented. This should be reduced to 30s once functionality is in place.
// TODO: Make [rpc_timout] a configurable system variable with [default = 30s] and [mempool_rpc_timout = 4*rpc_timeout]
let timeout = timeout(std::time::Duration::from_secs(120), async {
for txid in txids.transactions {
let transaction = zebrad_client.get_raw_transaction(txid, Some(1)).await;
match transaction {
Ok(GetTransactionResponse::Object { hex, height, .. }) => {
if channel_tx
.send(Ok(RawTransaction {
data: hex.as_ref().to_vec(),
height: height as u64,
}))
.await
.is_err()
{
break;
}
}
Ok(GetTransactionResponse::Raw(_)) => {
if channel_tx
.send(Err(tonic::Status::unknown(
"Received raw transaction type, this should not be impossible.",
)))
.await
.is_err()
{
break;
}
}
Err(e) => {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
if channel_tx
.send(Err(tonic::Status::unknown(e.to_string())))
.await
.is_err()
{
break;
}
}
}
}
})
.await;
match timeout {
Ok(_) => {}
Err(_) => {
channel_tx
.send(Err(tonic::Status::internal(
"Error: get_taddress_txids gRPC request timed out",
)))
.await
.ok();
}
}
});
let output_stream = RawTransactionStream::new(channel_rx);
let stream_boxed = Box::pin(output_stream);
Ok(tonic::Response::new(stream_boxed))
})
}
/// Returns the total balance for a list of taddrs
fn get_taddress_balance<'life0, 'async_trait>(
&'life0 self,
request: tonic::Request<AddressList>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<tonic::Response<Balance>, tonic::Status>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of get_taddress_balance.");
Box::pin(async {
let zebrad_client = JsonRpcConnector::new(
self.zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?;
let taddrs = request.into_inner().addresses;
if !taddrs.iter().all(|taddr| check_taddress(taddr).is_some()) {
return Err(tonic::Status::invalid_argument(
"Error: One or more invalid taddresses given.",
));
}
let balance = zebrad_client.get_address_balance(taddrs).await?;
let checked_balance: i64 = match i64::try_from(balance.balance) {
Ok(balance) => balance,
Err(_) => {
return Err(tonic::Status::unknown(
"Error: Error converting balance from u64 to i64.",
));
}
};
Ok(tonic::Response::new(Balance {
value_zat: checked_balance,
}))
})
}
/// Returns the total balance for a list of taddrs
#[must_use]
#[allow(clippy::type_complexity, clippy::type_repetition_in_bounds)]
fn get_taddress_balance_stream<'life0, 'async_trait>(
&'life0 self,
request: tonic::Request<tonic::Streaming<Address>>,
) -> ::core::pin::Pin<
Box<
dyn ::core::future::Future<Output = Result<tonic::Response<Balance>, tonic::Status>>
+ ::core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of get_taddress_balance_stream.");
Box::pin(async {
let zebrad_client = JsonRpcConnector::new(
self.zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?;
let (channel_tx, mut channel_rx) = tokio::sync::mpsc::channel::<String>(32);
let fetcher_task_handle = tokio::spawn(async move {
// NOTE: This timeout is so slow due to the blockcache not being implemented. This should be reduced to 30s once functionality is in place.
// TODO: Make [rpc_timout] a configurable system variable with [default = 30s] and [mempool_rpc_timout = 4*rpc_timeout]
let fetcher_timeout = timeout(std::time::Duration::from_secs(120), async {
let mut total_balance: u64 = 0;
loop {
match channel_rx.recv().await {
Some(taddr) => {
if check_taddress(taddr.as_str()).is_some() {
let balance =
zebrad_client.get_address_balance(vec![taddr]).await?;
total_balance += balance.balance;
} else {
return Err(tonic::Status::invalid_argument(
"Error: One or more invalid taddresses given.",
));
}
}
None => {
return Ok(total_balance);
}
}
}
})
.await;
match fetcher_timeout {
Ok(result) => result,
Err(_) => Err(tonic::Status::deadline_exceeded(
"Error: get_taddress_balance_stream request timed out.",
)),
}
});
// NOTE: This timeout is so slow due to the blockcache not being implemented. This should be reduced to 30s once functionality is in place.
// TODO: Make [rpc_timout] a configurable system variable with [default = 30s] and [mempool_rpc_timout = 4*rpc_timeout]
let addr_recv_timeout = timeout(std::time::Duration::from_secs(120), async {
let mut address_stream = request.into_inner();
while let Some(address_result) = address_stream.next().await {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
let address = address_result.map_err(|e| {
tonic::Status::unknown(format!("Failed to read from stream: {}", e))
})?;
if channel_tx.send(address.address).await.is_err() {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
return Err(tonic::Status::unknown(
"Error: Failed to send address to balance task.",
));
}
}
drop(channel_tx);
Ok::<(), tonic::Status>(())
})
.await;
match addr_recv_timeout {
Ok(Ok(())) => {}
Ok(Err(e)) => {
fetcher_task_handle.abort();
return Err(e);
}
Err(_) => {
fetcher_task_handle.abort();
return Err(tonic::Status::deadline_exceeded(
"Error: get_taddress_balance_stream request timed out in address loop.",
));
}
}
match fetcher_task_handle.await {
Ok(Ok(total_balance)) => {
let checked_balance: i64 = match i64::try_from(total_balance) {
Ok(balance) => balance,
Err(_) => {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
return Err(tonic::Status::unknown(
"Error: Error converting balance from u64 to i64.",
));
}
};
Ok(tonic::Response::new(Balance {
value_zat: checked_balance,
}))
}
Ok(Err(e)) => Err(e),
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
Err(e) => Err(tonic::Status::unknown(format!(
"Fetcher Task failed: {}",
e
))),
}
})
}
/// Server streaming response type for the GetMempoolTx method.
#[doc = "Server streaming response type for the GetMempoolTx method."]
type GetMempoolTxStream = std::pin::Pin<Box<CompactTransactionStream>>;
/// Return the compact transactions currently in the mempool; the results
/// can be a few seconds out of date. If the Exclude list is empty, return
/// all transactions; otherwise return all *except* those in the Exclude list
/// (if any); this allows the client to avoid receiving transactions that it
/// already has (from an earlier call to this rpc). The transaction IDs in the
/// Exclude list can be shortened to any number of bytes to make the request
/// more bandwidth-efficient; if two or more transactions in the mempool
/// match a shortened txid, they are all sent (none is excluded). Transactions
/// in the exclude list that don't exist in the mempool are ignored.
///
/// NOTE: This implementation is slow and should be re-implemented with the addition of the internal mempool and blockcache.
fn get_mempool_tx<'life0, 'async_trait>(
&'life0 self,
request: tonic::Request<Exclude>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<
tonic::Response<Self::GetMempoolTxStream>,
tonic::Status,
>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of get_mempool_tx.");
Box::pin(async {
let zebrad_uri = self.zebrad_uri.clone();
let zebrad_client = JsonRpcConnector::new(
self.zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?;
let exclude_txids: Vec<String> = request
.into_inner()
.txid
.iter()
.map(|txid_bytes| {
let reversed_txid_bytes: Vec<u8> = txid_bytes.iter().cloned().rev().collect();
hex::encode(&reversed_txid_bytes)
})
.collect();
let (channel_tx, channel_rx) = tokio::sync::mpsc::channel(32);
tokio::spawn(async move {
// NOTE: This timeout is so slow due to the blockcache not being implemented. This should be reduced to 30s once functionality is in place.
// TODO: Make [rpc_timout] a configurable system variable with [default = 30s] and [mempool_rpc_timout = 4*rpc_timeout]
let timeout = timeout(std::time::Duration::from_secs(480), async {
let mempool = Mempool::new();
if let Err(e) = mempool.update(&zebrad_uri).await {
channel_tx.send(Err(tonic::Status::unknown(e.to_string())))
.await
.ok();
return;
}
match mempool.get_filtered_mempool_txids(exclude_txids).await {
Ok(mempool_txids) => {
for txid in mempool_txids {
match zebrad_client
.get_raw_transaction(txid.clone(), Some(0))
.await {
Ok(GetTransactionResponse::Object { .. }) => {
if channel_tx
.send(Err(tonic::Status::internal(
"Error: Received transaction object type, this should not be impossible.",
)))
.await
.is_err()
{
break;
}
}
Ok(GetTransactionResponse::Raw(raw)) => {
let txid_bytes = match hex::decode(txid) {
Ok(bytes) => bytes,
Err(e) => {
if channel_tx
.send(Err(tonic::Status::unknown(e.to_string())))
.await
.is_err()
{
break;
} else {
continue;
}
}
};
match FullTransaction::parse_from_slice(raw.as_ref(), Some(vec!(txid_bytes)), None) {
Ok(transaction) => {
if transaction.0.len() > 0 {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
if channel_tx
.send(Err(tonic::Status::unknown("Error: ")))
.await
.is_err()
{
break;
}
} else {
match transaction.1.to_compact(0) {
Ok(compact_tx) => {
if channel_tx
.send(Ok(compact_tx))
.await
.is_err()
{
break;
}
}
Err(e) => {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
if channel_tx
.send(Err(tonic::Status::unknown(e.to_string())))
.await
.is_err()
{
break;
}
}
}
}
}
Err(e) => {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
if channel_tx
.send(Err(tonic::Status::unknown(e.to_string())))
.await
.is_err()
{
break;
}
}
}
}
Err(e) => {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
if channel_tx
.send(Err(tonic::Status::unknown(e.to_string())))
.await
.is_err()
{
break;
}
}
}
}
}
Err(e) => {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
if channel_tx
.send(Err(tonic::Status::unknown(e.to_string())))
.await
.is_err()
{
return;
}
}
}
})
.await;
match timeout {
Ok(_) => {
return;
}
Err(_) => {
channel_tx
.send(Err(tonic::Status::deadline_exceeded(
"Error: get_mempool_stream gRPC request timed out",
)))
.await
.ok();
return;
}
}
});
let output_stream = CompactTransactionStream::new(channel_rx);
let stream_boxed = Box::pin(output_stream);
Ok(tonic::Response::new(stream_boxed))
})
}
/// Server streaming response type for the GetMempoolStream method.
#[doc = "Server streaming response type for the GetMempoolStream method."]
type GetMempoolStreamStream = std::pin::Pin<Box<RawTransactionStream>>;
/// Return a stream of current Mempool transactions. This will keep the output stream open while
/// there are mempool transactions. It will close the returned stream when a new block is mined.
///
/// TODO: This implementation is slow. Zingo-Indexer's blockcache state engine should keep its own internal mempool state.
/// - This RPC should query Zingo-Indexer's internal mempool state rather than creating its own mempool and directly querying zebrad.
fn get_mempool_stream<'life0, 'async_trait>(
&'life0 self,
_request: tonic::Request<Empty>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<
tonic::Response<Self::GetMempoolStreamStream>,
tonic::Status,
>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of get_mempool_stream.");
Box::pin(async {
let zebrad_uri = self.zebrad_uri.clone();
let zebrad_client = JsonRpcConnector::new(
self.zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?;
let mempool_height = zebrad_client.get_blockchain_info().await?.blocks.0;
let (channel_tx, channel_rx) = tokio::sync::mpsc::channel(32);
tokio::spawn(async move {
// NOTE: This timeout is so slow due to the blockcache not being implemented. This should be reduced to 30s once functionality is in place.
// TODO: Make [rpc_timout] a configurable system variable with [default = 30s] and [mempool_rpc_timout = 4*rpc_timeout]
let timeout = timeout(std::time::Duration::from_secs(480), async {
let mempool = Mempool::new();
if let Err(e) = mempool.update(&zebrad_uri).await {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
channel_tx.send(Err(tonic::Status::unknown(e.to_string())))
.await
.ok();
return;
}
let mut mined = false;
let mut txid_index: usize = 0;
while !mined {
match mempool.get_mempool_txids().await {
Ok(mempool_txids) => {
for txid in &mempool_txids[txid_index..] {
match zebrad_client
.get_raw_transaction(txid.clone(), Some(1))
.await {
Ok(GetTransactionResponse::Object { hex, height: _, .. }) => {
txid_index += 1;
if channel_tx
.send(Ok(RawTransaction {
data: hex.as_ref().to_vec(),
height: mempool_height as u64,
}))
.await
.is_err()
{
break;
}
}
Ok(GetTransactionResponse::Raw(_)) => {
if channel_tx
.send(Err(tonic::Status::internal(
"Error: Received raw transaction type, this should not be impossible.",
)))
.await
.is_err()
{
break;
}
}
Err(e) => {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
if channel_tx
.send(Err(tonic::Status::unknown(e.to_string())))
.await
.is_err()
{
break;
}
}
}
}
}
Err(e) => {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
if channel_tx
.send(Err(tonic::Status::unknown(e.to_string())))
.await
.is_err()
{
break;
}
}
}
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
mined = match mempool.update(&zebrad_uri).await {
Ok(mined) => mined,
Err(e) => {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
channel_tx.send(Err(tonic::Status::unknown(e.to_string())))
.await
.ok();
break;
}
};
}
})
.await;
match timeout {
Ok(_) => {
return;
}
Err(_) => {
channel_tx
.send(Err(tonic::Status::deadline_exceeded(
"Error: get_mempool_stream gRPC request timed out",
)))
.await
.ok();
return;
}
}
});
let output_stream = RawTransactionStream::new(channel_rx);
let stream_boxed = Box::pin(output_stream);
Ok(tonic::Response::new(stream_boxed))
})
}
/// GetTreeState returns the note commitment tree state corresponding to the given block.
/// See section 3.7 of the Zcash protocol specification. It returns several other useful
/// values also (even though they can be obtained using GetBlock).
/// The block can be specified by either height or hash.
///
/// TODO: This is slow. Chain, along with other blockchain info should be saved on startup and used here [blockcache?].
fn get_tree_state<'life0, 'async_trait>(
&'life0 self,
request: tonic::Request<BlockId>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<tonic::Response<TreeState>, tonic::Status>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of get_tree_state.");
Box::pin(async {
let zebrad_client = JsonRpcConnector::new(
self.zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?;
let chain_info = zebrad_client
.get_blockchain_info()
.await
.map_err(|e| e.to_grpc_status())?;
let block_id = request.into_inner();
let hash_or_height = if block_id.height != 0 {
match u32::try_from(block_id.height) {
Ok(height) => {
if height >= chain_info.blocks.0 {
return Err(tonic::Status::out_of_range(
format!(
"Error: Height out of range [{}]. Height requested is greater than the best chain tip [{}].",
height, chain_info.blocks.0,
)
));
} else {
height.to_string()
}
}
Err(_) => {
return Err(tonic::Status::invalid_argument(
"Error: Height out of range. Failed to convert to u32.",
));
}
}
} else {
hex::encode(block_id.hash)
};
match zebrad_client.get_treestate(hash_or_height).await {
Ok(state) => Ok(tonic::Response::new(TreeState {
network: chain_info.chain,
height: state.height as u64,
hash: state.hash.to_string(),
time: state.time,
sapling_tree: state.sapling.inner().inner().clone(),
orchard_tree: state.orchard.inner().inner().clone(),
})),
Err(e) => {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
return Err(tonic::Status::unknown(format!(
"Error: Failed to retrieve treestate from node. Server Error: {}",
e.to_string(),
)));
}
}
})
}
/// GetLatestTreeState returns the note commitment tree state corresponding to the chain tip.
///
/// TODO: This is slow. Chain, along with other blockchain info should be saved on startup and used here [blockcache?].
fn get_latest_tree_state<'life0, 'async_trait>(
&'life0 self,
_request: tonic::Request<Empty>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<tonic::Response<TreeState>, tonic::Status>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of get_latest_tree_state.");
Box::pin(async {
let zebrad_client = JsonRpcConnector::new(
self.zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?;
let chain_info = zebrad_client
.get_blockchain_info()
.await
.map_err(|e| e.to_grpc_status())?;
match zebrad_client
.get_treestate(chain_info.blocks.0.to_string())
.await
{
Ok(state) => Ok(tonic::Response::new(TreeState {
network: chain_info.chain,
height: state.height as u64,
hash: state.hash.to_string(),
time: state.time,
sapling_tree: state.sapling.inner().inner().clone(),
orchard_tree: state.orchard.inner().inner().clone(),
})),
Err(e) => {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
return Err(tonic::Status::unknown(format!(
"Error: Failed to retrieve treestate from node. Server Error: {}",
e.to_string(),
)));
}
}
})
}
/// Server streaming response type for the GetSubtreeRoots method.
#[doc = " Server streaming response type for the GetSubtreeRoots method."]
type GetSubtreeRootsStream = std::pin::Pin<Box<SubtreeRootReplyStream>>;
/// Returns a stream of information about roots of subtrees of the Sapling and Orchard
/// note commitment trees.
fn get_subtree_roots<'life0, 'async_trait>(
&'life0 self,
request: tonic::Request<GetSubtreeRootsArg>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<
tonic::Response<Self::GetSubtreeRootsStream>,
tonic::Status,
>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of get_subtree_roots.");
Box::pin(async move {
let zebrad_uri =self.zebrad_uri.clone();
let zebrad_client = JsonRpcConnector::new(
zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?;
let subtree_roots_args = request.into_inner();
let pool = match ShieldedProtocol::try_from(subtree_roots_args.shielded_protocol) {
Ok(protocol) => protocol.as_str_name(),
Err(_) => return Err(tonic::Status::invalid_argument("Error: Invalid shielded protocol value.")),
};
let start_index = match u16::try_from(subtree_roots_args.start_index) {
Ok(value) => value,
Err(_) => return Err(tonic::Status::invalid_argument("Error: start_index value exceeds u16 range.")),
};
let limit = if subtree_roots_args.max_entries == 0 {
None
} else {
match u16::try_from(subtree_roots_args.max_entries) {
Ok(value) => Some(value),
Err(_) => return Err(tonic::Status::invalid_argument("Error: max_entries value exceeds u16 range.")),
}
};
let subtrees = zebrad_client.get_subtrees_by_index(pool.to_string(), start_index, limit).await?;
let (channel_tx, channel_rx) = tokio::sync::mpsc::channel(32);
tokio::spawn(async move {
// NOTE: This timeout is so slow due to the blockcache not being implemented. This should be reduced to 30s once functionality is in place.
// TODO: Make [rpc_timout] a configurable system variable with [default = 30s] and [mempool_rpc_timout = 4*rpc_timeout]
let timeout = timeout(std::time::Duration::from_secs(120), async {
for subtree in subtrees.subtrees {
match zebrad_client.get_block(subtree.end_height.0.to_string(), Some(1)).await {
Ok(GetBlockResponse::Object {
hash,
confirmations: _,
height,
time: _,
tx: _,
trees: _,
}) => {
let checked_height = match height {
Some(h) => h.0 as u64,
None => {
match channel_tx
.send(Err(tonic::Status::unknown("Error: No block height returned by node.")))
.await
{
Ok(_) => break,
Err(e) => {
eprintln!("Error: Channel closed unexpectedly: {}", e.to_string());
break;
}
}
}
};
let checked_root_hash = match hex::decode(&subtree.root) {
Ok(hash) => hash,
Err(e) => {
match channel_tx
.send(Err(tonic::Status::unknown(format!("Error: Failed to hex decode root hash: {}.",
e.to_string()
))))
.await
{
Ok(_) => break,
Err(e) => {
eprintln!("Error: Channel closed unexpectedly: {}", e.to_string());
break;
}
}
}
};
if channel_tx.send(
Ok(SubtreeRoot {
root_hash: checked_root_hash,
completing_block_hash: hash.0.bytes_in_display_order().to_vec(),
completing_block_height: checked_height,
})).await.is_err()
{
break;
}
}
Ok(GetBlockResponse::Raw(_)) => {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
if channel_tx
.send(Err(tonic::Status::unknown("Error: Received raw block type, this should not be possible.")))
.await
.is_err()
{
break;
}
}
Err(e) => {
// TODO: Hide server error from clients before release. Currently useful for dev purposes.
if channel_tx
.send(Err(tonic::Status::unknown(format!("Error: Could not fetch block at height [{}] from node: {}",
subtree.end_height.0.to_string(),
e.to_string()
))))
.await
.is_err()
{
break;
}
}
}
}
})
.await;
match timeout {
Ok(_) => {
return;
}
Err(_) => {
channel_tx
.send(Err(tonic::Status::deadline_exceeded(
"Error: get_mempool_stream gRPC request timed out",
)))
.await
.ok();
return;
}
}
});
let output_stream = SubtreeRootReplyStream::new(channel_rx);
let stream_boxed = Box::pin(output_stream);
Ok(tonic::Response::new(stream_boxed))
})
}
/// Returns all unspent outputs for a list of addresses.
///
/// Ignores all utxos below block height [GetAddressUtxosArg.start_height].
/// Returns max [GetAddressUtxosArg.max_entries] utxos, or unrestricted if [GetAddressUtxosArg.max_entries] = 0.
/// Utxos are collected and returned as a single Vec.
fn get_address_utxos<'life0, 'async_trait>(
&'life0 self,
request: tonic::Request<GetAddressUtxosArg>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<
tonic::Response<GetAddressUtxosReplyList>,
tonic::Status,
>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of get_address_utxos.");
Box::pin(async {
let zebrad_client = JsonRpcConnector::new(
self.zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?;
let addr_args = request.into_inner();
if !addr_args
.addresses
.iter()
.all(|taddr| check_taddress(taddr).is_some())
{
return Err(tonic::Status::invalid_argument(
"Error: One or more invalid taddresses given.",
));
}
let utxos = zebrad_client.get_address_utxos(addr_args.addresses).await?;
let mut address_utxos: Vec<GetAddressUtxosReply> = Vec::new();
let mut entries: u32 = 0;
for utxo in utxos {
if (utxo.height.0 as u64) < addr_args.start_height {
continue;
}
entries += 1;
if addr_args.max_entries > 0 && entries > addr_args.max_entries {
break;
}
let checked_index = match i32::try_from(utxo.output_index) {
Ok(index) => index,
Err(_) => {
return Err(tonic::Status::unknown(
"Error: Index out of range. Failed to convert to i32.",
));
}
};
let checked_satoshis = match i64::try_from(utxo.satoshis) {
Ok(satoshis) => satoshis,
Err(_) => {
return Err(tonic::Status::unknown(
"Error: Satoshis out of range. Failed to convert to i64.",
));
}
};
let utxo_reply = GetAddressUtxosReply {
address: utxo.address.to_string(),
txid: utxo.txid.0.to_vec(),
index: checked_index,
script: utxo.script.as_ref().to_vec(),
value_zat: checked_satoshis,
height: utxo.height.0 as u64,
};
address_utxos.push(utxo_reply)
}
Ok(tonic::Response::new(GetAddressUtxosReplyList {
address_utxos,
}))
})
}
/// Server streaming response type for the GetAddressUtxosStream method.
#[doc = "Server streaming response type for the GetAddressUtxosStream method."]
type GetAddressUtxosStreamStream = std::pin::Pin<Box<UtxoReplyStream>>;
/// Returns all unspent outputs for a list of addresses.
///
/// Ignores all utxos below block height [GetAddressUtxosArg.start_height].
/// Returns max [GetAddressUtxosArg.max_entries] utxos, or unrestricted if [GetAddressUtxosArg.max_entries] = 0.
/// Utxos are returned in a stream.
fn get_address_utxos_stream<'life0, 'async_trait>(
&'life0 self,
request: tonic::Request<GetAddressUtxosArg>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<
tonic::Response<Self::GetAddressUtxosStreamStream>,
tonic::Status,
>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of get_address_utxos_stream.");
Box::pin(async {
let zebrad_client = JsonRpcConnector::new(
self.zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?;
let addr_args = request.into_inner();
if !addr_args
.addresses
.iter()
.all(|taddr| check_taddress(taddr).is_some())
{
return Err(tonic::Status::invalid_argument(
"Error: One or more invalid taddresses given.",
));
}
let utxos = zebrad_client.get_address_utxos(addr_args.addresses).await?;
let (channel_tx, channel_rx) = tokio::sync::mpsc::channel(32);
tokio::spawn(async move {
// NOTE: This timeout is so slow due to the blockcache not being implemented. This should be reduced to 30s once functionality is in place.
// TODO: Make [rpc_timout] a configurable system variable with [default = 30s] and [mempool_rpc_timout = 4*rpc_timeout]
let timeout = timeout(std::time::Duration::from_secs(120), async {
let mut entries: u32 = 0;
for utxo in utxos {
if (utxo.height.0 as u64) < addr_args.start_height {
continue;
}
entries += 1;
if addr_args.max_entries > 0 && entries > addr_args.max_entries {
break;
}
let checked_index = match i32::try_from(utxo.output_index) {
Ok(index) => index,
Err(_) => {
let _ = channel_tx
.send(Err(tonic::Status::unknown(
"Error: Index out of range. Failed to convert to i32.",
)))
.await;
return;
}
};
let checked_satoshis = match i64::try_from(utxo.satoshis) {
Ok(satoshis) => satoshis,
Err(_) => {
let _ = channel_tx
.send(Err(tonic::Status::unknown(
"Error: Satoshis out of range. Failed to convert to i64.",
)))
.await;
return;
}
};
let utxo_reply = GetAddressUtxosReply {
address: utxo.address.to_string(),
txid: utxo.txid.0.to_vec(),
index: checked_index,
script: utxo.script.as_ref().to_vec(),
value_zat: checked_satoshis,
height: utxo.height.0 as u64,
};
if channel_tx.send(Ok(utxo_reply)).await.is_err() {
return;
}
}
})
.await;
match timeout {
Ok(_) => {
return;
}
Err(_) => {
channel_tx
.send(Err(tonic::Status::deadline_exceeded(
"Error: get_mempool_stream gRPC request timed out",
)))
.await
.ok();
return;
}
}
});
let output_stream = UtxoReplyStream::new(channel_rx);
let stream_boxed = Box::pin(output_stream);
Ok(tonic::Response::new(stream_boxed))
})
}
/// Return information about this lightwalletd instance and the blockchain
fn get_lightd_info<'life0, 'async_trait>(
&'life0 self,
_request: tonic::Request<Empty>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<tonic::Response<LightdInfo>, tonic::Status>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of get_lightd_info.");
// TODO: Add user and password as fields of GrpcClient and use here.
Box::pin(async {
let zebrad_client = JsonRpcConnector::new(
self.zebrad_uri.clone(),
Some("xxxxxx".to_string()),
Some("xxxxxx".to_string()),
)
.await?;
let zebra_info = zebrad_client
.get_info()
.await
.map_err(|e| e.to_grpc_status())?;
let blockchain_info = zebrad_client
.get_blockchain_info()
.await
.map_err(|e| e.to_grpc_status())?;
let build_info = get_build_info();
let sapling_id = zebra_rpc::methods::ConsensusBranchIdHex::new(
zebra_chain::parameters::ConsensusBranchId::from_hex("76b809bb")
.map_err(|_e| {
tonic::Status::internal(
"Internal Error - Consesnsus Branch ID hex conversion failed",
)
})?
.into(),
);
let sapling_activation_height = blockchain_info
.upgrades
.get(&sapling_id)
.map_or(zebra_chain::block::Height(1), |sapling_json| {
sapling_json.into_parts().1
});
let consensus_branch_id = zebra_chain::parameters::ConsensusBranchId::from(
blockchain_info.consensus.into_parts().0,
)
.to_string();
Ok(tonic::Response::new(LightdInfo {
version: build_info.version,
vendor: "ZingoLabs ZainoD".to_string(),
taddr_support: true,
chain_name: blockchain_info.chain,
sapling_activation_height: sapling_activation_height.0 as u64,
consensus_branch_id,
block_height: blockchain_info.blocks.0 as u64,
git_commit: build_info.commit_hash,
branch: build_info.branch,
build_date: build_info.build_date,
build_user: build_info.build_user,
estimated_height: blockchain_info.estimated_height.0 as u64,
zcashd_build: zebra_info.build,
zcashd_subversion: zebra_info.subversion,
}))
})
}
/// Testing-only, requires lightwalletd --ping-very-insecure (do not enable in production) [from zebrad]
/// This RPC has not been implemented as it is not currently used by zingolib.
/// If you require this RPC please open an issue or PR at the Zingo-Indexer github (https://github.com/zingolabs/zingo-indexer).
fn ping<'life0, 'async_trait>(
&'life0 self,
_request: tonic::Request<Duration>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<
Output = std::result::Result<tonic::Response<PingResponse>, tonic::Status>,
> + core::marker::Send
+ 'async_trait,
>,
>
where
'life0: 'async_trait,
Self: 'async_trait,
{
println!("[TEST] Received call of ping.");
Box::pin(async {
Err(tonic::Status::unimplemented("ping not yet implemented. If you require this RPC please open an issue or PR at the Zingo-Indexer github (https://github.com/zingolabs/zingo-indexer)."))
})
}
}