1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::{
gas::GasMeter,
storage::{self, DepositAccount, WriteOutcome},
BalanceOf, CodeHash, Config, ContractInfo, ContractInfoOf, DebugBufferVec, Determinism, Error,
Event, Nonce, Origin, Pallet as Contracts, Schedule, System, LOG_TARGET,
};
use frame_support::{
crypto::ecdsa::ECDSAExt,
dispatch::{
fmt::Debug, DispatchError, DispatchResult, DispatchResultWithPostInfo, Dispatchable,
},
storage::{with_transaction, TransactionOutcome},
traits::{
tokens::{Fortitude::Polite, Preservation::Expendable},
Contains, Currency, ExistenceRequirement, OriginTrait, Randomness, Time,
},
weights::Weight,
Blake2_128Concat, BoundedVec, StorageHasher,
};
use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin};
use pallet_contracts_primitives::ExecReturnValue;
use smallvec::{Array, SmallVec};
use sp_core::{
ecdsa::Public as ECDSAPublic,
sr25519::{Public as SR25519Public, Signature as SR25519Signature},
};
use sp_io::{crypto::secp256k1_ecdsa_recover_compressed, hashing::blake2_256};
use sp_runtime::traits::{Convert, Hash, Zero};
use sp_std::{marker::PhantomData, mem, prelude::*, vec::Vec};
pub type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
pub type MomentOf<T> = <<T as Config>::Time as Time>::Moment;
pub type SeedOf<T> = <T as frame_system::Config>::Hash;
pub type ExecResult = Result<ExecReturnValue, ExecError>;
/// A type that represents a topic of an event. At the moment a hash is used.
pub type TopicOf<T> = <T as frame_system::Config>::Hash;
/// Type for variable sized storage key. Used for transparent hashing.
type VarSizedKey<T> = BoundedVec<u8, <T as Config>::MaxStorageKeyLen>;
/// Combined key type for both fixed and variable sized storage keys.
pub enum Key<T: Config> {
/// Variant for fixed sized keys.
Fix([u8; 32]),
/// Variant for variable sized keys.
Var(VarSizedKey<T>),
}
impl<T: Config> Key<T> {
/// Copies self into a new vec.
pub fn to_vec(&self) -> Vec<u8> {
match self {
Key::Fix(v) => v.to_vec(),
Key::Var(v) => v.to_vec(),
}
}
pub fn hash(&self) -> Vec<u8> {
match self {
Key::Fix(v) => blake2_256(v.as_slice()).to_vec(),
Key::Var(v) => Blake2_128Concat::hash(v.as_slice()),
}
}
pub fn try_from_fix(v: Vec<u8>) -> Result<Self, Vec<u8>> {
<[u8; 32]>::try_from(v).map(Self::Fix)
}
pub fn try_from_var(v: Vec<u8>) -> Result<Self, Vec<u8>> {
VarSizedKey::<T>::try_from(v).map(Self::Var)
}
}
/// Origin of the error.
///
/// Call or instantiate both called into other contracts and pass through errors happening
/// in those to the caller. This enum is for the caller to distinguish whether the error
/// happened during the execution of the callee or in the current execution context.
#[cfg_attr(test, derive(Debug, PartialEq))]
pub enum ErrorOrigin {
/// Caller error origin.
///
/// The error happened in the current execution context rather than in the one
/// of the contract that is called into.
Caller,
/// The error happened during execution of the called contract.
Callee,
}
/// Error returned by contract execution.
#[cfg_attr(test, derive(Debug, PartialEq))]
pub struct ExecError {
/// The reason why the execution failed.
pub error: DispatchError,
/// Origin of the error.
pub origin: ErrorOrigin,
}
impl<T: Into<DispatchError>> From<T> for ExecError {
fn from(error: T) -> Self {
Self {
error: error.into(),
origin: ErrorOrigin::Caller,
}
}
}
/// An interface that provides access to the external environment in which the
/// smart-contract is executed.
///
/// This interface is specialized to an account of the executing code, so all
/// operations are implicitly performed on that account.
///
/// # Note
///
/// This trait is sealed and cannot be implemented by downstream crates.
pub trait Ext: sealing::Sealed {
type T: Config;
/// Call (possibly transferring some amount of funds) into the specified account.
///
/// Returns the code size of the called contract.
fn call(
&mut self,
gas_limit: Weight,
deposit_limit: BalanceOf<Self::T>,
to: AccountIdOf<Self::T>,
value: BalanceOf<Self::T>,
input_data: Vec<u8>,
allows_reentry: bool,
) -> Result<ExecReturnValue, ExecError>;
/// Execute code in the current frame.
///
/// Returns the code size of the called contract.
fn delegate_call(
&mut self,
code: CodeHash<Self::T>,
input_data: Vec<u8>,
) -> Result<ExecReturnValue, ExecError>;
/// Instantiate a contract from the given code.
///
/// Returns the original code size of the called contract.
/// The newly created account will be associated with `code`. `value` specifies the amount of
/// value transferred from the caller to the newly created account.
fn instantiate(
&mut self,
gas_limit: Weight,
deposit_limit: BalanceOf<Self::T>,
code: CodeHash<Self::T>,
value: BalanceOf<Self::T>,
input_data: Vec<u8>,
salt: &[u8],
) -> Result<(AccountIdOf<Self::T>, ExecReturnValue), ExecError>;
/// Transfer all funds to `beneficiary` and delete the contract.
///
/// Since this function removes the self contract eagerly, if succeeded, no further actions
/// should be performed on this `Ext` instance.
///
/// This function will fail if the same contract is present on the contract
/// call stack.
fn terminate(&mut self, beneficiary: &AccountIdOf<Self::T>) -> Result<(), DispatchError>;
/// Transfer some amount of funds into the specified account.
fn transfer(&mut self, to: &AccountIdOf<Self::T>, value: BalanceOf<Self::T>) -> DispatchResult;
/// Returns the storage entry of the executing account by the given `key`.
///
/// Returns `None` if the `key` wasn't previously set by `set_storage` or
/// was deleted.
fn get_storage(&mut self, key: &Key<Self::T>) -> Option<Vec<u8>>;
/// Returns `Some(len)` (in bytes) if a storage item exists at `key`.
///
/// Returns `None` if the `key` wasn't previously set by `set_storage` or
/// was deleted.
fn get_storage_size(&mut self, key: &Key<Self::T>) -> Option<u32>;
/// Sets the storage entry by the given key to the specified value. If `value` is `None` then
/// the storage entry is deleted.
fn set_storage(
&mut self,
key: &Key<Self::T>,
value: Option<Vec<u8>>,
take_old: bool,
) -> Result<WriteOutcome, DispatchError>;
/// Returns the caller.
fn caller(&self) -> Origin<Self::T>;
/// Check if a contract lives at the specified `address`.
fn is_contract(&self, address: &AccountIdOf<Self::T>) -> bool;
/// Returns the code hash of the contract for the given `address`.
///
/// Returns `None` if the `address` does not belong to a contract.
fn code_hash(&self, address: &AccountIdOf<Self::T>) -> Option<CodeHash<Self::T>>;
/// Returns the code hash of the contract being executed.
fn own_code_hash(&mut self) -> &CodeHash<Self::T>;
/// Check if the caller of the current contract is the origin of the whole call stack.
///
/// This can be checked with `is_contract(self.caller())` as well.
/// However, this function does not require any storage lookup and therefore uses less weight.
fn caller_is_origin(&self) -> bool;
/// Check if the caller is origin, and this origin is root.
fn caller_is_root(&self) -> bool;
/// Returns a reference to the account id of the current contract.
fn address(&self) -> &AccountIdOf<Self::T>;
/// Returns the balance of the current contract.
///
/// The `value_transferred` is already added.
fn balance(&self) -> BalanceOf<Self::T>;
/// Returns the value transferred along with this call.
fn value_transferred(&self) -> BalanceOf<Self::T>;
/// Returns a reference to the timestamp of the current block
fn now(&self) -> &MomentOf<Self::T>;
/// Returns the minimum balance that is required for creating an account.
fn minimum_balance(&self) -> BalanceOf<Self::T>;
/// Returns a random number for the current block with the given subject.
fn random(&self, subject: &[u8]) -> (SeedOf<Self::T>, BlockNumberFor<Self::T>);
/// Deposit an event with the given topics.
///
/// There should not be any duplicates in `topics`.
fn deposit_event(&mut self, topics: Vec<TopicOf<Self::T>>, data: Vec<u8>);
/// Returns the current block number.
fn block_number(&self) -> BlockNumberFor<Self::T>;
/// Returns the maximum allowed size of a storage item.
fn max_value_size(&self) -> u32;
/// Returns the price for the specified amount of weight.
fn get_weight_price(&self, weight: Weight) -> BalanceOf<Self::T>;
/// Get a reference to the schedule used by the current call.
fn schedule(&self) -> &Schedule<Self::T>;
/// Get an immutable reference to the nested gas meter.
fn gas_meter(&self) -> &GasMeter<Self::T>;
/// Get a mutable reference to the nested gas meter.
fn gas_meter_mut(&mut self) -> &mut GasMeter<Self::T>;
/// Append a string to the debug buffer.
///
/// It is added as-is without any additional new line.
///
/// This is a no-op if debug message recording is disabled which is always the case
/// when the code is executing on-chain.
///
/// Returns `true` if debug message recording is enabled. Otherwise `false` is returned.
fn append_debug_buffer(&mut self, msg: &str) -> bool;
/// Call some dispatchable and return the result.
fn call_runtime(&self, call: <Self::T as Config>::RuntimeCall) -> DispatchResultWithPostInfo;
/// Recovers ECDSA compressed public key based on signature and message hash.
fn ecdsa_recover(&self, signature: &[u8; 65], message_hash: &[u8; 32]) -> Result<[u8; 33], ()>;
/// Verify a sr25519 signature.
fn sr25519_verify(&self, signature: &[u8; 64], message: &[u8], pub_key: &[u8; 32]) -> bool;
/// Returns Ethereum address from the ECDSA compressed public key.
fn ecdsa_to_eth_address(&self, pk: &[u8; 33]) -> Result<[u8; 20], ()>;
/// Tests sometimes need to modify and inspect the contract info directly.
#[cfg(test)]
fn contract_info(&mut self) -> &mut ContractInfo<Self::T>;
/// Sets new code hash for existing contract.
fn set_code_hash(&mut self, hash: CodeHash<Self::T>) -> Result<(), DispatchError>;
/// Returns the number of times the currently executing contract exists on the call stack in
/// addition to the calling instance. A value of 0 means no reentrancy.
fn reentrance_count(&self) -> u32;
/// Returns the number of times the specified contract exists on the call stack. Delegated calls
/// are not calculated as separate entrance.
/// A value of 0 means it does not exist on the call stack.
fn account_reentrance_count(&self, account_id: &AccountIdOf<Self::T>) -> u32;
/// Returns a nonce that is incremented for every instantiated contract.
fn nonce(&mut self) -> u64;
}
/// Describes the different functions that can be exported by an [`Executable`].
#[derive(Clone, Copy, PartialEq)]
pub enum ExportedFunction {
/// The constructor function which is executed on deployment of a contract.
Constructor,
/// The function which is executed when a contract is called.
Call,
}
/// A trait that represents something that can be executed.
///
/// In the on-chain environment this would be represented by a wasm module. This trait exists in
/// order to be able to mock the wasm logic for testing.
pub trait Executable<T: Config>: Sized {
/// Load the executable from storage.
///
/// # Note
/// Charges size base load weight from the gas meter.
fn from_storage(
code_hash: CodeHash<T>,
gas_meter: &mut GasMeter<T>,
) -> Result<Self, DispatchError>;
/// Increment the reference count of a of a stored code by one.
///
/// # Errors
///
/// [`Error::CodeNotFound`] is returned if no stored code found having the specified
/// `code_hash`.
fn increment_refcount(code_hash: CodeHash<T>) -> Result<(), DispatchError>;
/// Decrement the reference count of a stored code by one.
///
/// # Note
///
/// A contract whose reference count dropped to zero isn't automatically removed. A
/// `remove_code` transaction must be submitted by the original uploader to do so.
fn decrement_refcount(code_hash: CodeHash<T>);
/// Execute the specified exported function and return the result.
///
/// When the specified function is `Constructor` the executable is stored and its
/// refcount incremented.
///
/// # Note
///
/// This functions expects to be executed in a storage transaction that rolls back
/// all of its emitted storage changes.
fn execute<E: Ext<T = T>>(
self,
ext: &mut E,
function: &ExportedFunction,
input_data: Vec<u8>,
) -> ExecResult;
/// The code hash of the executable.
fn code_hash(&self) -> &CodeHash<T>;
/// Size of the contract code in bytes.
fn code_len(&self) -> u32;
/// The code does not contain any instructions which could lead to indeterminism.
fn is_deterministic(&self) -> bool;
}
/// The complete call stack of a contract execution.
///
/// The call stack is initiated by either a signed origin or one of the contract RPC calls.
/// This type implements `Ext` and by that exposes the business logic of contract execution to
/// the runtime module which interfaces with the contract (the wasm blob) itself.
pub struct Stack<'a, T: Config, E> {
/// The origin that initiated the call stack. It could either be a Signed plain account that
/// holds an account id or Root.
///
/// # Note
///
/// Please note that it is possible that the id of a Signed origin belongs to a contract rather
/// than a plain account when being called through one of the contract RPCs where the
/// client can freely choose the origin. This usually makes no sense but is still possible.
origin: Origin<T>,
/// The cost schedule used when charging from the gas meter.
schedule: &'a Schedule<T>,
/// The gas meter where costs are charged to.
gas_meter: &'a mut GasMeter<T>,
/// The storage meter makes sure that the storage deposit limit is obeyed.
storage_meter: &'a mut storage::meter::Meter<T>,
/// The timestamp at the point of call stack instantiation.
timestamp: MomentOf<T>,
/// The block number at the time of call stack instantiation.
block_number: BlockNumberFor<T>,
/// The nonce is cached here when accessed. It is written back when the call stack
/// finishes executing. Please refer to [`Nonce`] to a description of
/// the nonce itself.
nonce: Option<u64>,
/// The actual call stack. One entry per nested contract called/instantiated.
/// This does **not** include the [`Self::first_frame`].
frames: SmallVec<T::CallStack>,
/// Statically guarantee that each call stack has at least one frame.
first_frame: Frame<T>,
/// A text buffer used to output human readable information.
///
/// All the bytes added to this field should be valid UTF-8. The buffer has no defined
/// structure and is intended to be shown to users as-is for debugging purposes.
debug_message: Option<&'a mut DebugBufferVec<T>>,
/// The determinism requirement of this call stack.
determinism: Determinism,
/// No executable is held by the struct but influences its behaviour.
_phantom: PhantomData<E>,
}
/// Represents one entry in the call stack.
///
/// For each nested contract call or instantiate one frame is created. It holds specific
/// information for the said call and caches the in-storage `ContractInfo` data structure.
///
/// # Note
///
/// This is an internal data structure. It is exposed to the public for the sole reason
/// of specifying [`Config::CallStack`].
pub struct Frame<T: Config> {
/// The account id of the executing contract.
account_id: T::AccountId,
/// The cached in-storage data of the contract.
contract_info: CachedContract<T>,
/// The amount of balance transferred by the caller as part of the call.
value_transferred: BalanceOf<T>,
/// Determines whether this is a call or instantiate frame.
entry_point: ExportedFunction,
/// The gas meter capped to the supplied gas limit.
nested_gas: GasMeter<T>,
/// The storage meter for the individual call.
nested_storage: storage::meter::NestedMeter<T>,
/// If `false` the contract enabled its defense against reentrance attacks.
allows_reentry: bool,
/// The caller of the currently executing frame which was spawned by `delegate_call`.
delegate_caller: Option<Origin<T>>,
}
/// Used in a delegate call frame arguments in order to override the executable and caller.
struct DelegatedCall<T: Config, E> {
/// The executable which is run instead of the contracts own `executable`.
executable: E,
/// The caller of the contract.
caller: Origin<T>,
}
/// Parameter passed in when creating a new `Frame`.
///
/// It determines whether the new frame is for a call or an instantiate.
enum FrameArgs<'a, T: Config, E> {
Call {
/// The account id of the contract that is to be called.
dest: T::AccountId,
/// If `None` the contract info needs to be reloaded from storage.
cached_info: Option<ContractInfo<T>>,
/// This frame was created by `seal_delegate_call` and hence uses different code than
/// what is stored at [`Self::Call::dest`]. Its caller ([`DelegatedCall::caller`]) is the
/// account which called the caller contract
delegated_call: Option<DelegatedCall<T, E>>,
},
Instantiate {
/// The contract or signed origin which instantiates the new contract.
sender: T::AccountId,
/// The nonce that should be used to derive a new trie id for the contract.
nonce: u64,
/// The executable whose `deploy` function is run.
executable: E,
/// A salt used in the contract address deriviation of the new contract.
salt: &'a [u8],
/// The input data is used in the contract address deriviation of the new contract.
input_data: &'a [u8],
},
}
/// Describes the different states of a contract as contained in a `Frame`.
enum CachedContract<T: Config> {
/// The cached contract is up to date with the in-storage value.
Cached(ContractInfo<T>),
/// A recursive call into the same contract did write to the contract info.
///
/// In this case the cached contract is stale and needs to be reloaded from storage.
Invalidated,
/// The current contract executed `terminate` and removed the contract.
///
/// In this case a reload is neither allowed nor possible. Please note that recursive
/// calls cannot remove a contract as this is checked and denied.
Terminated(DepositAccount<T>),
}
impl<T: Config> CachedContract<T> {
/// Return `Some(ContractInfo)` if the contract is in cached state. `None` otherwise.
fn into_contract(self) -> Option<ContractInfo<T>> {
if let CachedContract::Cached(contract) = self {
Some(contract)
} else {
None
}
}
/// Return `Some(&mut ContractInfo)` if the contract is in cached state. `None` otherwise.
fn as_contract(&mut self) -> Option<&mut ContractInfo<T>> {
if let CachedContract::Cached(contract) = self {
Some(contract)
} else {
None
}
}
/// Returns `Some` iff the contract is not `Cached::Invalidated`.
fn deposit_account(&self) -> Option<&DepositAccount<T>> {
match self {
CachedContract::Cached(contract) => Some(contract.deposit_account()),
CachedContract::Terminated(deposit_account) => Some(deposit_account),
CachedContract::Invalidated => None,
}
}
}
impl<T: Config> Frame<T> {
/// Return the `contract_info` of the current contract.
fn contract_info(&mut self) -> &mut ContractInfo<T> {
self.contract_info.get(&self.account_id)
}
/// Terminate and return the `contract_info` of the current contract.
///
/// # Note
///
/// Under no circumstances the contract is allowed to access the `contract_info` after
/// a call to this function. This would constitute a programming error in the exec module.
fn terminate(&mut self) -> ContractInfo<T> {
self.contract_info.terminate(&self.account_id)
}
}
/// Extract the contract info after loading it from storage.
///
/// This assumes that `load` was executed before calling this macro.
macro_rules! get_cached_or_panic_after_load {
($c:expr) => {{
if let CachedContract::Cached(contract) = $c {
contract
} else {
panic!(
"It is impossible to remove a contract that is on the call stack;\
See implementations of terminate;\
Therefore fetching a contract will never fail while using an account id
that is currently active on the call stack;\
qed"
);
}
}};
}
/// Same as [`Stack::top_frame`].
///
/// We need this access as a macro because sometimes hiding the lifetimes behind
/// a function won't work out.
macro_rules! top_frame {
($stack:expr) => {
$stack.frames.last().unwrap_or(&$stack.first_frame)
};
}
/// Same as [`Stack::top_frame_mut`].
///
/// We need this access as a macro because sometimes hiding the lifetimes behind
/// a function won't work out.
macro_rules! top_frame_mut {
($stack:expr) => {
$stack.frames.last_mut().unwrap_or(&mut $stack.first_frame)
};
}
impl<T: Config> CachedContract<T> {
/// Load the `contract_info` from storage if necessary.
fn load(&mut self, account_id: &T::AccountId) {
if let CachedContract::Invalidated = self {
let contract = <ContractInfoOf<T>>::get(account_id);
if let Some(contract) = contract {
*self = CachedContract::Cached(contract);
}
}
}
/// Return the cached contract_info.
fn get(&mut self, account_id: &T::AccountId) -> &mut ContractInfo<T> {
self.load(account_id);
get_cached_or_panic_after_load!(self)
}
/// Terminate and return the contract info.
fn terminate(&mut self, account_id: &T::AccountId) -> ContractInfo<T> {
self.load(account_id);
let contract = get_cached_or_panic_after_load!(self);
let deposit_account = contract.deposit_account().clone();
get_cached_or_panic_after_load!(mem::replace(self, Self::Terminated(deposit_account)))
}
}
impl<'a, T, E> Stack<'a, T, E>
where
T: Config,
E: Executable<T>,
{
/// Create and run a new call stack by calling into `dest`.
///
/// # Note
///
/// `debug_message` should only ever be set to `Some` when executing as an RPC because
/// it adds allocations and could be abused to drive the runtime into an OOM panic.
///
/// # Return Value
///
/// Result<(ExecReturnValue, CodeSize), (ExecError, CodeSize)>
pub fn run_call(
origin: Origin<T>,
dest: T::AccountId,
gas_meter: &'a mut GasMeter<T>,
storage_meter: &'a mut storage::meter::Meter<T>,
schedule: &'a Schedule<T>,
value: BalanceOf<T>,
input_data: Vec<u8>,
debug_message: Option<&'a mut DebugBufferVec<T>>,
determinism: Determinism,
) -> Result<ExecReturnValue, ExecError> {
let (mut stack, executable) = Self::new(
FrameArgs::Call {
dest,
cached_info: None,
delegated_call: None,
},
origin,
gas_meter,
storage_meter,
schedule,
value,
debug_message,
determinism,
)?;
stack.run(executable, input_data)
}
/// Create and run a new call stack by instantiating a new contract.
///
/// # Note
///
/// `debug_message` should only ever be set to `Some` when executing as an RPC because
/// it adds allocations and could be abused to drive the runtime into an OOM panic.
///
/// # Return Value
///
/// Result<(NewContractAccountId, ExecReturnValue), ExecError)>
pub fn run_instantiate(
origin: T::AccountId,
executable: E,
gas_meter: &'a mut GasMeter<T>,
storage_meter: &'a mut storage::meter::Meter<T>,
schedule: &'a Schedule<T>,
value: BalanceOf<T>,
input_data: Vec<u8>,
salt: &[u8],
debug_message: Option<&'a mut DebugBufferVec<T>>,
) -> Result<(T::AccountId, ExecReturnValue), ExecError> {
let (mut stack, executable) = Self::new(
FrameArgs::Instantiate {
sender: origin.clone(),
nonce: <Nonce<T>>::get().wrapping_add(1),
executable,
salt,
input_data: input_data.as_ref(),
},
Origin::from_account_id(origin),
gas_meter,
storage_meter,
schedule,
value,
debug_message,
Determinism::Enforced,
)?;
let account_id = stack.top_frame().account_id.clone();
stack
.run(executable, input_data)
.map(|ret| (account_id, ret))
}
/// Create a new call stack.
fn new(
args: FrameArgs<T, E>,
origin: Origin<T>,
gas_meter: &'a mut GasMeter<T>,
storage_meter: &'a mut storage::meter::Meter<T>,
schedule: &'a Schedule<T>,
value: BalanceOf<T>,
debug_message: Option<&'a mut DebugBufferVec<T>>,
determinism: Determinism,
) -> Result<(Self, E), ExecError> {
let (first_frame, executable, nonce) = Self::new_frame(
args,
value,
gas_meter,
Weight::zero(),
storage_meter,
BalanceOf::<T>::zero(),
determinism,
)?;
let stack = Self {
origin,
schedule,
gas_meter,
storage_meter,
timestamp: T::Time::now(),
block_number: <frame_system::Pallet<T>>::block_number(),
nonce,
first_frame,
frames: Default::default(),
debug_message,
determinism,
_phantom: Default::default(),
};
Ok((stack, executable))
}
/// Construct a new frame.
///
/// This does not take `self` because when constructing the first frame `self` is
/// not initialized, yet.
fn new_frame<S: storage::meter::State + Default + Debug>(
frame_args: FrameArgs<T, E>,
value_transferred: BalanceOf<T>,
gas_meter: &mut GasMeter<T>,
gas_limit: Weight,
storage_meter: &mut storage::meter::GenericMeter<T, S>,
deposit_limit: BalanceOf<T>,
determinism: Determinism,
) -> Result<(Frame<T>, E, Option<u64>), ExecError> {
let (account_id, contract_info, executable, delegate_caller, entry_point, nonce) =
match frame_args {
FrameArgs::Call {
dest,
cached_info,
delegated_call,
} => {
let contract = if let Some(contract) = cached_info {
contract
} else {
<ContractInfoOf<T>>::get(&dest).ok_or(<Error<T>>::ContractNotFound)?
};
let (executable, delegate_caller) =
if let Some(DelegatedCall { executable, caller }) = delegated_call {
(executable, Some(caller))
} else {
(E::from_storage(contract.code_hash, gas_meter)?, None)
};
(
dest,
contract,
executable,
delegate_caller,
ExportedFunction::Call,
None,
)
},
FrameArgs::Instantiate {
sender,
nonce,
executable,
salt,
input_data,
} => {
let account_id = Contracts::<T>::contract_address(
&sender,
executable.code_hash(),
input_data,
salt,
);
let contract = ContractInfo::new(&account_id, nonce, *executable.code_hash())?;
(
account_id,
contract,
executable,
None,
ExportedFunction::Constructor,
Some(nonce),
)
},
};
// `Relaxed` will only be ever set in case of off-chain execution.
// Instantiations are never allowed even when executing off-chain.
if !(executable.is_deterministic()
|| (matches!(determinism, Determinism::Relaxed)
&& matches!(entry_point, ExportedFunction::Call)))
{
return Err(Error::<T>::Indeterministic.into())
}
let frame = Frame {
delegate_caller,
value_transferred,
contract_info: CachedContract::Cached(contract_info),
account_id,
entry_point,
nested_gas: gas_meter.nested(gas_limit)?,
nested_storage: storage_meter.nested(deposit_limit),
allows_reentry: true,
};
Ok((frame, executable, nonce))
}
/// Create a subsequent nested frame.
fn push_frame(
&mut self,
frame_args: FrameArgs<T, E>,
value_transferred: BalanceOf<T>,
gas_limit: Weight,
deposit_limit: BalanceOf<T>,
) -> Result<E, ExecError> {
if self.frames.len() == T::CallStack::size() {
return Err(Error::<T>::MaxCallDepthReached.into())
}
// We need to make sure that changes made to the contract info are not discarded.
// See the `in_memory_changes_not_discarded` test for more information.
// We do not store on instantiate because we do not allow to call into a contract
// from its own constructor.
let frame = self.top_frame();
if let (CachedContract::Cached(contract), ExportedFunction::Call) =
(&frame.contract_info, frame.entry_point)
{
<ContractInfoOf<T>>::insert(frame.account_id.clone(), contract.clone());
}
let frame = top_frame_mut!(self);
let nested_gas = &mut frame.nested_gas;
let nested_storage = &mut frame.nested_storage;
let (frame, executable, _) = Self::new_frame(
frame_args,
value_transferred,
nested_gas,
gas_limit,
nested_storage,
deposit_limit,
self.determinism,
)?;
self.frames.push(frame);
Ok(executable)
}
/// Run the current (top) frame.
///
/// This can be either a call or an instantiate.
fn run(&mut self, executable: E, input_data: Vec<u8>) -> Result<ExecReturnValue, ExecError> {
let frame = self.top_frame();
let entry_point = frame.entry_point;
let delegated_code_hash = if frame.delegate_caller.is_some() {
Some(*executable.code_hash())
} else {
None
};
let do_transaction = || {
// We need to charge the storage deposit before the initial transfer so that
// it can create the account in case the initial transfer is < ed.
if entry_point == ExportedFunction::Constructor {
// Root origin can't be used to instantiate a contract, so it is safe to assume that
// if we reached this point the origin has an associated account.
let origin = &self.origin.account_id()?;
let frame = top_frame_mut!(self);
frame.nested_storage.charge_instantiate(
origin,
&frame.account_id,
frame.contract_info.get(&frame.account_id),
)?;
}
// Every non delegate call or instantiate also optionally transfers the balance.
self.initial_transfer()?;
// Call into the Wasm blob.
let output = executable
.execute(self, &entry_point, input_data)
.map_err(|e| ExecError {
error: e.error,
origin: ErrorOrigin::Callee,
})?;
// Avoid useless work that would be reverted anyways.
if output.did_revert() {
return Ok(output)
}
// Storage limit is normally enforced as late as possible (when the last frame returns)
// so that the ordering of storage accesses does not matter.
// (However, if a special limit was set for a sub-call, it should be enforced right
// after the sub-call returned. See below for this case of enforcement).
if self.frames.is_empty() {
let frame = &mut self.first_frame;
frame.contract_info.load(&frame.account_id);
let contract = frame.contract_info.as_contract();
frame.nested_storage.enforce_limit(contract)?;
}
let frame = self.top_frame();
let account_id = &frame.account_id.clone();
match (entry_point, delegated_code_hash) {
(ExportedFunction::Constructor, _) => {
// It is not allowed to terminate a contract inside its constructor.
if matches!(frame.contract_info, CachedContract::Terminated(_)) {
return Err(Error::<T>::TerminatedInConstructor.into())
}
// If a special limit was set for the sub-call, we enforce it here.
// This is needed because contract constructor might write to storage.
// The sub-call will be rolled back in case the limit is exhausted.
let frame = self.top_frame_mut();
let contract = frame.contract_info.as_contract();
frame.nested_storage.enforce_subcall_limit(contract)?;
let caller = self.caller().account_id()?.clone();
// Deposit an instantiation event.
Contracts::<T>::deposit_event(
vec![
T::Hashing::hash_of(&caller),
T::Hashing::hash_of(account_id),
],
Event::Instantiated {
deployer: caller,
contract: account_id.clone(),
},
);
},
(ExportedFunction::Call, Some(code_hash)) => {
Contracts::<T>::deposit_event(
vec![
T::Hashing::hash_of(account_id),
T::Hashing::hash_of(&code_hash),
],
Event::DelegateCalled {
contract: account_id.clone(),
code_hash,
},
);
},
(ExportedFunction::Call, None) => {
// If a special limit was set for the sub-call, we enforce it here.
// The sub-call will be rolled back in case the limit is exhausted.
let frame = self.top_frame_mut();
let contract = frame.contract_info.as_contract();
frame.nested_storage.enforce_subcall_limit(contract)?;
let caller = self.caller();
Contracts::<T>::deposit_event(
vec![
T::Hashing::hash_of(&caller),
T::Hashing::hash_of(&account_id),
],
Event::Called {
caller: caller.clone(),
contract: account_id.clone(),
},
);
},
}
Ok(output)
};
// All changes performed by the contract are executed under a storage transaction.
// This allows for roll back on error. Changes to the cached contract_info are
// committed or rolled back when popping the frame.
//
// `with_transactional` may return an error caused by a limit in the
// transactional storage depth.
let transaction_outcome =
with_transaction(|| -> TransactionOutcome<Result<_, DispatchError>> {
let output = do_transaction();
match &output {
Ok(result) if !result.did_revert() =>
TransactionOutcome::Commit(Ok((true, output))),
_ => TransactionOutcome::Rollback(Ok((false, output))),
}
});
let (success, output) = match transaction_outcome {
// `with_transactional` executed successfully, and we have the expected output.
Ok((success, output)) => (success, output),
// `with_transactional` returned an error, and we propagate that error and note no state
// has changed.
Err(error) => (false, Err(error.into())),
};
self.pop_frame(success);
output
}
/// Remove the current (top) frame from the stack.
///
/// This is called after running the current frame. It commits cached values to storage
/// and invalidates all stale references to it that might exist further down the call stack.
fn pop_frame(&mut self, persist: bool) {
// Revert changes to the nonce in case of a failed instantiation.
if !persist && self.top_frame().entry_point == ExportedFunction::Constructor {
self.nonce.as_mut().map(|c| *c = c.wrapping_sub(1));
}
// Pop the current frame from the stack and return it in case it needs to interact
// with duplicates that might exist on the stack.
// A `None` means that we are returning from the `first_frame`.
let frame = self.frames.pop();
// Both branches do essentially the same with the exception. The difference is that
// the else branch does consume the hardcoded `first_frame`.
if let Some(mut frame) = frame {
let account_id = &frame.account_id;
let prev = top_frame_mut!(self);
prev.nested_gas.absorb_nested(frame.nested_gas);
// Only gas counter changes are persisted in case of a failure.
if !persist {
return
}
// Record the storage meter changes of the nested call into the parent meter.
// If the dropped frame's contract wasn't terminated we update the deposit counter
// in its contract info. The load is necessary to pull it from storage in case
// it was invalidated.
frame.contract_info.load(account_id);
let deposit_account = frame
.contract_info
.deposit_account()
.expect(
"Is only `None` when the info is invalidated.
We just re-loaded from storage which either makes the state `Cached` or `Terminated`.
qed",
)
.clone();
let mut contract = frame.contract_info.into_contract();
prev.nested_storage
.absorb(frame.nested_storage, deposit_account, contract.as_mut());
// In case the contract wasn't terminated we need to persist changes made to it.
if let Some(contract) = contract {
// optimization: Predecessor is the same contract.
// We can just copy the contract into the predecessor without a storage write.
// This is possible when there is no other contract in-between that could
// trigger a rollback.
if prev.account_id == *account_id {
prev.contract_info = CachedContract::Cached(contract);
return
}
// Predecessor is a different contract: We persist the info and invalidate the first
// stale cache we find. This triggers a reload from storage on next use. We skip(1)
// because that case is already handled by the optimization above. Only the first
// cache needs to be invalidated because that one will invalidate the next cache
// when it is popped from the stack.
<ContractInfoOf<T>>::insert(account_id, contract);
if let Some(c) = self
.frames_mut()
.skip(1)
.find(|f| f.account_id == *account_id)
{
c.contract_info = CachedContract::Invalidated;
}
}
} else {
if let Some((msg, false)) = self.debug_message.as_ref().map(|m| (m, m.is_empty())) {
log::debug!(
target: LOG_TARGET,
"Execution finished with debug buffer: {}",
core::str::from_utf8(msg).unwrap_or("<Invalid UTF8>"),
);
}
self.gas_meter
.absorb_nested(mem::take(&mut self.first_frame.nested_gas));
if !persist {
return
}
let deposit_account = self.first_frame.contract_info.deposit_account().expect(
"Is only `None` when the info is invalidated. The first frame can't be invalidated.
qed",
).clone();
let mut contract = self.first_frame.contract_info.as_contract();
self.storage_meter.absorb(
mem::take(&mut self.first_frame.nested_storage),
deposit_account,
contract.as_deref_mut(),
);
if let Some(contract) = contract {
<ContractInfoOf<T>>::insert(&self.first_frame.account_id, contract);
}
if let Some(nonce) = self.nonce {
<Nonce<T>>::set(nonce);
}
}
}
/// Transfer some funds from `from` to `to`.
fn transfer(
existence_requirement: ExistenceRequirement,
from: &T::AccountId,
to: &T::AccountId,
value: BalanceOf<T>,
) -> DispatchResult {
T::Currency::transfer(from, to, value, existence_requirement)
.map_err(|_| Error::<T>::TransferFailed)?;
Ok(())
}
// The transfer as performed by a call or instantiate.
fn initial_transfer(&self) -> DispatchResult {
let frame = self.top_frame();
// If it is a delegate call, then we've already transferred tokens in the
// last non-delegate frame.
if frame.delegate_caller.is_some() {
return Ok(())
}
let value = frame.value_transferred;
// Get the account id from the caller.
// If the caller is root there is no account to transfer from, and therefore we can't take
// any `value` other than 0.
let caller = match self.caller() {
Origin::Signed(caller) => caller,
Origin::Root if value.is_zero() => return Ok(()),
Origin::Root => return DispatchError::RootNotAllowed.into(),
};
Self::transfer(
ExistenceRequirement::KeepAlive,
&caller,
&frame.account_id,
value,
)
}
/// Reference to the current (top) frame.
fn top_frame(&self) -> &Frame<T> {
top_frame!(self)
}
/// Mutable reference to the current (top) frame.
fn top_frame_mut(&mut self) -> &mut Frame<T> {
top_frame_mut!(self)
}
/// Iterator over all frames.
///
/// The iterator starts with the top frame and ends with the root frame.
fn frames(&self) -> impl Iterator<Item = &Frame<T>> {
sp_std::iter::once(&self.first_frame)
.chain(&self.frames)
.rev()
}
/// Same as `frames` but with a mutable reference as iterator item.
fn frames_mut(&mut self) -> impl Iterator<Item = &mut Frame<T>> {
sp_std::iter::once(&mut self.first_frame)
.chain(&mut self.frames)
.rev()
}
/// Returns whether the current contract is on the stack multiple times.
fn is_recursive(&self) -> bool {
let account_id = &self.top_frame().account_id;
self.frames().skip(1).any(|f| &f.account_id == account_id)
}
/// Returns whether the specified contract allows to be reentered right now.
fn allows_reentry(&self, id: &AccountIdOf<T>) -> bool {
!self
.frames()
.any(|f| &f.account_id == id && !f.allows_reentry)
}
/// Increments and returns the next nonce. Pulls it from storage if it isn't in cache.
fn next_nonce(&mut self) -> u64 {
let next = self.nonce().wrapping_add(1);
self.nonce = Some(next);
next
}
}
impl<'a, T, E> Ext for Stack<'a, T, E>
where
T: Config,
E: Executable<T>,
{
type T = T;
fn call(
&mut self,
gas_limit: Weight,
deposit_limit: BalanceOf<T>,
to: T::AccountId,
value: BalanceOf<T>,
input_data: Vec<u8>,
allows_reentry: bool,
) -> Result<ExecReturnValue, ExecError> {
// Before pushing the new frame: Protect the caller contract against reentrancy attacks.
// It is important to do this before calling `allows_reentry` so that a direct recursion
// is caught by it.
self.top_frame_mut().allows_reentry = allows_reentry;
let try_call = || {
if !self.allows_reentry(&to) {
return Err(<Error<T>>::ReentranceDenied.into())
}
// We ignore instantiate frames in our search for a cached contract.
// Otherwise it would be possible to recursively call a contract from its own
// constructor: We disallow calling not fully constructed contracts.
let cached_info = self
.frames()
.find(|f| f.entry_point == ExportedFunction::Call && f.account_id == to)
.and_then(|f| match &f.contract_info {
CachedContract::Cached(contract) => Some(contract.clone()),
_ => None,
});
let executable = self.push_frame(
FrameArgs::Call {
dest: to,
cached_info,
delegated_call: None,
},
value,
gas_limit,
deposit_limit,
)?;
self.run(executable, input_data)
};
// We need to make sure to reset `allows_reentry` even on failure.
let result = try_call();
// Protection is on a per call basis.
self.top_frame_mut().allows_reentry = true;
result
}
fn delegate_call(
&mut self,
code_hash: CodeHash<Self::T>,
input_data: Vec<u8>,
) -> Result<ExecReturnValue, ExecError> {
let executable = E::from_storage(code_hash, self.gas_meter_mut())?;
let top_frame = self.top_frame_mut();
let contract_info = top_frame.contract_info().clone();
let account_id = top_frame.account_id.clone();
let value = top_frame.value_transferred;
let executable = self.push_frame(
FrameArgs::Call {
dest: account_id,
cached_info: Some(contract_info),
delegated_call: Some(DelegatedCall {
executable,
caller: self.caller().clone(),
}),
},
value,
Weight::zero(),
BalanceOf::<T>::zero(),
)?;
self.run(executable, input_data)
}
fn instantiate(
&mut self,
gas_limit: Weight,
deposit_limit: BalanceOf<Self::T>,
code_hash: CodeHash<T>,
value: BalanceOf<T>,
input_data: Vec<u8>,
salt: &[u8],
) -> Result<(AccountIdOf<T>, ExecReturnValue), ExecError> {
let executable = E::from_storage(code_hash, self.gas_meter_mut())?;
let nonce = self.next_nonce();
let executable = self.push_frame(
FrameArgs::Instantiate {
sender: self.top_frame().account_id.clone(),
nonce,
executable,
salt,
input_data: input_data.as_ref(),
},
value,
gas_limit,
deposit_limit,
)?;
let account_id = self.top_frame().account_id.clone();
self.run(executable, input_data)
.map(|ret| (account_id, ret))
}
fn terminate(&mut self, beneficiary: &AccountIdOf<Self::T>) -> Result<(), DispatchError> {
use frame_support::traits::fungible::Inspect;
if self.is_recursive() {
return Err(Error::<T>::TerminatedWhileReentrant.into())
}
let frame = self.top_frame_mut();
let info = frame.terminate();
frame.nested_storage.terminate(&info);
System::<T>::dec_consumers(&frame.account_id);
T::Currency::transfer(
&frame.account_id,
beneficiary,
T::Currency::reducible_balance(&frame.account_id, Expendable, Polite),
ExistenceRequirement::AllowDeath,
)?;
info.queue_trie_for_deletion();
ContractInfoOf::<T>::remove(&frame.account_id);
E::decrement_refcount(info.code_hash);
Contracts::<T>::deposit_event(
vec![
T::Hashing::hash_of(&frame.account_id),
T::Hashing::hash_of(&beneficiary),
],
Event::Terminated {
contract: frame.account_id.clone(),
beneficiary: beneficiary.clone(),
},
);
Ok(())
}
fn transfer(&mut self, to: &T::AccountId, value: BalanceOf<T>) -> DispatchResult {
Self::transfer(
ExistenceRequirement::KeepAlive,
&self.top_frame().account_id,
to,
value,
)
}
fn get_storage(&mut self, key: &Key<T>) -> Option<Vec<u8>> {
self.top_frame_mut().contract_info().read(key)
}
fn get_storage_size(&mut self, key: &Key<T>) -> Option<u32> {
self.top_frame_mut().contract_info().size(key)
}
fn set_storage(
&mut self,
key: &Key<T>,
value: Option<Vec<u8>>,
take_old: bool,
) -> Result<WriteOutcome, DispatchError> {
let frame = self.top_frame_mut();
frame.contract_info.get(&frame.account_id).write(
key,
value,
Some(&mut frame.nested_storage),
take_old,
)
}
fn address(&self) -> &T::AccountId {
&self.top_frame().account_id
}
fn caller(&self) -> Origin<T> {
if let Some(caller) = &self.top_frame().delegate_caller {
caller.clone()
} else {
self.frames()
.nth(1)
.map(|f| Origin::from_account_id(f.account_id.clone()))
.unwrap_or(self.origin.clone())
}
}
fn is_contract(&self, address: &T::AccountId) -> bool {
ContractInfoOf::<T>::contains_key(address)
}
fn code_hash(&self, address: &T::AccountId) -> Option<CodeHash<Self::T>> {
<ContractInfoOf<T>>::get(address).map(|contract| contract.code_hash)
}
fn own_code_hash(&mut self) -> &CodeHash<Self::T> {
&self.top_frame_mut().contract_info().code_hash
}
fn caller_is_origin(&self) -> bool {
self.origin == self.caller()
}
fn caller_is_root(&self) -> bool {
// if the caller isn't origin, then it can't be root.
self.caller_is_origin() && self.origin == Origin::Root
}
fn balance(&self) -> BalanceOf<T> {
T::Currency::free_balance(&self.top_frame().account_id)
}
fn value_transferred(&self) -> BalanceOf<T> {
self.top_frame().value_transferred
}
fn random(&self, subject: &[u8]) -> (SeedOf<T>, BlockNumberFor<T>) {
T::Randomness::random(subject)
}
fn now(&self) -> &MomentOf<T> {
&self.timestamp
}
fn minimum_balance(&self) -> BalanceOf<T> {
T::Currency::minimum_balance()
}
fn deposit_event(&mut self, topics: Vec<T::Hash>, data: Vec<u8>) {
Contracts::<Self::T>::deposit_event(
topics,
Event::ContractEmitted {
contract: self.top_frame().account_id.clone(),
data,
},
);
}
fn block_number(&self) -> BlockNumberFor<T> {
self.block_number
}
fn max_value_size(&self) -> u32 {
self.schedule.limits.payload_len
}
fn get_weight_price(&self, weight: Weight) -> BalanceOf<Self::T> {
T::WeightPrice::convert(weight)
}
fn schedule(&self) -> &Schedule<Self::T> {
self.schedule
}
fn gas_meter(&self) -> &GasMeter<Self::T> {
&self.top_frame().nested_gas
}
fn gas_meter_mut(&mut self) -> &mut GasMeter<Self::T> {
&mut self.top_frame_mut().nested_gas
}
fn append_debug_buffer(&mut self, msg: &str) -> bool {
if let Some(buffer) = &mut self.debug_message {
buffer
.try_extend(&mut msg.bytes())
.map_err(|_| {
log::debug!(
target: LOG_TARGET,
"Debug buffer (of {} bytes) exhausted!",
DebugBufferVec::<T>::bound(),
)
})
.ok();
true
} else {
false
}
}
fn call_runtime(&self, call: <Self::T as Config>::RuntimeCall) -> DispatchResultWithPostInfo {
let mut origin: T::RuntimeOrigin = RawOrigin::Signed(self.address().clone()).into();
origin.add_filter(T::CallFilter::contains);
call.dispatch(origin)
}
fn ecdsa_recover(&self, signature: &[u8; 65], message_hash: &[u8; 32]) -> Result<[u8; 33], ()> {
secp256k1_ecdsa_recover_compressed(signature, message_hash).map_err(|_| ())
}
fn sr25519_verify(&self, signature: &[u8; 64], message: &[u8], pub_key: &[u8; 32]) -> bool {
sp_io::crypto::sr25519_verify(
&SR25519Signature(*signature),
message,
&SR25519Public(*pub_key),
)
}
fn ecdsa_to_eth_address(&self, pk: &[u8; 33]) -> Result<[u8; 20], ()> {
ECDSAPublic(*pk).to_eth_address()
}
#[cfg(test)]
fn contract_info(&mut self) -> &mut ContractInfo<Self::T> {
self.top_frame_mut().contract_info()
}
fn set_code_hash(&mut self, hash: CodeHash<Self::T>) -> Result<(), DispatchError> {
let frame = top_frame_mut!(self);
if !E::from_storage(hash, &mut frame.nested_gas)?.is_deterministic() {
return Err(<Error<T>>::Indeterministic.into())
}
E::increment_refcount(hash)?;
let prev_hash = frame.contract_info().code_hash;
E::decrement_refcount(prev_hash);
frame.contract_info().code_hash = hash;
Contracts::<Self::T>::deposit_event(
vec![T::Hashing::hash_of(&frame.account_id), hash, prev_hash],
Event::ContractCodeUpdated {
contract: frame.account_id.clone(),
new_code_hash: hash,
old_code_hash: prev_hash,
},
);
Ok(())
}
fn reentrance_count(&self) -> u32 {
let id: &AccountIdOf<Self::T> = &self.top_frame().account_id;
self.account_reentrance_count(id).saturating_sub(1)
}
fn account_reentrance_count(&self, account_id: &AccountIdOf<Self::T>) -> u32 {
self.frames()
.filter(|f| f.delegate_caller.is_none() && &f.account_id == account_id)
.count() as u32
}
fn nonce(&mut self) -> u64 {
if let Some(current) = self.nonce {
current
} else {
let current = <Nonce<T>>::get();
self.nonce = Some(current);
current
}
}
}
mod sealing {
use super::*;
pub trait Sealed {}
impl<'a, T: Config, E> Sealed for Stack<'a, T, E> {}
#[cfg(test)]
impl Sealed for crate::wasm::MockExt {}
#[cfg(test)]
impl Sealed for &mut crate::wasm::MockExt {}
}
/// These tests exercise the executive layer.
///
/// In these tests the VM/loader are mocked. Instead of dealing with wasm bytecode they use simple
/// closures. This allows you to tackle executive logic more thoroughly without writing a
/// wasm VM code.
#[cfg(test)]
mod tests {
use super::*;
use crate::{
exec::ExportedFunction::*,
gas::GasMeter,
tests::{
test_utils::{get_balance, hash, place_contract, set_balance},
ExtBuilder, RuntimeCall, RuntimeEvent as MetaEvent, Test, TestFilter, ALICE, BOB,
CHARLIE, GAS_LIMIT,
},
Error,
};
use assert_matches::assert_matches;
use codec::{Decode, Encode};
use frame_support::{assert_err, assert_ok, parameter_types};
use frame_system::{EventRecord, Phase};
use pallet_contracts_primitives::ReturnFlags;
use pretty_assertions::assert_eq;
use sp_runtime::{traits::Hash, DispatchError};
use std::{
cell::RefCell,
collections::hash_map::{Entry, HashMap},
rc::Rc,
};
type System = frame_system::Pallet<Test>;
type MockStack<'a> = Stack<'a, Test, MockExecutable>;
parameter_types! {
static Loader: MockLoader = MockLoader::default();
}
fn events() -> Vec<Event<Test>> {
System::events()
.into_iter()
.filter_map(|meta| match meta.event {
MetaEvent::Contracts(contract_event) => Some(contract_event),
_ => None,
})
.collect()
}
struct MockCtx<'a> {
ext: &'a mut dyn Ext<T = Test>,
input_data: Vec<u8>,
}
#[derive(Clone)]
struct MockExecutable {
func: Rc<dyn Fn(MockCtx, &Self) -> ExecResult + 'static>,
func_type: ExportedFunction,
code_hash: CodeHash<Test>,
refcount: u64,
}
#[derive(Default, Clone)]
pub struct MockLoader {
map: HashMap<CodeHash<Test>, MockExecutable>,
counter: u64,
}
impl MockLoader {
fn insert(
func_type: ExportedFunction,
f: impl Fn(MockCtx, &MockExecutable) -> ExecResult + 'static,
) -> CodeHash<Test> {
Loader::mutate(|loader| {
// Generate code hashes as monotonically increasing values.
let hash = <Test as frame_system::Config>::Hash::from_low_u64_be(loader.counter);
loader.counter += 1;
loader.map.insert(
hash,
MockExecutable {
func: Rc::new(f),
func_type,
code_hash: hash,
refcount: 1,
},
);
hash
})
}
fn increment_refcount(code_hash: CodeHash<Test>) -> Result<(), DispatchError> {
Loader::mutate(|loader| {
match loader.map.entry(code_hash) {
Entry::Vacant(_) => Err(<Error<Test>>::CodeNotFound)?,
Entry::Occupied(mut entry) => entry.get_mut().refcount += 1,
}
Ok(())
})
}
fn decrement_refcount(code_hash: CodeHash<Test>) {
use std::collections::hash_map::Entry::Occupied;
Loader::mutate(|loader| {
let mut entry = match loader.map.entry(code_hash) {
Occupied(e) => e,
_ => panic!("code_hash does not exist"),
};
let refcount = &mut entry.get_mut().refcount;
*refcount -= 1;
if *refcount == 0 {
entry.remove();
}
});
}
}
impl Executable<Test> for MockExecutable {
fn from_storage(
code_hash: CodeHash<Test>,
_gas_meter: &mut GasMeter<Test>,
) -> Result<Self, DispatchError> {
Loader::mutate(|loader| {
loader
.map
.get(&code_hash)
.cloned()
.ok_or(Error::<Test>::CodeNotFound.into())
})
}
fn increment_refcount(code_hash: CodeHash<Test>) -> Result<(), DispatchError> {
MockLoader::increment_refcount(code_hash)
}
fn decrement_refcount(code_hash: CodeHash<Test>) {
MockLoader::decrement_refcount(code_hash);
}
fn execute<E: Ext<T = Test>>(
self,
ext: &mut E,
function: &ExportedFunction,
input_data: Vec<u8>,
) -> ExecResult {
if let &Constructor = function {
Self::increment_refcount(self.code_hash).unwrap();
}
if function == &self.func_type {
(self.func)(MockCtx { ext, input_data }, &self)
} else {
exec_success()
}
}
fn code_hash(&self) -> &CodeHash<Test> {
&self.code_hash
}
fn code_len(&self) -> u32 {
0
}
fn is_deterministic(&self) -> bool {
true
}
}
fn exec_success() -> ExecResult {
Ok(ExecReturnValue {
flags: ReturnFlags::empty(),
data: Vec::new(),
})
}
fn exec_trapped() -> ExecResult {
Err(ExecError {
error: <Error<Test>>::ContractTrapped.into(),
origin: ErrorOrigin::Callee,
})
}
#[test]
fn it_works() {
parameter_types! {
static TestData: Vec<usize> = vec![0];
}
let value = Default::default();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
let exec_ch = MockLoader::insert(Call, |_ctx, _executable| {
TestData::mutate(|data| data.push(1));
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&BOB, exec_ch);
let mut storage_meter =
storage::meter::Meter::new(&Origin::from_account_id(ALICE), Some(0), value)
.unwrap();
assert_matches!(
MockStack::run_call(
Origin::from_account_id(ALICE),
BOB,
&mut gas_meter,
&mut storage_meter,
&schedule,
value,
vec![],
None,
Determinism::Enforced,
),
Ok(_)
);
});
assert_eq!(TestData::get(), vec![0, 1]);
}
#[test]
fn transfer_works() {
// This test verifies that a contract is able to transfer
// some funds to another account.
let origin = ALICE;
let dest = BOB;
ExtBuilder::default().build().execute_with(|| {
set_balance(&origin, 100);
set_balance(&dest, 0);
MockStack::transfer(ExistenceRequirement::KeepAlive, &origin, &dest, 55).unwrap();
assert_eq!(get_balance(&origin), 45);
assert_eq!(get_balance(&dest), 55);
});
}
#[test]
fn correct_transfer_on_call() {
let origin = ALICE;
let dest = BOB;
let value = 55;
let success_ch = MockLoader::insert(Call, move |ctx, _| {
assert_eq!(ctx.ext.value_transferred(), value);
Ok(ExecReturnValue {
flags: ReturnFlags::empty(),
data: Vec::new(),
})
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&dest, success_ch);
set_balance(&origin, 100);
let balance = get_balance(&dest);
let contract_origin = Origin::from_account_id(origin.clone());
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), value).unwrap();
let _ = MockStack::run_call(
contract_origin.clone(),
dest.clone(),
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
value,
vec![],
None,
Determinism::Enforced,
)
.unwrap();
assert_eq!(get_balance(&origin), 100 - value);
assert_eq!(get_balance(&dest), balance + value);
});
}
#[test]
fn correct_transfer_on_delegate_call() {
let origin = ALICE;
let dest = BOB;
let value = 35;
let success_ch = MockLoader::insert(Call, move |ctx, _| {
assert_eq!(ctx.ext.value_transferred(), value);
Ok(ExecReturnValue {
flags: ReturnFlags::empty(),
data: Vec::new(),
})
});
let delegate_ch = MockLoader::insert(Call, move |ctx, _| {
assert_eq!(ctx.ext.value_transferred(), value);
let _ = ctx.ext.delegate_call(success_ch, Vec::new())?;
Ok(ExecReturnValue {
flags: ReturnFlags::empty(),
data: Vec::new(),
})
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&dest, delegate_ch);
set_balance(&origin, 100);
let balance = get_balance(&dest);
let contract_origin = Origin::from_account_id(origin.clone());
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 55).unwrap();
let _ = MockStack::run_call(
contract_origin.clone(),
dest.clone(),
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
value,
vec![],
None,
Determinism::Enforced,
)
.unwrap();
assert_eq!(get_balance(&origin), 100 - value);
assert_eq!(get_balance(&dest), balance + value);
});
}
#[test]
fn changes_are_reverted_on_failing_call() {
// This test verifies that changes are reverted on a call which fails (or equally, returns
// a non-zero status code).
let origin = ALICE;
let dest = BOB;
let return_ch = MockLoader::insert(Call, |_, _| {
Ok(ExecReturnValue {
flags: ReturnFlags::REVERT,
data: Vec::new(),
})
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&dest, return_ch);
set_balance(&origin, 100);
let balance = get_balance(&dest);
let contract_origin = Origin::from_account_id(origin.clone());
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 55).unwrap();
let output = MockStack::run_call(
contract_origin.clone(),
dest.clone(),
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
55,
vec![],
None,
Determinism::Enforced,
)
.unwrap();
assert!(output.did_revert());
assert_eq!(get_balance(&origin), 100);
assert_eq!(get_balance(&dest), balance);
});
}
#[test]
fn balance_too_low() {
// This test verifies that a contract can't send value if it's
// balance is too low.
let origin = ALICE;
let dest = BOB;
ExtBuilder::default().build().execute_with(|| {
set_balance(&origin, 0);
let result = MockStack::transfer(ExistenceRequirement::KeepAlive, &origin, &dest, 100);
assert_eq!(result, Err(Error::<Test>::TransferFailed.into()));
assert_eq!(get_balance(&origin), 0);
assert_eq!(get_balance(&dest), 0);
});
}
#[test]
fn output_is_returned_on_success() {
// Verifies that if a contract returns data with a successful exit status, this data
// is returned from the execution context.
let origin = ALICE;
let dest = BOB;
let return_ch = MockLoader::insert(Call, |_, _| {
Ok(ExecReturnValue {
flags: ReturnFlags::empty(),
data: vec![1, 2, 3, 4],
})
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
let contract_origin = Origin::from_account_id(origin);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
place_contract(&BOB, return_ch);
let result = MockStack::run_call(
contract_origin,
dest,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
vec![],
None,
Determinism::Enforced,
);
let output = result.unwrap();
assert!(!output.did_revert());
assert_eq!(output.data, vec![1, 2, 3, 4]);
});
}
#[test]
fn output_is_returned_on_failure() {
// Verifies that if a contract returns data with a failing exit status, this data
// is returned from the execution context.
let origin = ALICE;
let dest = BOB;
let return_ch = MockLoader::insert(Call, |_, _| {
Ok(ExecReturnValue {
flags: ReturnFlags::REVERT,
data: vec![1, 2, 3, 4],
})
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&BOB, return_ch);
let contract_origin = Origin::from_account_id(origin);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
let result = MockStack::run_call(
contract_origin,
dest,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
vec![],
None,
Determinism::Enforced,
);
let output = result.unwrap();
assert!(output.did_revert());
assert_eq!(output.data, vec![1, 2, 3, 4]);
});
}
#[test]
fn input_data_to_call() {
let input_data_ch = MockLoader::insert(Call, |ctx, _| {
assert_eq!(ctx.input_data, &[1, 2, 3, 4]);
exec_success()
});
// This one tests passing the input data into a contract via call.
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&BOB, input_data_ch);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
let result = MockStack::run_call(
contract_origin,
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
vec![1, 2, 3, 4],
None,
Determinism::Enforced,
);
assert_matches!(result, Ok(_));
});
}
#[test]
fn input_data_to_instantiate() {
let input_data_ch = MockLoader::insert(Constructor, |ctx, _| {
assert_eq!(ctx.input_data, &[1, 2, 3, 4]);
exec_success()
});
// This one tests passing the input data into a contract via instantiate.
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
let min_balance = <Test as Config>::Currency::minimum_balance();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
let executable = MockExecutable::from_storage(input_data_ch, &mut gas_meter).unwrap();
set_balance(&ALICE, min_balance * 10_000);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, None, min_balance).unwrap();
let result = MockStack::run_instantiate(
ALICE,
executable,
&mut gas_meter,
&mut storage_meter,
&schedule,
min_balance,
vec![1, 2, 3, 4],
&[],
None,
);
assert_matches!(result, Ok(_));
});
}
#[test]
fn max_depth() {
// This test verifies that when we reach the maximal depth creation of an
// yet another context fails.
parameter_types! {
static ReachedBottom: bool = false;
}
let value = Default::default();
let recurse_ch = MockLoader::insert(Call, |ctx, _| {
// Try to call into yourself.
let r = ctx.ext.call(
Weight::zero(),
BalanceOf::<Test>::zero(),
BOB,
0,
vec![],
true,
);
ReachedBottom::mutate(|reached_bottom| {
if !*reached_bottom {
// We are first time here, it means we just reached bottom.
// Verify that we've got proper error and set `reached_bottom`.
assert_eq!(r, Err(Error::<Test>::MaxCallDepthReached.into()));
*reached_bottom = true;
} else {
// We just unwinding stack here.
assert_matches!(r, Ok(_));
}
});
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
set_balance(&BOB, 1);
place_contract(&BOB, recurse_ch);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), value).unwrap();
let result = MockStack::run_call(
contract_origin,
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
value,
vec![],
None,
Determinism::Enforced,
);
assert_matches!(result, Ok(_));
});
}
#[test]
fn caller_returns_proper_values() {
let origin = ALICE;
let dest = BOB;
parameter_types! {
static WitnessedCallerBob: Option<AccountIdOf<Test>> = None;
static WitnessedCallerCharlie: Option<AccountIdOf<Test>> = None;
}
let bob_ch = MockLoader::insert(Call, |ctx, _| {
// Record the caller for bob.
WitnessedCallerBob::mutate(|caller| {
*caller = Some(ctx.ext.caller().account_id().unwrap().clone())
});
// Call into CHARLIE contract.
assert_matches!(
ctx.ext.call(
Weight::zero(),
BalanceOf::<Test>::zero(),
CHARLIE,
0,
vec![],
true
),
Ok(_)
);
exec_success()
});
let charlie_ch = MockLoader::insert(Call, |ctx, _| {
// Record the caller for charlie.
WitnessedCallerCharlie::mutate(|caller| {
*caller = Some(ctx.ext.caller().account_id().unwrap().clone())
});
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&dest, bob_ch);
place_contract(&CHARLIE, charlie_ch);
let contract_origin = Origin::from_account_id(origin.clone());
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
let result = MockStack::run_call(
contract_origin.clone(),
dest.clone(),
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
vec![],
None,
Determinism::Enforced,
);
assert_matches!(result, Ok(_));
});
assert_eq!(WitnessedCallerBob::get(), Some(origin));
assert_eq!(WitnessedCallerCharlie::get(), Some(dest));
}
#[test]
fn is_contract_returns_proper_values() {
let bob_ch = MockLoader::insert(Call, |ctx, _| {
// Verify that BOB is a contract
assert!(ctx.ext.is_contract(&BOB));
// Verify that ALICE is not a contract
assert!(!ctx.ext.is_contract(&ALICE));
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&BOB, bob_ch);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
let result = MockStack::run_call(
contract_origin,
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
vec![],
None,
Determinism::Enforced,
);
assert_matches!(result, Ok(_));
});
}
#[test]
fn code_hash_returns_proper_values() {
let code_bob = MockLoader::insert(Call, |ctx, _| {
// ALICE is not a contract and hence they do not have a code_hash
assert!(ctx.ext.code_hash(&ALICE).is_none());
// BOB is a contract and hence it has a code_hash
assert!(ctx.ext.code_hash(&BOB).is_some());
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&BOB, code_bob);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
// ALICE (not contract) -> BOB (contract)
let result = MockStack::run_call(
contract_origin,
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
vec![0],
None,
Determinism::Enforced,
);
assert_matches!(result, Ok(_));
});
}
#[test]
fn own_code_hash_returns_proper_values() {
let bob_ch = MockLoader::insert(Call, |ctx, _| {
let code_hash = ctx.ext.code_hash(&BOB).unwrap();
assert_eq!(*ctx.ext.own_code_hash(), code_hash);
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&BOB, bob_ch);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
// ALICE (not contract) -> BOB (contract)
let result = MockStack::run_call(
contract_origin,
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
vec![0],
None,
Determinism::Enforced,
);
assert_matches!(result, Ok(_));
});
}
#[test]
fn caller_is_origin_returns_proper_values() {
let code_charlie = MockLoader::insert(Call, |ctx, _| {
// BOB is not the origin of the stack call
assert!(!ctx.ext.caller_is_origin());
exec_success()
});
let code_bob = MockLoader::insert(Call, |ctx, _| {
// ALICE is the origin of the call stack
assert!(ctx.ext.caller_is_origin());
// BOB calls CHARLIE
ctx.ext.call(
Weight::zero(),
BalanceOf::<Test>::zero(),
CHARLIE,
0,
vec![],
true,
)
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&BOB, code_bob);
place_contract(&CHARLIE, code_charlie);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
// ALICE -> BOB (caller is origin) -> CHARLIE (caller is not origin)
let result = MockStack::run_call(
contract_origin,
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
vec![0],
None,
Determinism::Enforced,
);
assert_matches!(result, Ok(_));
});
}
#[test]
fn root_caller_succeeds() {
let code_bob = MockLoader::insert(Call, |ctx, _| {
// root is the origin of the call stack.
assert!(ctx.ext.caller_is_root());
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&BOB, code_bob);
let contract_origin = Origin::Root;
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
// root -> BOB (caller is root)
let result = MockStack::run_call(
contract_origin,
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
vec![0],
None,
Determinism::Enforced,
);
assert_matches!(result, Ok(_));
});
}
#[test]
fn root_caller_does_not_succeed_when_value_not_zero() {
let code_bob = MockLoader::insert(Call, |ctx, _| {
// root is the origin of the call stack.
assert!(ctx.ext.caller_is_root());
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&BOB, code_bob);
let contract_origin = Origin::Root;
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
// root -> BOB (caller is root)
let result = MockStack::run_call(
contract_origin,
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
1,
vec![0],
None,
Determinism::Enforced,
);
assert_matches!(result, Err(_));
});
}
#[test]
fn root_caller_succeeds_with_consecutive_calls() {
let code_charlie = MockLoader::insert(Call, |ctx, _| {
// BOB is not root, even though the origin is root.
assert!(!ctx.ext.caller_is_root());
exec_success()
});
let code_bob = MockLoader::insert(Call, |ctx, _| {
// root is the origin of the call stack.
assert!(ctx.ext.caller_is_root());
// BOB calls CHARLIE.
ctx.ext.call(
Weight::zero(),
BalanceOf::<Test>::zero(),
CHARLIE,
0,
vec![],
true,
)
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&BOB, code_bob);
place_contract(&CHARLIE, code_charlie);
let contract_origin = Origin::Root;
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
// root -> BOB (caller is root) -> CHARLIE (caller is not root)
let result = MockStack::run_call(
contract_origin,
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
vec![0],
None,
Determinism::Enforced,
);
assert_matches!(result, Ok(_));
});
}
#[test]
fn address_returns_proper_values() {
let bob_ch = MockLoader::insert(Call, |ctx, _| {
// Verify that address matches BOB.
assert_eq!(*ctx.ext.address(), BOB);
// Call into charlie contract.
assert_matches!(
ctx.ext.call(
Weight::zero(),
BalanceOf::<Test>::zero(),
CHARLIE,
0,
vec![],
true
),
Ok(_)
);
exec_success()
});
let charlie_ch = MockLoader::insert(Call, |ctx, _| {
assert_eq!(*ctx.ext.address(), CHARLIE);
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&BOB, bob_ch);
place_contract(&CHARLIE, charlie_ch);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
let result = MockStack::run_call(
contract_origin,
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
vec![],
None,
Determinism::Enforced,
);
assert_matches!(result, Ok(_));
});
}
#[test]
fn refuse_instantiate_with_value_below_existential_deposit() {
let dummy_ch = MockLoader::insert(Constructor, |_, _| exec_success());
ExtBuilder::default()
.existential_deposit(15)
.build()
.execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
let executable = MockExecutable::from_storage(dummy_ch, &mut gas_meter).unwrap();
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
assert_matches!(
MockStack::run_instantiate(
ALICE,
executable,
&mut gas_meter,
&mut storage_meter,
&schedule,
0, // <- zero value
vec![],
&[],
None,
),
Err(_)
);
});
}
#[test]
fn instantiation_work_with_success_output() {
let dummy_ch = MockLoader::insert(Constructor, |_, _| {
Ok(ExecReturnValue {
flags: ReturnFlags::empty(),
data: vec![80, 65, 83, 83],
})
});
ExtBuilder::default()
.existential_deposit(15)
.build()
.execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
let min_balance = <Test as Config>::Currency::minimum_balance();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
let executable = MockExecutable::from_storage(dummy_ch, &mut gas_meter).unwrap();
set_balance(&ALICE, min_balance * 1000);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter = storage::meter::Meter::new(
&contract_origin,
Some(min_balance * 100),
min_balance,
)
.unwrap();
let instantiated_contract_address = assert_matches!(
MockStack::run_instantiate(
ALICE,
executable,
&mut gas_meter,
&mut storage_meter,
&schedule,
min_balance,
vec![],
&[],
None,
),
Ok((address, ref output)) if output.data == vec![80, 65, 83, 83] => address
);
// Check that the newly created account has the expected code hash and
// there are instantiation event.
assert_eq!(
ContractInfo::<Test>::load_code_hash(&instantiated_contract_address).unwrap(),
dummy_ch
);
assert_eq!(
&events(),
&[Event::Instantiated {
deployer: ALICE,
contract: instantiated_contract_address
}]
);
});
}
#[test]
fn instantiation_fails_with_failing_output() {
let dummy_ch = MockLoader::insert(Constructor, |_, _| {
Ok(ExecReturnValue {
flags: ReturnFlags::REVERT,
data: vec![70, 65, 73, 76],
})
});
ExtBuilder::default()
.existential_deposit(15)
.build()
.execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
let min_balance = <Test as Config>::Currency::minimum_balance();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
let executable = MockExecutable::from_storage(dummy_ch, &mut gas_meter).unwrap();
set_balance(&ALICE, min_balance * 1000);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter = storage::meter::Meter::new(
&contract_origin,
Some(min_balance * 100),
min_balance,
)
.unwrap();
let instantiated_contract_address = assert_matches!(
MockStack::run_instantiate(
ALICE,
executable,
&mut gas_meter,
&mut storage_meter,
&schedule,
min_balance,
vec![],
&[],
None,
),
Ok((address, ref output)) if output.data == vec![70, 65, 73, 76] => address
);
// Check that the account has not been created.
assert!(
ContractInfo::<Test>::load_code_hash(&instantiated_contract_address).is_none()
);
assert!(events().is_empty());
});
}
#[test]
fn instantiation_from_contract() {
let dummy_ch = MockLoader::insert(Call, |_, _| exec_success());
let instantiated_contract_address = Rc::new(RefCell::new(None::<AccountIdOf<Test>>));
let instantiator_ch = MockLoader::insert(Call, {
let instantiated_contract_address = Rc::clone(&instantiated_contract_address);
move |ctx, _| {
// Instantiate a contract and save it's address in `instantiated_contract_address`.
let (address, output) = ctx
.ext
.instantiate(
Weight::zero(),
BalanceOf::<Test>::zero(),
dummy_ch,
<Test as Config>::Currency::minimum_balance(),
vec![],
&[48, 49, 50],
)
.unwrap();
*instantiated_contract_address.borrow_mut() = address.into();
Ok(output)
}
});
ExtBuilder::default()
.existential_deposit(15)
.build()
.execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
let min_balance = <Test as Config>::Currency::minimum_balance();
set_balance(&ALICE, min_balance * 100);
place_contract(&BOB, instantiator_ch);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter = storage::meter::Meter::new(
&contract_origin,
Some(min_balance * 10),
min_balance * 10,
)
.unwrap();
assert_matches!(
MockStack::run_call(
contract_origin,
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
min_balance * 10,
vec![],
None,
Determinism::Enforced,
),
Ok(_)
);
let instantiated_contract_address = instantiated_contract_address
.borrow()
.as_ref()
.unwrap()
.clone();
// Check that the newly created account has the expected code hash and
// there are instantiation event.
assert_eq!(
ContractInfo::<Test>::load_code_hash(&instantiated_contract_address).unwrap(),
dummy_ch
);
assert_eq!(
&events(),
&[
Event::Instantiated {
deployer: BOB,
contract: instantiated_contract_address
},
Event::Called {
caller: Origin::from_account_id(ALICE),
contract: BOB
},
]
);
});
}
#[test]
fn instantiation_traps() {
let dummy_ch = MockLoader::insert(Constructor, |_, _| Err("It's a trap!".into()));
let instantiator_ch = MockLoader::insert(Call, {
move |ctx, _| {
// Instantiate a contract and save it's address in `instantiated_contract_address`.
assert_matches!(
ctx.ext.instantiate(
Weight::zero(),
BalanceOf::<Test>::zero(),
dummy_ch,
<Test as Config>::Currency::minimum_balance(),
vec![],
&[],
),
Err(ExecError {
error: DispatchError::Other("It's a trap!"),
origin: ErrorOrigin::Callee,
})
);
exec_success()
}
});
ExtBuilder::default()
.existential_deposit(15)
.build()
.execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
set_balance(&ALICE, 1000);
set_balance(&BOB, 100);
place_contract(&BOB, instantiator_ch);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(200), 0).unwrap();
assert_matches!(
MockStack::run_call(
contract_origin,
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
vec![],
None,
Determinism::Enforced,
),
Ok(_)
);
// The contract wasn't instantiated so we don't expect to see an instantiation
// event here.
assert_eq!(
&events(),
&[Event::Called {
caller: Origin::from_account_id(ALICE),
contract: BOB
},]
);
});
}
#[test]
fn termination_from_instantiate_fails() {
let terminate_ch = MockLoader::insert(Constructor, |ctx, _| {
ctx.ext.terminate(&ALICE).unwrap();
exec_success()
});
ExtBuilder::default()
.existential_deposit(15)
.build()
.execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
let executable =
MockExecutable::from_storage(terminate_ch, &mut gas_meter).unwrap();
set_balance(&ALICE, 10_000);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, None, 100).unwrap();
assert_eq!(
MockStack::run_instantiate(
ALICE,
executable,
&mut gas_meter,
&mut storage_meter,
&schedule,
100,
vec![],
&[],
None,
),
Err(Error::<Test>::TerminatedInConstructor.into())
);
assert_eq!(&events(), &[]);
});
}
#[test]
fn in_memory_changes_not_discarded() {
// Call stack: BOB -> CHARLIE (trap) -> BOB' (success)
// This tests verifies some edge case of the contract info cache:
// We change some value in our contract info before calling into a contract
// that calls into ourself. This triggers a case where BOBs contract info
// is written to storage and invalidated by the successful execution of BOB'.
// The trap of CHARLIE reverts the storage changes to BOB. When the root BOB regains
// control it reloads its contract info from storage. We check that changes that
// are made before calling into CHARLIE are not discarded.
let code_bob = MockLoader::insert(Call, |ctx, _| {
if ctx.input_data[0] == 0 {
let info = ctx.ext.contract_info();
assert_eq!(info.storage_byte_deposit, 0);
info.storage_byte_deposit = 42;
assert_eq!(
ctx.ext.call(
Weight::zero(),
BalanceOf::<Test>::zero(),
CHARLIE,
0,
vec![],
true
),
exec_trapped()
);
assert_eq!(ctx.ext.contract_info().storage_byte_deposit, 42);
}
exec_success()
});
let code_charlie = MockLoader::insert(Call, |ctx, _| {
assert!(ctx
.ext
.call(
Weight::zero(),
BalanceOf::<Test>::zero(),
BOB,
0,
vec![99],
true
)
.is_ok());
exec_trapped()
});
// This one tests passing the input data into a contract via call.
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&BOB, code_bob);
place_contract(&CHARLIE, code_charlie);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
let result = MockStack::run_call(
contract_origin,
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
vec![0],
None,
Determinism::Enforced,
);
assert_matches!(result, Ok(_));
});
}
#[test]
fn recursive_call_during_constructor_fails() {
let code = MockLoader::insert(Constructor, |ctx, _| {
assert_matches!(
ctx.ext.call(Weight::zero(), BalanceOf::<Test>::zero(), ctx.ext.address().clone(), 0, vec![], true),
Err(ExecError{error, ..}) if error == <Error<Test>>::ContractNotFound.into()
);
exec_success()
});
// This one tests passing the input data into a contract via instantiate.
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
let min_balance = <Test as Config>::Currency::minimum_balance();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
let executable = MockExecutable::from_storage(code, &mut gas_meter).unwrap();
set_balance(&ALICE, min_balance * 10_000);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, None, min_balance).unwrap();
let result = MockStack::run_instantiate(
ALICE,
executable,
&mut gas_meter,
&mut storage_meter,
&schedule,
min_balance,
vec![],
&[],
None,
);
assert_matches!(result, Ok(_));
});
}
#[test]
fn printing_works() {
let code_hash = MockLoader::insert(Call, |ctx, _| {
ctx.ext.append_debug_buffer("This is a test");
ctx.ext.append_debug_buffer("More text");
exec_success()
});
let mut debug_buffer = DebugBufferVec::<Test>::try_from(Vec::new()).unwrap();
ExtBuilder::default().build().execute_with(|| {
let min_balance = <Test as Config>::Currency::minimum_balance();
let schedule = <Test as Config>::Schedule::get();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
set_balance(&ALICE, min_balance * 10);
place_contract(&BOB, code_hash);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
MockStack::run_call(
contract_origin,
BOB,
&mut gas_meter,
&mut storage_meter,
&schedule,
0,
vec![],
Some(&mut debug_buffer),
Determinism::Enforced,
)
.unwrap();
});
assert_eq!(
&String::from_utf8(debug_buffer.to_vec()).unwrap(),
"This is a testMore text"
);
}
#[test]
fn printing_works_on_fail() {
let code_hash = MockLoader::insert(Call, |ctx, _| {
ctx.ext.append_debug_buffer("This is a test");
ctx.ext.append_debug_buffer("More text");
exec_trapped()
});
let mut debug_buffer = DebugBufferVec::<Test>::try_from(Vec::new()).unwrap();
ExtBuilder::default().build().execute_with(|| {
let min_balance = <Test as Config>::Currency::minimum_balance();
let schedule = <Test as Config>::Schedule::get();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
set_balance(&ALICE, min_balance * 10);
place_contract(&BOB, code_hash);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
let result = MockStack::run_call(
contract_origin,
BOB,
&mut gas_meter,
&mut storage_meter,
&schedule,
0,
vec![],
Some(&mut debug_buffer),
Determinism::Enforced,
);
assert!(result.is_err());
});
assert_eq!(
&String::from_utf8(debug_buffer.to_vec()).unwrap(),
"This is a testMore text"
);
}
#[test]
fn debug_buffer_is_limited() {
let code_hash = MockLoader::insert(Call, move |ctx, _| {
ctx.ext.append_debug_buffer("overflowing bytes");
exec_success()
});
// Pre-fill the buffer almost up to its limit, leaving not enough space to the message
let debug_buf_before =
DebugBufferVec::<Test>::try_from(vec![0u8; DebugBufferVec::<Test>::bound() - 5])
.unwrap();
let mut debug_buf_after = debug_buf_before.clone();
ExtBuilder::default().build().execute_with(|| {
let schedule: Schedule<Test> = <Test as Config>::Schedule::get();
let min_balance = <Test as Config>::Currency::minimum_balance();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
set_balance(&ALICE, min_balance * 10);
place_contract(&BOB, code_hash);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
MockStack::run_call(
contract_origin,
BOB,
&mut gas_meter,
&mut storage_meter,
&schedule,
0,
vec![],
Some(&mut debug_buf_after),
Determinism::Enforced,
)
.unwrap();
assert_eq!(debug_buf_before, debug_buf_after);
});
}
#[test]
fn call_reentry_direct_recursion() {
// call the contract passed as input with disabled reentry
let code_bob = MockLoader::insert(Call, |ctx, _| {
let dest = Decode::decode(&mut ctx.input_data.as_ref()).unwrap();
ctx.ext.call(
Weight::zero(),
BalanceOf::<Test>::zero(),
dest,
0,
vec![],
false,
)
});
let code_charlie = MockLoader::insert(Call, |_, _| exec_success());
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&BOB, code_bob);
place_contract(&CHARLIE, code_charlie);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
// Calling another contract should succeed
assert_ok!(MockStack::run_call(
contract_origin.clone(),
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
CHARLIE.encode(),
None,
Determinism::Enforced
));
// Calling into oneself fails
assert_err!(
MockStack::run_call(
contract_origin,
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
BOB.encode(),
None,
Determinism::Enforced
)
.map_err(|e| e.error),
<Error<Test>>::ReentranceDenied,
);
});
}
#[test]
fn call_deny_reentry() {
let code_bob = MockLoader::insert(Call, |ctx, _| {
if ctx.input_data[0] == 0 {
ctx.ext.call(
Weight::zero(),
BalanceOf::<Test>::zero(),
CHARLIE,
0,
vec![],
false,
)
} else {
exec_success()
}
});
// call BOB with input set to '1'
let code_charlie = MockLoader::insert(Call, |ctx, _| {
ctx.ext.call(
Weight::zero(),
BalanceOf::<Test>::zero(),
BOB,
0,
vec![1],
true,
)
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&BOB, code_bob);
place_contract(&CHARLIE, code_charlie);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
// BOB -> CHARLIE -> BOB fails as BOB denies reentry.
assert_err!(
MockStack::run_call(
contract_origin,
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
vec![0],
None,
Determinism::Enforced
)
.map_err(|e| e.error),
<Error<Test>>::ReentranceDenied,
);
});
}
#[test]
fn call_runtime_works() {
let code_hash = MockLoader::insert(Call, |ctx, _| {
let call = RuntimeCall::System(frame_system::Call::remark_with_event {
remark: b"Hello World".to_vec(),
});
ctx.ext.call_runtime(call).unwrap();
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let min_balance = <Test as Config>::Currency::minimum_balance();
let schedule = <Test as Config>::Schedule::get();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
set_balance(&ALICE, min_balance * 10);
place_contract(&BOB, code_hash);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
System::reset_events();
MockStack::run_call(
contract_origin,
BOB,
&mut gas_meter,
&mut storage_meter,
&schedule,
0,
vec![],
None,
Determinism::Enforced,
)
.unwrap();
let remark_hash = <Test as frame_system::Config>::Hashing::hash(b"Hello World");
assert_eq!(
System::events(),
vec![
EventRecord {
phase: Phase::Initialization,
event: MetaEvent::System(frame_system::Event::Remarked {
sender: BOB,
hash: remark_hash
}),
topics: vec![],
},
EventRecord {
phase: Phase::Initialization,
event: MetaEvent::Contracts(crate::Event::Called {
caller: Origin::from_account_id(ALICE),
contract: BOB,
}),
topics: vec![hash(&Origin::<Test>::from_account_id(ALICE)), hash(&BOB)],
},
]
);
});
}
#[test]
fn call_runtime_filter() {
let code_hash = MockLoader::insert(Call, |ctx, _| {
use frame_system::Call as SysCall;
use pallet_balances::Call as BalanceCall;
use pallet_utility::Call as UtilCall;
// remark should still be allowed
let allowed_call = RuntimeCall::System(SysCall::remark_with_event {
remark: b"Hello".to_vec(),
});
// transfers are disallowed by the `TestFiler` (see below)
let forbidden_call = RuntimeCall::Balances(BalanceCall::transfer_allow_death {
dest: CHARLIE,
value: 22,
});
// simple cases: direct call
assert_err!(
ctx.ext.call_runtime(forbidden_call.clone()),
frame_system::Error::<Test>::CallFiltered
);
// as part of a patch: return is OK (but it interrupted the batch)
assert_ok!(ctx.ext.call_runtime(RuntimeCall::Utility(UtilCall::batch {
calls: vec![allowed_call.clone(), forbidden_call, allowed_call]
})),);
// the transfer wasn't performed
assert_eq!(get_balance(&CHARLIE), 0);
exec_success()
});
TestFilter::set_filter(|call| match call {
RuntimeCall::Balances(pallet_balances::Call::transfer_allow_death { .. }) => false,
_ => true,
});
ExtBuilder::default().build().execute_with(|| {
let min_balance = <Test as Config>::Currency::minimum_balance();
let schedule = <Test as Config>::Schedule::get();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
set_balance(&ALICE, min_balance * 10);
place_contract(&BOB, code_hash);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
System::reset_events();
MockStack::run_call(
contract_origin,
BOB,
&mut gas_meter,
&mut storage_meter,
&schedule,
0,
vec![],
None,
Determinism::Enforced,
)
.unwrap();
let remark_hash = <Test as frame_system::Config>::Hashing::hash(b"Hello");
assert_eq!(
System::events(),
vec![
EventRecord {
phase: Phase::Initialization,
event: MetaEvent::System(frame_system::Event::Remarked {
sender: BOB,
hash: remark_hash
}),
topics: vec![],
},
EventRecord {
phase: Phase::Initialization,
event: MetaEvent::Utility(pallet_utility::Event::ItemCompleted),
topics: vec![],
},
EventRecord {
phase: Phase::Initialization,
event: MetaEvent::Utility(pallet_utility::Event::BatchInterrupted {
index: 1,
error: frame_system::Error::<Test>::CallFiltered.into()
},),
topics: vec![],
},
EventRecord {
phase: Phase::Initialization,
event: MetaEvent::Contracts(crate::Event::Called {
caller: Origin::from_account_id(ALICE),
contract: BOB,
}),
topics: vec![hash(&Origin::<Test>::from_account_id(ALICE)), hash(&BOB)],
},
]
);
});
}
#[test]
fn nonce() {
let fail_code = MockLoader::insert(Constructor, |_, _| exec_trapped());
let success_code = MockLoader::insert(Constructor, |_, _| exec_success());
let succ_fail_code = MockLoader::insert(Constructor, move |ctx, _| {
ctx.ext
.instantiate(
Weight::zero(),
BalanceOf::<Test>::zero(),
fail_code,
ctx.ext.minimum_balance() * 100,
vec![],
&[],
)
.ok();
exec_success()
});
let succ_succ_code = MockLoader::insert(Constructor, move |ctx, _| {
let (account_id, _) = ctx
.ext
.instantiate(
Weight::zero(),
BalanceOf::<Test>::zero(),
success_code,
ctx.ext.minimum_balance() * 100,
vec![],
&[],
)
.unwrap();
// a plain call should not influence the account counter
ctx.ext
.call(
Weight::zero(),
BalanceOf::<Test>::zero(),
account_id,
0,
vec![],
false,
)
.unwrap();
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
let min_balance = <Test as Config>::Currency::minimum_balance();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
let fail_executable = MockExecutable::from_storage(fail_code, &mut gas_meter).unwrap();
let success_executable =
MockExecutable::from_storage(success_code, &mut gas_meter).unwrap();
let succ_fail_executable =
MockExecutable::from_storage(succ_fail_code, &mut gas_meter).unwrap();
let succ_succ_executable =
MockExecutable::from_storage(succ_succ_code, &mut gas_meter).unwrap();
set_balance(&ALICE, min_balance * 10_000);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, None, min_balance * 100).unwrap();
MockStack::run_instantiate(
ALICE,
fail_executable,
&mut gas_meter,
&mut storage_meter,
&schedule,
min_balance * 100,
vec![],
&[],
None,
)
.ok();
assert_eq!(<Nonce<Test>>::get(), 0);
assert_ok!(MockStack::run_instantiate(
ALICE,
success_executable,
&mut gas_meter,
&mut storage_meter,
&schedule,
min_balance * 100,
vec![],
&[],
None,
));
assert_eq!(<Nonce<Test>>::get(), 1);
assert_ok!(MockStack::run_instantiate(
ALICE,
succ_fail_executable,
&mut gas_meter,
&mut storage_meter,
&schedule,
min_balance * 200,
vec![],
&[],
None,
));
assert_eq!(<Nonce<Test>>::get(), 2);
assert_ok!(MockStack::run_instantiate(
ALICE,
succ_succ_executable,
&mut gas_meter,
&mut storage_meter,
&schedule,
min_balance * 200,
vec![],
&[],
None,
));
assert_eq!(<Nonce<Test>>::get(), 4);
});
}
#[test]
fn set_storage_works() {
let code_hash = MockLoader::insert(Call, |ctx, _| {
// Write
assert_eq!(
ctx.ext
.set_storage(&Key::Fix([1; 32]), Some(vec![1, 2, 3]), false),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext
.set_storage(&Key::Fix([2; 32]), Some(vec![4, 5, 6]), true),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext.set_storage(&Key::Fix([3; 32]), None, false),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext.set_storage(&Key::Fix([4; 32]), None, true),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext.set_storage(&Key::Fix([5; 32]), Some(vec![]), false),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext.set_storage(&Key::Fix([6; 32]), Some(vec![]), true),
Ok(WriteOutcome::New)
);
// Overwrite
assert_eq!(
ctx.ext
.set_storage(&Key::Fix([1; 32]), Some(vec![42]), false),
Ok(WriteOutcome::Overwritten(3))
);
assert_eq!(
ctx.ext
.set_storage(&Key::Fix([2; 32]), Some(vec![48]), true),
Ok(WriteOutcome::Taken(vec![4, 5, 6]))
);
assert_eq!(
ctx.ext.set_storage(&Key::Fix([3; 32]), None, false),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext.set_storage(&Key::Fix([4; 32]), None, true),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext.set_storage(&Key::Fix([5; 32]), Some(vec![]), false),
Ok(WriteOutcome::Overwritten(0))
);
assert_eq!(
ctx.ext.set_storage(&Key::Fix([6; 32]), Some(vec![]), true),
Ok(WriteOutcome::Taken(vec![]))
);
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let min_balance = <Test as Config>::Currency::minimum_balance();
let schedule = <Test as Config>::Schedule::get();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
set_balance(&ALICE, min_balance * 1000);
place_contract(&BOB, code_hash);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter = storage::meter::Meter::new(&contract_origin, None, 0).unwrap();
assert_ok!(MockStack::run_call(
contract_origin,
BOB,
&mut gas_meter,
&mut storage_meter,
&schedule,
0,
vec![],
None,
Determinism::Enforced
));
});
}
#[test]
fn set_storage_varsized_key_works() {
let code_hash = MockLoader::insert(Call, |ctx, _| {
// Write
assert_eq!(
ctx.ext.set_storage(
&Key::<Test>::try_from_var([1; 64].to_vec()).unwrap(),
Some(vec![1, 2, 3]),
false
),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext.set_storage(
&Key::<Test>::try_from_var([2; 19].to_vec()).unwrap(),
Some(vec![4, 5, 6]),
true
),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext.set_storage(
&Key::<Test>::try_from_var([3; 19].to_vec()).unwrap(),
None,
false
),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext.set_storage(
&Key::<Test>::try_from_var([4; 64].to_vec()).unwrap(),
None,
true
),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext.set_storage(
&Key::<Test>::try_from_var([5; 30].to_vec()).unwrap(),
Some(vec![]),
false
),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext.set_storage(
&Key::<Test>::try_from_var([6; 128].to_vec()).unwrap(),
Some(vec![]),
true
),
Ok(WriteOutcome::New)
);
// Overwrite
assert_eq!(
ctx.ext.set_storage(
&Key::<Test>::try_from_var([1; 64].to_vec()).unwrap(),
Some(vec![42, 43, 44]),
false
),
Ok(WriteOutcome::Overwritten(3))
);
assert_eq!(
ctx.ext.set_storage(
&Key::<Test>::try_from_var([2; 19].to_vec()).unwrap(),
Some(vec![48]),
true
),
Ok(WriteOutcome::Taken(vec![4, 5, 6]))
);
assert_eq!(
ctx.ext.set_storage(
&Key::<Test>::try_from_var([3; 19].to_vec()).unwrap(),
None,
false
),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext.set_storage(
&Key::<Test>::try_from_var([4; 64].to_vec()).unwrap(),
None,
true
),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext.set_storage(
&Key::<Test>::try_from_var([5; 30].to_vec()).unwrap(),
Some(vec![]),
false
),
Ok(WriteOutcome::Overwritten(0))
);
assert_eq!(
ctx.ext.set_storage(
&Key::<Test>::try_from_var([6; 128].to_vec()).unwrap(),
Some(vec![]),
true
),
Ok(WriteOutcome::Taken(vec![]))
);
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let min_balance = <Test as Config>::Currency::minimum_balance();
let schedule = <Test as Config>::Schedule::get();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
set_balance(&ALICE, min_balance * 1000);
place_contract(&BOB, code_hash);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter = storage::meter::Meter::new(&contract_origin, None, 0).unwrap();
assert_ok!(MockStack::run_call(
contract_origin,
BOB,
&mut gas_meter,
&mut storage_meter,
&schedule,
0,
vec![],
None,
Determinism::Enforced
));
});
}
#[test]
fn get_storage_works() {
let code_hash = MockLoader::insert(Call, |ctx, _| {
assert_eq!(
ctx.ext
.set_storage(&Key::Fix([1; 32]), Some(vec![1, 2, 3]), false),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext.set_storage(&Key::Fix([2; 32]), Some(vec![]), false),
Ok(WriteOutcome::New)
);
assert_eq!(ctx.ext.get_storage(&Key::Fix([1; 32])), Some(vec![1, 2, 3]));
assert_eq!(ctx.ext.get_storage(&Key::Fix([2; 32])), Some(vec![]));
assert_eq!(ctx.ext.get_storage(&Key::Fix([3; 32])), None);
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let min_balance = <Test as Config>::Currency::minimum_balance();
let schedule = <Test as Config>::Schedule::get();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
set_balance(&ALICE, min_balance * 1000);
place_contract(&BOB, code_hash);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter = storage::meter::Meter::new(&contract_origin, None, 0).unwrap();
assert_ok!(MockStack::run_call(
contract_origin,
BOB,
&mut gas_meter,
&mut storage_meter,
&schedule,
0,
vec![],
None,
Determinism::Enforced
));
});
}
#[test]
fn get_storage_size_works() {
let code_hash = MockLoader::insert(Call, |ctx, _| {
assert_eq!(
ctx.ext
.set_storage(&Key::Fix([1; 32]), Some(vec![1, 2, 3]), false),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext.set_storage(&Key::Fix([2; 32]), Some(vec![]), false),
Ok(WriteOutcome::New)
);
assert_eq!(ctx.ext.get_storage_size(&Key::Fix([1; 32])), Some(3));
assert_eq!(ctx.ext.get_storage_size(&Key::Fix([2; 32])), Some(0));
assert_eq!(ctx.ext.get_storage_size(&Key::Fix([3; 32])), None);
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let min_balance = <Test as Config>::Currency::minimum_balance();
let schedule = <Test as Config>::Schedule::get();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
set_balance(&ALICE, min_balance * 1000);
place_contract(&BOB, code_hash);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter = storage::meter::Meter::new(&contract_origin, None, 0).unwrap();
assert_ok!(MockStack::run_call(
contract_origin,
BOB,
&mut gas_meter,
&mut storage_meter,
&schedule,
0,
vec![],
None,
Determinism::Enforced
));
});
}
#[test]
fn get_storage_varsized_key_works() {
let code_hash = MockLoader::insert(Call, |ctx, _| {
assert_eq!(
ctx.ext.set_storage(
&Key::<Test>::try_from_var([1; 19].to_vec()).unwrap(),
Some(vec![1, 2, 3]),
false
),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext.set_storage(
&Key::<Test>::try_from_var([2; 16].to_vec()).unwrap(),
Some(vec![]),
false
),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext
.get_storage(&Key::<Test>::try_from_var([1; 19].to_vec()).unwrap()),
Some(vec![1, 2, 3])
);
assert_eq!(
ctx.ext
.get_storage(&Key::<Test>::try_from_var([2; 16].to_vec()).unwrap()),
Some(vec![])
);
assert_eq!(
ctx.ext
.get_storage(&Key::<Test>::try_from_var([3; 8].to_vec()).unwrap()),
None
);
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let min_balance = <Test as Config>::Currency::minimum_balance();
let schedule = <Test as Config>::Schedule::get();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
set_balance(&ALICE, min_balance * 1000);
place_contract(&BOB, code_hash);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter = storage::meter::Meter::new(&contract_origin, None, 0).unwrap();
assert_ok!(MockStack::run_call(
contract_origin,
BOB,
&mut gas_meter,
&mut storage_meter,
&schedule,
0,
vec![],
None,
Determinism::Enforced
));
});
}
#[test]
fn get_storage_size_varsized_key_works() {
let code_hash = MockLoader::insert(Call, |ctx, _| {
assert_eq!(
ctx.ext.set_storage(
&Key::<Test>::try_from_var([1; 19].to_vec()).unwrap(),
Some(vec![1, 2, 3]),
false
),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext.set_storage(
&Key::<Test>::try_from_var([2; 16].to_vec()).unwrap(),
Some(vec![]),
false
),
Ok(WriteOutcome::New)
);
assert_eq!(
ctx.ext
.get_storage_size(&Key::<Test>::try_from_var([1; 19].to_vec()).unwrap()),
Some(3)
);
assert_eq!(
ctx.ext
.get_storage_size(&Key::<Test>::try_from_var([2; 16].to_vec()).unwrap()),
Some(0)
);
assert_eq!(
ctx.ext
.get_storage_size(&Key::<Test>::try_from_var([3; 8].to_vec()).unwrap()),
None
);
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let min_balance = <Test as Config>::Currency::minimum_balance();
let schedule = <Test as Config>::Schedule::get();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
set_balance(&ALICE, min_balance * 1000);
place_contract(&BOB, code_hash);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter = storage::meter::Meter::new(&contract_origin, None, 0).unwrap();
assert_ok!(MockStack::run_call(
contract_origin,
BOB,
&mut gas_meter,
&mut storage_meter,
&schedule,
0,
vec![],
None,
Determinism::Enforced
));
});
}
#[test]
fn ecdsa_to_eth_address_returns_proper_value() {
let bob_ch = MockLoader::insert(Call, |ctx, _| {
let pubkey_compressed = array_bytes::hex2array_unchecked(
"028db55b05db86c0b1786ca49f095d76344c9e6056b2f02701a7e7f3c20aabfd91",
);
assert_eq!(
ctx.ext.ecdsa_to_eth_address(&pubkey_compressed).unwrap(),
array_bytes::hex2array_unchecked::<_, 20>(
"09231da7b19A016f9e576d23B16277062F4d46A8"
)
);
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&BOB, bob_ch);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
let result = MockStack::run_call(
contract_origin,
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
vec![],
None,
Determinism::Enforced,
);
assert_matches!(result, Ok(_));
});
}
#[test]
fn nonce_api_works() {
let fail_code = MockLoader::insert(Constructor, |_, _| exec_trapped());
let success_code = MockLoader::insert(Constructor, |_, _| exec_success());
let code_hash = MockLoader::insert(Call, move |ctx, _| {
// It is set to one when this contract was instantiated by `place_contract`
assert_eq!(ctx.ext.nonce(), 1);
// Should not change without any instantiation in-between
assert_eq!(ctx.ext.nonce(), 1);
// Should not change with a failed instantiation
assert_err!(
ctx.ext.instantiate(
Weight::zero(),
BalanceOf::<Test>::zero(),
fail_code,
0,
vec![],
&[],
),
ExecError {
error: <Error<Test>>::ContractTrapped.into(),
origin: ErrorOrigin::Callee
}
);
assert_eq!(ctx.ext.nonce(), 1);
// Successful instantiation increments
ctx.ext
.instantiate(
Weight::zero(),
BalanceOf::<Test>::zero(),
success_code,
0,
vec![],
&[],
)
.unwrap();
assert_eq!(ctx.ext.nonce(), 2);
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let min_balance = <Test as Config>::Currency::minimum_balance();
let schedule = <Test as Config>::Schedule::get();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
set_balance(&ALICE, min_balance * 1000);
place_contract(&BOB, code_hash);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter = storage::meter::Meter::new(&contract_origin, None, 0).unwrap();
assert_ok!(MockStack::run_call(
contract_origin,
BOB,
&mut gas_meter,
&mut storage_meter,
&schedule,
0,
vec![],
None,
Determinism::Enforced
));
});
}
/// This works even though random interface is deprecated, as the check to ban deprecated
/// functions happens in the wasm stack which is mocked for exec tests.
#[test]
fn randomness_works() {
let subject = b"nice subject".as_ref();
let code_hash = MockLoader::insert(Call, move |ctx, _| {
let rand = <Test as Config>::Randomness::random(subject);
assert_eq!(rand, ctx.ext.random(subject));
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let schedule = <Test as Config>::Schedule::get();
place_contract(&BOB, code_hash);
let contract_origin = Origin::from_account_id(ALICE);
let mut storage_meter =
storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap();
let result = MockStack::run_call(
contract_origin,
BOB,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
&schedule,
0,
vec![],
None,
Determinism::Enforced,
);
assert_matches!(result, Ok(_));
});
}
}