Compare commits
645 Commits
release/1.
...
v1.10.8
Author | SHA1 | Date | |
---|---|---|---|
|
26675454bf | ||
|
1d99573192 | ||
|
f38abc55f1 | ||
|
dfeb2f7e80 | ||
|
bb1f7ebf20 | ||
|
d02c605367 | ||
|
c368f728c1 | ||
|
5566e5d152 | ||
|
57feabea66 | ||
|
16ecdd5839 | ||
|
85b9bdd641 | ||
|
6902485767 | ||
|
fb4007bb22 | ||
|
0a68558e7e | ||
|
fd604becbb | ||
|
5f98020a21 | ||
|
a580f7d6c5 | ||
|
12f0ff40b1 | ||
|
971df49fe2 | ||
|
f4ad493870 | ||
|
2a451f9eb3 | ||
|
278ec7176a | ||
|
deff5056fb | ||
|
c27bd3481e | ||
|
0fbc94eabc | ||
|
9097d0a325 | ||
|
5d0ab07343 | ||
|
9d6480c3cd | ||
|
a879c42bd3 | ||
|
39fe7eca6b | ||
|
66948316f7 | ||
|
57d9e0ac75 | ||
|
e4b687cf46 | ||
|
6d175460df | ||
|
520f25688a | ||
|
3b38a83274 | ||
|
97bd6cd216 | ||
|
d60cfd2604 | ||
|
9e59474e46 | ||
|
8a24b56331 | ||
|
0658712f65 | ||
|
d3e3a460ec | ||
|
28ba686cbf | ||
|
f311488d2c | ||
|
c38fab912b | ||
|
4cd6a1458e | ||
|
82c5085399 | ||
|
95bbd46eab | ||
|
85afdeef37 | ||
|
860184d542 | ||
|
3526f69047 | ||
|
295bc35ecf | ||
|
8f11d279d2 | ||
|
b157bae2c9 | ||
|
64a5e125c5 | ||
|
fb8ea5993f | ||
|
5c13012b56 | ||
|
523866c2cc | ||
|
56e9001a1a | ||
|
0730acc5a0 | ||
|
2faf796d2a | ||
|
3aea432b35 | ||
|
b20bc5c0ca | ||
|
5c89ec9b98 | ||
|
bbfa6488ac | ||
|
a1f16bc74c | ||
|
576681f29b | ||
|
370680a7a9 | ||
|
97aacd9b35 | ||
|
f05419f0fb | ||
|
a5e3aa693c | ||
|
89fde59a80 | ||
|
f0b1bddac4 | ||
|
33ca98ece9 | ||
|
1fac96c1f9 | ||
|
b9e6e43722 | ||
|
c49e065fea | ||
|
846badc480 | ||
|
8fe47b0a0d | ||
|
58b0420a8a | ||
|
afd4227df8 | ||
|
9624f92ede | ||
|
dea71556cc | ||
|
ff4ff30a68 | ||
|
00b922fc5d | ||
|
7522642393 | ||
|
b9d4412715 | ||
|
5441a8fa47 | ||
|
e13d14e6a3 | ||
|
d21a069619 | ||
|
13bc9c0c6e | ||
|
5afc82de6e | ||
|
bd566977e8 | ||
|
99169016d2 | ||
|
78c34fdc3c | ||
|
d081c935d7 | ||
|
bb0191f22b | ||
|
c619562313 | ||
|
6b6d3190cf | ||
|
3b05318525 | ||
|
a182c76815 | ||
|
6ed812db13 | ||
|
3212fb6838 | ||
|
f5f906dd0d | ||
|
bbbeb7d8ba | ||
|
c131e812ae | ||
|
686b2884ee | ||
|
e7c8693635 | ||
|
ec88bd0cd0 | ||
|
acdf9238fb | ||
|
d3f018fde8 | ||
|
4fcc93d922 | ||
|
61f4b5aa89 | ||
|
35dbf7a8a3 | ||
|
1b5582acf7 | ||
|
dde6f1e92d | ||
|
2d4eff21ca | ||
|
bca8c03e57 | ||
|
c07918e7d8 | ||
|
0e6961366a | ||
|
948a600ed5 | ||
|
9e23610b0f | ||
|
29905d86ae | ||
|
10eb654f27 | ||
|
4dde0665c8 | ||
|
a750bf8686 | ||
|
bef78efb49 | ||
|
ddf10250c7 | ||
|
fcd7bdc2b7 | ||
|
1e44c3585f | ||
|
5228b2a353 | ||
|
e0123026b6 | ||
|
653a30f4ca | ||
|
0f2347d070 | ||
|
da000c8314 | ||
|
f915a4bf20 | ||
|
732a6a3666 | ||
|
7b6c8363da | ||
|
4695117f2e | ||
|
e9f99d1c91 | ||
|
ef946a6c87 | ||
|
58aeab77d2 | ||
|
97ce6dfa6d | ||
|
bbb2b30506 | ||
|
15fe3050a1 | ||
|
c63c2d855e | ||
|
87a11a87c2 | ||
|
aa637fd38a | ||
|
e1f244a6e6 | ||
|
40a11d644c | ||
|
b28f8c0c43 | ||
|
90ffcfde89 | ||
|
a675c89c75 | ||
|
080b6ebe91 | ||
|
ae315ef7a1 | ||
|
aa69d36152 | ||
|
0aadb49c86 | ||
|
cdb9fefc48 | ||
|
7a7abe3de8 | ||
|
087ed9c92e | ||
|
7530803065 | ||
|
8a4460c47e | ||
|
1d57f22d58 | ||
|
ccf53daee1 | ||
|
eff998effb | ||
|
a2ea537a6f | ||
|
1fc0eba50d | ||
|
be1267ced5 | ||
|
f68a68a313 | ||
|
7a00378e2b | ||
|
c503f98f6d | ||
|
f763846e6e | ||
|
248572ee54 | ||
|
ddeeb89c03 | ||
|
0e9c7d564d | ||
|
08379b5533 | ||
|
92b8f28df3 | ||
|
71ff65b188 | ||
|
7e915ee379 | ||
|
3094e7f3b8 | ||
|
216ed05c6e | ||
|
7760a60794 | ||
|
5cff9754d7 | ||
|
2dee31930c | ||
|
2cde472650 | ||
|
9aaa4208a8 | ||
|
08ea52e77a | ||
|
2d716c4b01 | ||
|
966ee3ae6d | ||
|
ee35ddc8fd | ||
|
04cb5e2be3 | ||
|
427175153c | ||
|
0703ef62d3 | ||
|
d836ad141e | ||
|
7194c847b6 | ||
|
2e7714f864 | ||
|
5869789d75 | ||
|
c73652da0b | ||
|
05dab7f6bd | ||
|
10962b685e | ||
|
49bde05a55 | ||
|
6c7d6cf886 | ||
|
750115ff39 | ||
|
51b32cc7e4 | ||
|
836c647bdd | ||
|
4d33de9b49 | ||
|
017cf71fbd | ||
|
93407b14a6 | ||
|
154ca32a8a | ||
|
0d076d92db | ||
|
59f259b058 | ||
|
6bc72783f6 | ||
|
835fe06f1d | ||
|
81662fe827 | ||
|
a6c462781f | ||
|
16bc57438b | ||
|
3e795881ea | ||
|
b3a1fda650 | ||
|
088da24ebf | ||
|
3e6f46caec | ||
|
32c1ed8a9c | ||
|
b7a91663ab | ||
|
bb9f9ccf4f | ||
|
67e7f61af7 | ||
|
94451c2788 | ||
|
14bc6e5130 | ||
|
597ecb39cc | ||
|
addd8824cf | ||
|
1cca781a02 | ||
|
a2c456a526 | ||
|
f34f749e81 | ||
|
0524cede37 | ||
|
ca98080798 | ||
|
643fd0efc6 | ||
|
e536bb52ff | ||
|
c0e201b690 | ||
|
ae5fcdc67f | ||
|
f19a679b09 | ||
|
7ab7acfded | ||
|
700df1442d | ||
|
17b1be2661 | ||
|
8a070e8f7d | ||
|
a5669ae292 | ||
|
e77ef8fa8a | ||
|
e69130d9f1 | ||
|
cc606be74c | ||
|
df20b3b982 | ||
|
37b5595456 | ||
|
991384a7f6 | ||
|
0f3a1e7f9b | ||
|
41671d449f | ||
|
3a2b29c1ed | ||
|
973ad66b49 | ||
|
d107f90d1c | ||
|
effaf18523 | ||
|
b8040a430e | ||
|
640d2c5e30 | ||
|
856c379626 | ||
|
fc1c1cbea9 | ||
|
8f94fc26e3 | ||
|
afb097eda8 | ||
|
ca9c576e62 | ||
|
0e00ee42ec | ||
|
8ff98108e5 | ||
|
afc1abd878 | ||
|
52b5d2d869 | ||
|
8681a2536c | ||
|
745757ac6b | ||
|
bbb57fd64b | ||
|
f66f1a16b3 | ||
|
ff75b21f25 | ||
|
b778e37daa | ||
|
dde6cb0b92 | ||
|
1e57ab5de6 | ||
|
8130dd5cef | ||
|
bb43cd7a79 | ||
|
b50b17ac69 | ||
|
63bad18c33 | ||
|
56f533d00c | ||
|
793c8f889f | ||
|
c7d07294a6 | ||
|
871f50b911 | ||
|
06f44c0fd4 | ||
|
64b60c7995 | ||
|
fae165a5de | ||
|
a81cf0d2b3 | ||
|
abb6cfae6a | ||
|
e4270cacf4 | ||
|
558bff4008 | ||
|
6d7c9566df | ||
|
9e5bb84c0e | ||
|
256c5d68b2 | ||
|
0c99868416 | ||
|
d9c9ee5ac9 | ||
|
ff3535e8e0 | ||
|
55043eec45 | ||
|
45fca44c24 | ||
|
caea6c4661 | ||
|
65a1c2d829 | ||
|
a0a99e610d | ||
|
ad983b300b | ||
|
85a0bab6d7 | ||
|
a3f0da1ac4 | ||
|
854f068ed6 | ||
|
9b99e3dfe0 | ||
|
83375b0873 | ||
|
34f3c9539b | ||
|
cac1b21d39 | ||
|
49281ab84f | ||
|
ea54c58d4f | ||
|
1fb9a6dd32 | ||
|
9357280fce | ||
|
67da83aca5 | ||
|
4b783c0064 | ||
|
3e68d627b1 | ||
|
96828c90f5 | ||
|
dd9c3225cf | ||
|
cc33398cef | ||
|
beee6b77a0 | ||
|
581539c6ee | ||
|
d7bfb978ba | ||
|
d6ffa14035 | ||
|
653b7e959d | ||
|
424656519a | ||
|
e43ac53264 | ||
|
f79cce5de9 | ||
|
09d44e9925 | ||
|
4f3ba6742f | ||
|
65689e7fce | ||
|
f8afb681dd | ||
|
fda93f643e | ||
|
3cfd0fe7a8 | ||
|
9553c98de8 | ||
|
1e207342b5 | ||
|
d8ff53dfb8 | ||
|
d5e57948d1 | ||
|
7088f1e814 | ||
|
a50251e6cb | ||
|
72e37942f3 | ||
|
271e5b7fc9 | ||
|
6c27d8f996 | ||
|
9c653ff662 | ||
|
fe1586b094 | ||
|
04dcc9378d | ||
|
97d11b0187 | ||
|
a665f5d2d6 | ||
|
e3ff37c47a | ||
|
264fff7dd4 | ||
|
2a7c4b62a9 | ||
|
9d10856e84 | ||
|
a600dab7e5 | ||
|
2d89fe0883 | ||
|
e275b1a293 | ||
|
95219ae62d | ||
|
5338ce4447 | ||
|
adf09aeab1 | ||
|
706683ea72 | ||
|
c79fc209cd | ||
|
73ed68988f | ||
|
55300d4fdb | ||
|
4a37ae510e | ||
|
61ff3e86b2 | ||
|
3faae5defc | ||
|
44fe466999 | ||
|
59ac3c9fd3 | ||
|
43a3768066 | ||
|
24588bacfd | ||
|
b6912c1047 | ||
|
7644795950 | ||
|
76700ac892 | ||
|
27056f62e5 | ||
|
e7f3962612 | ||
|
099be04100 | ||
|
063f78c6ba | ||
|
62379f02c6 | ||
|
cae6b5527e | ||
|
955727181b | ||
|
6477ea6502 | ||
|
2550e46269 | ||
|
efe0229768 | ||
|
6d7ff6acea | ||
|
54c0d573d7 | ||
|
4adf0b9187 | ||
|
bed74b38d9 | ||
|
497448bf90 | ||
|
0fda25e471 | ||
|
c5df05b9a9 | ||
|
ab8fd4d005 | ||
|
15e6c27f8b | ||
|
5129cdc4f0 | ||
|
e862cbff95 | ||
|
477ec75323 | ||
|
f304290b7d | ||
|
a31f6d54df | ||
|
8d6cc16742 | ||
|
0c70b83e00 | ||
|
aab35600bc | ||
|
eaccdba4ab | ||
|
ec73ec092d | ||
|
36b51b8156 | ||
|
5bf6612a2e | ||
|
9429ab1472 | ||
|
d3040a80d7 | ||
|
c454717fa6 | ||
|
5bc0343ed3 | ||
|
e3a3f7cd64 | ||
|
d50e9d24be | ||
|
345890a558 | ||
|
a90861ae0c | ||
|
38ea7f2cf4 | ||
|
aa8b2189c6 | ||
|
6a528fce33 | ||
|
117fa7d4a1 | ||
|
410089afea | ||
|
91726e8aad | ||
|
6d9707a458 | ||
|
62d8022b51 | ||
|
94ab4ea341 | ||
|
7cbf1d70a7 | ||
|
7076e8e42f | ||
|
99830720f6 | ||
|
bc47993692 | ||
|
faacc8e0fa | ||
|
c6d45009f1 | ||
|
3f74c8e0e5 | ||
|
6387c520b7 | ||
|
aae7660410 | ||
|
22082f9e56 | ||
|
3d299b7468 | ||
|
be87f769f6 | ||
|
182670849e | ||
|
c2d2f4ed8f | ||
|
5aba946164 | ||
|
72b8cacf13 | ||
|
44c0bb2b44 | ||
|
658cb9fc4f | ||
|
dab90e4d42 | ||
|
5b95453ef2 | ||
|
89026d5d70 | ||
|
de61da99c4 | ||
|
9230ca4924 | ||
|
63385374ec | ||
|
56dec25ae2 | ||
|
cd316d7c71 | ||
|
5a81dd97d5 | ||
|
b24804d88c | ||
|
ba999105ef | ||
|
07e907c7d4 | ||
|
c539a052bd | ||
|
0540d3c6f6 | ||
|
430f69e01e | ||
|
7834e4a278 | ||
|
19d7a37abb | ||
|
d96870428f | ||
|
498458b410 | ||
|
3822b09904 | ||
|
744707a490 | ||
|
27b31371d4 | ||
|
0928562670 | ||
|
dc109cce26 | ||
|
de9465f991 | ||
|
bbfb1e4008 | ||
|
7a3c890009 | ||
|
378e961d85 | ||
|
96d9306413 | ||
|
b2b5c82aca | ||
|
8e547eecd5 | ||
|
f54dc4ab3d | ||
|
bf5b379b13 | ||
|
70afe15f68 | ||
|
b502c86662 | ||
|
c9aa267049 | ||
|
cdb6a84339 | ||
|
4ee8d2d305 | ||
|
2743fb0429 | ||
|
2d1a0e9b03 | ||
|
142fbcfd6f | ||
|
c4a2b682ff | ||
|
3ecfdccd9a | ||
|
8f03e3b107 | ||
|
8647233a8e | ||
|
c5023e1dc5 | ||
|
ca76db6116 | ||
|
c027507e03 | ||
|
d36276d85e | ||
|
6ec1561044 | ||
|
b1835b3855 | ||
|
9ec32a9e7b | ||
|
52e5c38aa5 | ||
|
e01096f531 | ||
|
1489c3f494 | ||
|
f9445e93bb | ||
|
bfdff4c5b8 | ||
|
6291fc9230 | ||
|
9ec3329899 | ||
|
915c614959 | ||
|
f4fcd4f506 | ||
|
e991bdae24 | ||
|
77787802fe | ||
|
08c878acd2 | ||
|
7d1b711c7d | ||
|
2fc465a7be | ||
|
ef227c5f42 | ||
|
111abdcfbd | ||
|
1bbc8a1944 | ||
|
409b16e5ab | ||
|
cb3c7e4319 | ||
|
27786671d2 | ||
|
2fdba3aacb | ||
|
74dbc20260 | ||
|
944d901436 | ||
|
2728672c28 | ||
|
123e934e72 | ||
|
f566dd305e | ||
|
d86906f1e6 | ||
|
bbe694fc52 | ||
|
477fd420b3 | ||
|
994cdc69c8 | ||
|
e74bd587f7 | ||
|
7ed860d4f1 | ||
|
fba5a63afe | ||
|
098a2b6e26 | ||
|
28121324ac | ||
|
54735a6723 | ||
|
3512b41c5c | ||
|
83e4c49e2b | ||
|
ef84da8481 | ||
|
4eae0c6b6f | ||
|
e3430ac7df | ||
|
3c728fb129 | ||
|
f25b437b70 | ||
|
7a800f98f6 | ||
|
eb21c652c0 | ||
|
2e5d141708 | ||
|
a72fa88a0d | ||
|
9c5729311e | ||
|
ad038b6289 | ||
|
681618275c | ||
|
14d495491d | ||
|
573f373d2b | ||
|
7202b410b0 | ||
|
d2779ed7ac | ||
|
adf130def8 | ||
|
49cdcf5c70 | ||
|
04a72260c5 | ||
|
59a79137b9 | ||
|
c0862f4f4c | ||
|
1770fe718a | ||
|
797b0812ab | ||
|
3708454f58 | ||
|
db35d77b63 | ||
|
f26c19cbcd | ||
|
9e1bd0f367 | ||
|
231040c633 | ||
|
c4307a9339 | ||
|
ddadc3d273 | ||
|
42f9f1f073 | ||
|
1e1865b73f | ||
|
81bf9f97c9 | ||
|
7da8f75d5b | ||
|
d1301eb0df | ||
|
45cb1a580a | ||
|
24c1e3053b | ||
|
5e9f5ca5d3 | ||
|
10555d4684 | ||
|
398182284c | ||
|
034ecc3210 | ||
|
c76573a97b | ||
|
8d62ee65b2 | ||
|
3944976a9a | ||
|
c4deebbf1e | ||
|
d13c59fef0 | ||
|
12969084d1 | ||
|
96157a897b | ||
|
2aaff0ad76 | ||
|
6296211a3e | ||
|
c94081774f | ||
|
c7a6be163f | ||
|
93a89b2681 | ||
|
23f837c388 | ||
|
984e752ce5 | ||
|
39b3b8ffb4 | ||
|
49c2816d54 | ||
|
79e2174e4d | ||
|
ab5e3f400f | ||
|
5a1b384352 | ||
|
89030ec0b4 | ||
|
889f5645b5 | ||
|
6b88ab75bc | ||
|
165f53fc6e | ||
|
d3952898c3 | ||
|
3c6665e7d6 | ||
|
4bb5c6ca7a | ||
|
38310f9022 | ||
|
58b9db5f7c | ||
|
44208d9258 | ||
|
8bd8e1b24a | ||
|
d2e1b17f18 | ||
|
072fd96254 | ||
|
d667ee2d10 | ||
|
83d317cff9 | ||
|
618454214b | ||
|
9ba306d47e | ||
|
4714ce9430 | ||
|
eb2a1dfdd2 | ||
|
664903dc88 | ||
|
9584f56b9d | ||
|
6ada9f0f38 | ||
|
e4571d8c12 | ||
|
1951e20d10 | ||
|
5c2a7ce2cc | ||
|
47820ef726 | ||
|
f83fc302a5 | ||
|
167ff563d1 | ||
|
0a3993c558 | ||
|
a425a47ddc | ||
|
c17a7733df | ||
|
653e8b9dd9 | ||
|
ab0979f930 | ||
|
0a09a39325 | ||
|
2f8100615a | ||
|
b13e9c4e3d | ||
|
9c6b5b904a | ||
|
25c0bd9b43 | ||
|
b9012a039b | ||
|
158f72cc0c | ||
|
61469cfeaf | ||
|
c5a3ffa363 | ||
|
3c46f5570b | ||
|
c7f2536735 | ||
|
8cde2966af | ||
|
0fe66f8ae4 | ||
|
4859929798 | ||
|
017831dd5b | ||
|
00d10e610f | ||
|
38c1d592b7 | ||
|
4d48980e74 | ||
|
c49aae9870 | ||
|
efe6dd2904 | ||
|
88c696240d | ||
|
b47f4ca5cf | ||
|
62dc59c2bd | ||
|
1a715d7db5 | ||
|
fc0662bb23 | ||
|
493100ba4d |
1
.github/CODEOWNERS
vendored
1
.github/CODEOWNERS
vendored
@@ -9,6 +9,7 @@ cmd/puppeth @karalabe
|
||||
consensus @karalabe
|
||||
core/ @karalabe @holiman @rjl493456442
|
||||
eth/ @karalabe @holiman @rjl493456442
|
||||
eth/catalyst/ @gballet
|
||||
graphql/ @gballet
|
||||
les/ @zsfelfoldi @rjl493456442
|
||||
light/ @zsfelfoldi @rjl493456442
|
||||
|
4
.github/CONTRIBUTING.md
vendored
4
.github/CONTRIBUTING.md
vendored
@@ -30,11 +30,11 @@ Please make sure your contributions adhere to our coding guidelines:
|
||||
Before you submit a feature request, please check and make sure that it isn't
|
||||
possible through some other means. The JavaScript-enabled console is a powerful
|
||||
feature in the right hands. Please check our
|
||||
[Wiki page](https://github.com/ethereum/go-ethereum/wiki) for more info
|
||||
[Geth documentation page](https://geth.ethereum.org/docs/) for more info
|
||||
and help.
|
||||
|
||||
## Configuration, dependencies, and tests
|
||||
|
||||
Please see the [Developers' Guide](https://github.com/ethereum/go-ethereum/wiki/Developers'-Guide)
|
||||
Please see the [Developers' Guide](https://geth.ethereum.org/docs/developers/devguide)
|
||||
for more details on configuring your environment, managing project dependencies
|
||||
and testing procedures.
|
||||
|
2
.github/ISSUE_TEMPLATE/bug.md
vendored
2
.github/ISSUE_TEMPLATE/bug.md
vendored
@@ -26,3 +26,5 @@ Commit hash : (if `develop`)
|
||||
````
|
||||
[backtrace]
|
||||
````
|
||||
|
||||
When submitting logs: please submit them as text and not screenshots.
|
103
.travis.yml
103
.travis.yml
@@ -5,7 +5,7 @@ jobs:
|
||||
allow_failures:
|
||||
- stage: build
|
||||
os: osx
|
||||
go: 1.14.x
|
||||
go: 1.15.x
|
||||
env:
|
||||
- azure-osx
|
||||
- azure-ios
|
||||
@@ -15,8 +15,8 @@ jobs:
|
||||
# This builder only tests code linters on latest version of Go
|
||||
- stage: lint
|
||||
os: linux
|
||||
dist: xenial
|
||||
go: 1.15.x
|
||||
dist: bionic
|
||||
go: 1.16.x
|
||||
env:
|
||||
- lint
|
||||
git:
|
||||
@@ -24,12 +24,48 @@ jobs:
|
||||
script:
|
||||
- go run build/ci.go lint
|
||||
|
||||
# These builders create the Docker sub-images for multi-arch push and each
|
||||
# will attempt to push the multi-arch image if they are the last builder
|
||||
- stage: build
|
||||
if: type = push
|
||||
os: linux
|
||||
arch: amd64
|
||||
dist: bionic
|
||||
go: 1.16.x
|
||||
env:
|
||||
- docker
|
||||
services:
|
||||
- docker
|
||||
git:
|
||||
submodules: false # avoid cloning ethereum/tests
|
||||
before_install:
|
||||
- export DOCKER_CLI_EXPERIMENTAL=enabled
|
||||
script:
|
||||
- go run build/ci.go docker -image -manifest amd64,arm64 -upload ethereum/client-go
|
||||
|
||||
- stage: build
|
||||
if: type = push
|
||||
os: linux
|
||||
arch: arm64
|
||||
dist: bionic
|
||||
go: 1.16.x
|
||||
env:
|
||||
- docker
|
||||
services:
|
||||
- docker
|
||||
git:
|
||||
submodules: false # avoid cloning ethereum/tests
|
||||
before_install:
|
||||
- export DOCKER_CLI_EXPERIMENTAL=enabled
|
||||
script:
|
||||
- go run build/ci.go docker -image -manifest amd64,arm64 -upload ethereum/client-go
|
||||
|
||||
# This builder does the Ubuntu PPA upload
|
||||
- stage: build
|
||||
if: type = push
|
||||
os: linux
|
||||
dist: xenial
|
||||
go: 1.15.x
|
||||
dist: bionic
|
||||
go: 1.16.x
|
||||
env:
|
||||
- ubuntu-ppa
|
||||
- GO111MODULE=on
|
||||
@@ -52,9 +88,9 @@ jobs:
|
||||
- stage: build
|
||||
if: type = push
|
||||
os: linux
|
||||
dist: xenial
|
||||
dist: bionic
|
||||
sudo: required
|
||||
go: 1.15.x
|
||||
go: 1.16.x
|
||||
env:
|
||||
- azure-linux
|
||||
- GO111MODULE=on
|
||||
@@ -88,10 +124,10 @@ jobs:
|
||||
- stage: build
|
||||
if: type = push
|
||||
os: linux
|
||||
dist: xenial
|
||||
dist: bionic
|
||||
services:
|
||||
- docker
|
||||
go: 1.15.x
|
||||
go: 1.16.x
|
||||
env:
|
||||
- azure-linux-mips
|
||||
- GO111MODULE=on
|
||||
@@ -118,20 +154,11 @@ jobs:
|
||||
- stage: build
|
||||
if: type = push
|
||||
os: linux
|
||||
dist: xenial
|
||||
dist: bionic
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
- oracle-java8-installer
|
||||
- oracle-java8-set-default
|
||||
language: android
|
||||
android:
|
||||
components:
|
||||
- platform-tools
|
||||
- tools
|
||||
- android-15
|
||||
- android-19
|
||||
- android-24
|
||||
- openjdk-8-jdk
|
||||
env:
|
||||
- azure-android
|
||||
- maven-android
|
||||
@@ -139,16 +166,24 @@ jobs:
|
||||
git:
|
||||
submodules: false # avoid cloning ethereum/tests
|
||||
before_install:
|
||||
- curl https://dl.google.com/go/go1.15.5.linux-amd64.tar.gz | tar -xz
|
||||
# Install Android and it's dependencies manually, Travis is stale
|
||||
- export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
|
||||
- curl https://dl.google.com/android/repository/commandlinetools-linux-6858069_latest.zip -o android.zip
|
||||
- unzip -q android.zip -d $HOME/sdk && rm android.zip
|
||||
- mv $HOME/sdk/cmdline-tools $HOME/sdk/latest && mkdir $HOME/sdk/cmdline-tools && mv $HOME/sdk/latest $HOME/sdk/cmdline-tools
|
||||
- export PATH=$PATH:$HOME/sdk/cmdline-tools/latest/bin
|
||||
- export ANDROID_HOME=$HOME/sdk
|
||||
|
||||
- yes | sdkmanager --licenses >/dev/null
|
||||
- sdkmanager "platform-tools" "platforms;android-15" "platforms;android-19" "platforms;android-24" "ndk-bundle"
|
||||
|
||||
# Install Go to allow building with
|
||||
- curl https://dl.google.com/go/go1.16.linux-amd64.tar.gz | tar -xz
|
||||
- export PATH=`pwd`/go/bin:$PATH
|
||||
- export GOROOT=`pwd`/go
|
||||
- export GOPATH=$HOME/go
|
||||
script:
|
||||
# Build the Android archive and upload it to Maven Central and Azure
|
||||
- curl https://dl.google.com/android/repository/android-ndk-r19b-linux-x86_64.zip -o android-ndk-r19b.zip
|
||||
- unzip -q android-ndk-r19b.zip && rm android-ndk-r19b.zip
|
||||
- mv android-ndk-r19b $ANDROID_HOME/ndk-bundle
|
||||
|
||||
- mkdir -p $GOPATH/src/github.com/ethereum
|
||||
- ln -s `pwd` $GOPATH/src/github.com/ethereum/go-ethereum
|
||||
- go run build/ci.go aar -signer ANDROID_SIGNING_KEY -signify SIGNIFY_KEY -deploy https://oss.sonatype.org -upload gethstore/builds
|
||||
@@ -157,7 +192,7 @@ jobs:
|
||||
- stage: build
|
||||
if: type = push
|
||||
os: osx
|
||||
go: 1.15.x
|
||||
go: 1.16.x
|
||||
env:
|
||||
- azure-osx
|
||||
- azure-ios
|
||||
@@ -188,8 +223,8 @@ jobs:
|
||||
- stage: build
|
||||
os: linux
|
||||
arch: amd64
|
||||
dist: xenial
|
||||
go: 1.15.x
|
||||
dist: bionic
|
||||
go: 1.16.x
|
||||
env:
|
||||
- GO111MODULE=on
|
||||
script:
|
||||
@@ -199,8 +234,8 @@ jobs:
|
||||
if: type = pull_request
|
||||
os: linux
|
||||
arch: arm64
|
||||
dist: xenial
|
||||
go: 1.15.x
|
||||
dist: bionic
|
||||
go: 1.16.x
|
||||
env:
|
||||
- GO111MODULE=on
|
||||
script:
|
||||
@@ -208,8 +243,8 @@ jobs:
|
||||
|
||||
- stage: build
|
||||
os: linux
|
||||
dist: xenial
|
||||
go: 1.14.x
|
||||
dist: bionic
|
||||
go: 1.15.x
|
||||
env:
|
||||
- GO111MODULE=on
|
||||
script:
|
||||
@@ -219,8 +254,8 @@ jobs:
|
||||
- stage: build
|
||||
if: type = cron
|
||||
os: linux
|
||||
dist: xenial
|
||||
go: 1.15.x
|
||||
dist: bionic
|
||||
go: 1.16.x
|
||||
env:
|
||||
- azure-purge
|
||||
- GO111MODULE=on
|
||||
|
20
Dockerfile
20
Dockerfile
@@ -1,10 +1,15 @@
|
||||
# Build Geth in a stock Go builder container
|
||||
FROM golang:1.15-alpine as builder
|
||||
# Support setting various labels on the final image
|
||||
ARG COMMIT=""
|
||||
ARG VERSION=""
|
||||
ARG BUILDNUM=""
|
||||
|
||||
RUN apk add --no-cache make gcc musl-dev linux-headers git
|
||||
# Build Geth in a stock Go builder container
|
||||
FROM golang:1.16-alpine as builder
|
||||
|
||||
RUN apk add --no-cache gcc musl-dev linux-headers git
|
||||
|
||||
ADD . /go-ethereum
|
||||
RUN cd /go-ethereum && make geth
|
||||
RUN cd /go-ethereum && go run build/ci.go install ./cmd/geth
|
||||
|
||||
# Pull Geth into a second stage deploy alpine container
|
||||
FROM alpine:latest
|
||||
@@ -14,3 +19,10 @@ COPY --from=builder /go-ethereum/build/bin/geth /usr/local/bin/
|
||||
|
||||
EXPOSE 8545 8546 30303 30303/udp
|
||||
ENTRYPOINT ["geth"]
|
||||
|
||||
# Add some metadata labels to help programatic image consumption
|
||||
ARG COMMIT=""
|
||||
ARG VERSION=""
|
||||
ARG BUILDNUM=""
|
||||
|
||||
LABEL commit="$COMMIT" version="$VERSION" buildnum="$BUILDNUM"
|
||||
|
@@ -1,10 +1,15 @@
|
||||
# Build Geth in a stock Go builder container
|
||||
FROM golang:1.15-alpine as builder
|
||||
# Support setting various labels on the final image
|
||||
ARG COMMIT=""
|
||||
ARG VERSION=""
|
||||
ARG BUILDNUM=""
|
||||
|
||||
RUN apk add --no-cache make gcc musl-dev linux-headers git
|
||||
# Build Geth in a stock Go builder container
|
||||
FROM golang:1.16-alpine as builder
|
||||
|
||||
RUN apk add --no-cache gcc musl-dev linux-headers git
|
||||
|
||||
ADD . /go-ethereum
|
||||
RUN cd /go-ethereum && make all
|
||||
RUN cd /go-ethereum && go run build/ci.go install
|
||||
|
||||
# Pull all binaries into a second stage deploy alpine container
|
||||
FROM alpine:latest
|
||||
@@ -13,3 +18,10 @@ RUN apk add --no-cache ca-certificates
|
||||
COPY --from=builder /go-ethereum/build/bin/* /usr/local/bin/
|
||||
|
||||
EXPOSE 8545 8546 30303 30303/udp
|
||||
|
||||
# Add some metadata labels to help programatic image consumption
|
||||
ARG COMMIT=""
|
||||
ARG VERSION=""
|
||||
ARG BUILDNUM=""
|
||||
|
||||
LABEL commit="$COMMIT" version="$VERSION" buildnum="$BUILDNUM"
|
||||
|
11
Makefile
11
Makefile
@@ -26,7 +26,7 @@ android:
|
||||
@echo "Import \"$(GOBIN)/geth.aar\" to use the library."
|
||||
@echo "Import \"$(GOBIN)/geth-sources.jar\" to add javadocs"
|
||||
@echo "For more info see https://stackoverflow.com/questions/20994336/android-studio-how-to-attach-javadoc"
|
||||
|
||||
|
||||
ios:
|
||||
$(GORUN) build/ci.go xcode --local
|
||||
@echo "Done building."
|
||||
@@ -46,12 +46,11 @@ clean:
|
||||
# You need to put $GOBIN (or $GOPATH/bin) in your PATH to use 'go generate'.
|
||||
|
||||
devtools:
|
||||
env GOBIN= go get -u golang.org/x/tools/cmd/stringer
|
||||
env GOBIN= go get -u github.com/kevinburke/go-bindata/go-bindata
|
||||
env GOBIN= go get -u github.com/fjl/gencodec
|
||||
env GOBIN= go get -u github.com/golang/protobuf/protoc-gen-go
|
||||
env GOBIN= go install golang.org/x/tools/cmd/stringer@latest
|
||||
env GOBIN= go install github.com/kevinburke/go-bindata/go-bindata@latest
|
||||
env GOBIN= go install github.com/fjl/gencodec@latest
|
||||
env GOBIN= go install github.com/golang/protobuf/protoc-gen-go@latest
|
||||
env GOBIN= go install ./cmd/abigen
|
||||
@type "npm" 2> /dev/null || echo 'Please install node.js and npm'
|
||||
@type "solc" 2> /dev/null || echo 'Please install solc'
|
||||
@type "protoc" 2> /dev/null || echo 'Please install protoc'
|
||||
|
||||
|
47
README.md
47
README.md
@@ -6,7 +6,7 @@ Official Golang implementation of the Ethereum protocol.
|
||||
https://camo.githubusercontent.com/915b7be44ada53c290eb157634330494ebe3e30a/68747470733a2f2f676f646f632e6f72672f6769746875622e636f6d2f676f6c616e672f6764646f3f7374617475732e737667
|
||||
)](https://pkg.go.dev/github.com/ethereum/go-ethereum?tab=doc)
|
||||
[](https://goreportcard.com/report/github.com/ethereum/go-ethereum)
|
||||
[](https://travis-ci.org/ethereum/go-ethereum)
|
||||
[](https://travis-ci.com/ethereum/go-ethereum)
|
||||
[](https://discord.gg/nthXNEv)
|
||||
|
||||
Automated builds are available for stable releases and the unstable master branch. Binary
|
||||
@@ -14,9 +14,9 @@ archives are published at https://geth.ethereum.org/downloads/.
|
||||
|
||||
## Building the source
|
||||
|
||||
For prerequisites and detailed build instructions please read the [Installation Instructions](https://github.com/ethereum/go-ethereum/wiki/Building-Ethereum) on the wiki.
|
||||
For prerequisites and detailed build instructions please read the [Installation Instructions](https://geth.ethereum.org/docs/install-and-build/installing-geth).
|
||||
|
||||
Building `geth` requires both a Go (version 1.13 or later) and a C compiler. You can install
|
||||
Building `geth` requires both a Go (version 1.14 or later) and a C compiler. You can install
|
||||
them using your favourite package manager. Once the dependencies are installed, run
|
||||
|
||||
```shell
|
||||
@@ -36,18 +36,19 @@ directory.
|
||||
|
||||
| Command | Description |
|
||||
| :-----------: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **`geth`** | Our main Ethereum CLI client. It is the entry point into the Ethereum network (main-, test- or private net), capable of running as a full node (default), archive node (retaining all historical state) or a light node (retrieving data live). It can be used by other processes as a gateway into the Ethereum network via JSON RPC endpoints exposed on top of HTTP, WebSocket and/or IPC transports. `geth --help` and the [CLI Wiki page](https://github.com/ethereum/go-ethereum/wiki/Command-Line-Options) for command line options. |
|
||||
| `abigen` | Source code generator to convert Ethereum contract definitions into easy to use, compile-time type-safe Go packages. It operates on plain [Ethereum contract ABIs](https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI) with expanded functionality if the contract bytecode is also available. However, it also accepts Solidity source files, making development much more streamlined. Please see our [Native DApps](https://github.com/ethereum/go-ethereum/wiki/Native-DApps:-Go-bindings-to-Ethereum-contracts) wiki page for details. |
|
||||
| **`geth`** | Our main Ethereum CLI client. It is the entry point into the Ethereum network (main-, test- or private net), capable of running as a full node (default), archive node (retaining all historical state) or a light node (retrieving data live). It can be used by other processes as a gateway into the Ethereum network via JSON RPC endpoints exposed on top of HTTP, WebSocket and/or IPC transports. `geth --help` and the [CLI page](https://geth.ethereum.org/docs/interface/command-line-options) for command line options. |
|
||||
| `clef` | Stand-alone signing tool, which can be used as a backend signer for `geth`. |
|
||||
| `devp2p` | Utilities to interact with nodes on the networking layer, without running a full blockchain. |
|
||||
| `abigen` | Source code generator to convert Ethereum contract definitions into easy to use, compile-time type-safe Go packages. It operates on plain [Ethereum contract ABIs](https://docs.soliditylang.org/en/develop/abi-spec.html) with expanded functionality if the contract bytecode is also available. However, it also accepts Solidity source files, making development much more streamlined. Please see our [Native DApps](https://geth.ethereum.org/docs/dapp/native-bindings) page for details. |
|
||||
| `bootnode` | Stripped down version of our Ethereum client implementation that only takes part in the network node discovery protocol, but does not run any of the higher level application protocols. It can be used as a lightweight bootstrap node to aid in finding peers in private networks. |
|
||||
| `evm` | Developer utility version of the EVM (Ethereum Virtual Machine) that is capable of running bytecode snippets within a configurable environment and execution mode. Its purpose is to allow isolated, fine-grained debugging of EVM opcodes (e.g. `evm --code 60ff60ff --debug run`). |
|
||||
| `gethrpctest` | Developer utility tool to support our [ethereum/rpc-test](https://github.com/ethereum/rpc-tests) test suite which validates baseline conformity to the [Ethereum JSON RPC](https://github.com/ethereum/wiki/wiki/JSON-RPC) specs. Please see the [test suite's readme](https://github.com/ethereum/rpc-tests/blob/master/README.md) for details. |
|
||||
| `rlpdump` | Developer utility tool to convert binary RLP ([Recursive Length Prefix](https://github.com/ethereum/wiki/wiki/RLP)) dumps (data encoding used by the Ethereum protocol both network as well as consensus wise) to user-friendlier hierarchical representation (e.g. `rlpdump --hex CE0183FFFFFFC4C304050583616263`). |
|
||||
| `rlpdump` | Developer utility tool to convert binary RLP ([Recursive Length Prefix](https://eth.wiki/en/fundamentals/rlp)) dumps (data encoding used by the Ethereum protocol both network as well as consensus wise) to user-friendlier hierarchical representation (e.g. `rlpdump --hex CE0183FFFFFFC4C304050583616263`). |
|
||||
| `puppeth` | a CLI wizard that aids in creating a new Ethereum network. |
|
||||
|
||||
## Running `geth`
|
||||
|
||||
Going through all the possible command line flags is out of scope here (please consult our
|
||||
[CLI Wiki page](https://github.com/ethereum/go-ethereum/wiki/Command-Line-Options)),
|
||||
[CLI Wiki page](https://geth.ethereum.org/docs/interface/command-line-options)),
|
||||
but we've enumerated a few common parameter combos to get you up to speed quickly
|
||||
on how you can run your own `geth` instance.
|
||||
|
||||
@@ -63,12 +64,13 @@ $ geth console
|
||||
```
|
||||
|
||||
This command will:
|
||||
* Start `geth` in fast sync mode (default, can be changed with the `--syncmode` flag),
|
||||
* Start `geth` in snap sync mode (default, can be changed with the `--syncmode` flag),
|
||||
causing it to download more data in exchange for avoiding processing the entire history
|
||||
of the Ethereum network, which is very CPU intensive.
|
||||
* Start up `geth`'s built-in interactive [JavaScript console](https://github.com/ethereum/go-ethereum/wiki/JavaScript-Console),
|
||||
(via the trailing `console` subcommand) through which you can invoke all official [`web3` methods](https://github.com/ethereum/wiki/wiki/JavaScript-API)
|
||||
as well as `geth`'s own [management APIs](https://github.com/ethereum/go-ethereum/wiki/Management-APIs).
|
||||
* Start up `geth`'s built-in interactive [JavaScript console](https://geth.ethereum.org/docs/interface/javascript-console),
|
||||
(via the trailing `console` subcommand) through which you can interact using [`web3` methods](https://web3js.readthedocs.io/en/)
|
||||
(note: the `web3` version bundled within `geth` is very old, and not up to date with official docs),
|
||||
as well as `geth`'s own [management APIs](https://geth.ethereum.org/docs/rpc/server).
|
||||
This tool is optional and if you leave it out you can always attach to an already running
|
||||
`geth` instance with `geth attach`.
|
||||
|
||||
@@ -170,8 +172,8 @@ accessible from the outside.
|
||||
|
||||
As a developer, sooner rather than later you'll want to start interacting with `geth` and the
|
||||
Ethereum network via your own programs and not manually through the console. To aid
|
||||
this, `geth` has built-in support for a JSON-RPC based APIs ([standard APIs](https://github.com/ethereum/wiki/wiki/JSON-RPC)
|
||||
and [`geth` specific APIs](https://github.com/ethereum/go-ethereum/wiki/Management-APIs)).
|
||||
this, `geth` has built-in support for a JSON-RPC based APIs ([standard APIs](https://eth.wiki/json-rpc/API)
|
||||
and [`geth` specific APIs](https://geth.ethereum.org/docs/rpc/server)).
|
||||
These can be exposed via HTTP, WebSockets and IPC (UNIX sockets on UNIX based
|
||||
platforms, and named pipes on Windows).
|
||||
|
||||
@@ -228,7 +230,8 @@ aware of and agree upon. This consists of a small JSON file (e.g. call it `genes
|
||||
"byzantiumBlock": 0,
|
||||
"constantinopleBlock": 0,
|
||||
"petersburgBlock": 0,
|
||||
"istanbulBlock": 0
|
||||
"istanbulBlock": 0,
|
||||
"berlinBlock": 0
|
||||
},
|
||||
"alloc": {},
|
||||
"coinbase": "0x0000000000000000000000000000000000000000",
|
||||
@@ -277,7 +280,7 @@ $ bootnode --genkey=boot.key
|
||||
$ bootnode --nodekey=boot.key
|
||||
```
|
||||
|
||||
With the bootnode online, it will display an [`enode` URL](https://github.com/ethereum/wiki/wiki/enode-url-format)
|
||||
With the bootnode online, it will display an [`enode` URL](https://eth.wiki/en/fundamentals/enode-url-format)
|
||||
that other nodes can use to connect to it and exchange peer information. Make sure to
|
||||
replace the displayed IP address information (most probably `[::]`) with your externally
|
||||
accessible IP to get the actual `enode` URL.
|
||||
@@ -314,13 +317,13 @@ ones either). To start a `geth` instance for mining, run it with all your usual
|
||||
by:
|
||||
|
||||
```shell
|
||||
$ geth <usual-flags> --mine --miner.threads=1 --etherbase=0x0000000000000000000000000000000000000000
|
||||
$ geth <usual-flags> --mine --miner.threads=1 --miner.etherbase=0x0000000000000000000000000000000000000000
|
||||
```
|
||||
|
||||
Which will start mining blocks and transactions on a single CPU thread, crediting all
|
||||
proceedings to the account specified by `--etherbase`. You can further tune the mining
|
||||
by changing the default gas limit blocks converge to (`--targetgaslimit`) and the price
|
||||
transactions are accepted at (`--gasprice`).
|
||||
proceedings to the account specified by `--miner.etherbase`. You can further tune the mining
|
||||
by changing the default gas limit blocks converge to (`--miner.targetgaslimit`) and the price
|
||||
transactions are accepted at (`--miner.gasprice`).
|
||||
|
||||
## Contribution
|
||||
|
||||
@@ -329,7 +332,7 @@ from anyone on the internet, and are grateful for even the smallest of fixes!
|
||||
|
||||
If you'd like to contribute to go-ethereum, please fork, fix, commit and send a pull request
|
||||
for the maintainers to review and merge into the main code base. If you wish to submit
|
||||
more complex changes though, please check up with the core devs first on [our gitter channel](https://gitter.im/ethereum/go-ethereum)
|
||||
more complex changes though, please check up with the core devs first on [our Discord Server](https://discord.gg/invite/nthXNEv)
|
||||
to ensure those changes are in line with the general philosophy of the project and/or get
|
||||
some early feedback which can make both your efforts much lighter as well as our review
|
||||
and merge procedures quick and simple.
|
||||
@@ -344,7 +347,7 @@ Please make sure your contributions adhere to our coding guidelines:
|
||||
* Commit messages should be prefixed with the package(s) they modify.
|
||||
* E.g. "eth, rpc: make trace configs optional"
|
||||
|
||||
Please see the [Developers' Guide](https://github.com/ethereum/go-ethereum/wiki/Developers'-Guide)
|
||||
Please see the [Developers' Guide](https://geth.ethereum.org/docs/developers/devguide)
|
||||
for more details on configuring your environment, managing project dependencies, and
|
||||
testing procedures.
|
||||
|
||||
|
10
SECURITY.md
10
SECURITY.md
@@ -2,31 +2,29 @@
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Please see Releases. We recommend to use the most recent released version.
|
||||
Please see [Releases](https://github.com/ethereum/go-ethereum/releases). We recommend using the [most recently released version](https://github.com/ethereum/go-ethereum/releases/latest).
|
||||
|
||||
## Audit reports
|
||||
|
||||
Audit reports are published in the `docs` folder: https://github.com/ethereum/go-ethereum/tree/master/docs/audits
|
||||
|
||||
|
||||
| Scope | Date | Report Link |
|
||||
| ------- | ------- | ----------- |
|
||||
| `geth` | 20170425 | [pdf](https://github.com/ethereum/go-ethereum/blob/master/docs/audits/2017-04-25_Geth-audit_Truesec.pdf) |
|
||||
| `clef` | 20180914 | [pdf](https://github.com/ethereum/go-ethereum/blob/master/docs/audits/2018-09-14_Clef-audit_NCC.pdf) |
|
||||
|
||||
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
**Please do not file a public ticket** mentioning the vulnerability.
|
||||
|
||||
To find out how to disclose a vulnerability in Ethereum visit [https://bounty.ethereum.org](https://bounty.ethereum.org) or email bounty@ethereum.org.
|
||||
To find out how to disclose a vulnerability in Ethereum visit [https://bounty.ethereum.org](https://bounty.ethereum.org) or email bounty@ethereum.org. Please read the [disclosure page](https://github.com/ethereum/go-ethereum/security/advisories?state=published) for more information about publically disclosed security vulnerabilities.
|
||||
|
||||
Use the built-in `geth version-check` feature to check whether the software is affected by any known vulnerability. This command will fetch the latest [`vulnerabilities.json`](https://geth.ethereum.org/docs/vulnerabilities/vulnerabilities.json) file which contains known security vulnerabilities concerning `geth`, and cross-check the data against its own version number.
|
||||
|
||||
The following key may be used to communicate sensitive information to developers.
|
||||
|
||||
Fingerprint: `AE96 ED96 9E47 9B00 84F3 E17F E88D 3334 FA5F 6A0A`
|
||||
|
||||
|
||||
```
|
||||
-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
Version: GnuPG v1
|
||||
|
@@ -43,6 +43,7 @@ const jsondata = `
|
||||
{ "type" : "function", "name" : "uint64[2]", "inputs" : [ { "name" : "inputs", "type" : "uint64[2]" } ] },
|
||||
{ "type" : "function", "name" : "uint64[]", "inputs" : [ { "name" : "inputs", "type" : "uint64[]" } ] },
|
||||
{ "type" : "function", "name" : "int8", "inputs" : [ { "name" : "inputs", "type" : "int8" } ] },
|
||||
{ "type" : "function", "name" : "bytes32", "inputs" : [ { "name" : "inputs", "type" : "bytes32" } ] },
|
||||
{ "type" : "function", "name" : "foo", "inputs" : [ { "name" : "inputs", "type" : "uint32" } ] },
|
||||
{ "type" : "function", "name" : "bar", "inputs" : [ { "name" : "inputs", "type" : "uint32" }, { "name" : "string", "type" : "uint16" } ] },
|
||||
{ "type" : "function", "name" : "slice", "inputs" : [ { "name" : "inputs", "type" : "uint32[2]" } ] },
|
||||
@@ -68,6 +69,7 @@ var (
|
||||
String, _ = NewType("string", "", nil)
|
||||
Bool, _ = NewType("bool", "", nil)
|
||||
Bytes, _ = NewType("bytes", "", nil)
|
||||
Bytes32, _ = NewType("bytes32", "", nil)
|
||||
Address, _ = NewType("address", "", nil)
|
||||
Uint64Arr, _ = NewType("uint64[]", "", nil)
|
||||
AddressArr, _ = NewType("address[]", "", nil)
|
||||
@@ -98,6 +100,7 @@ var methods = map[string]Method{
|
||||
"uint64[]": NewMethod("uint64[]", "uint64[]", Function, "", false, false, []Argument{{"inputs", Uint64Arr, false}}, nil),
|
||||
"uint64[2]": NewMethod("uint64[2]", "uint64[2]", Function, "", false, false, []Argument{{"inputs", Uint64Arr2, false}}, nil),
|
||||
"int8": NewMethod("int8", "int8", Function, "", false, false, []Argument{{"inputs", Int8, false}}, nil),
|
||||
"bytes32": NewMethod("bytes32", "bytes32", Function, "", false, false, []Argument{{"inputs", Bytes32, false}}, nil),
|
||||
"foo": NewMethod("foo", "foo", Function, "", false, false, []Argument{{"inputs", Uint32, false}}, nil),
|
||||
"bar": NewMethod("bar", "bar", Function, "", false, false, []Argument{{"inputs", Uint32, false}, {"string", Uint16, false}}, nil),
|
||||
"slice": NewMethod("slice", "slice", Function, "", false, false, []Argument{{"inputs", Uint32Arr2, false}}, nil),
|
||||
|
@@ -17,6 +17,7 @@
|
||||
package bind
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"errors"
|
||||
"io"
|
||||
@@ -74,6 +75,7 @@ func NewKeyStoreTransactor(keystore *keystore.KeyStore, account accounts.Account
|
||||
}
|
||||
return tx.WithSignature(signer, signature)
|
||||
},
|
||||
Context: context.Background(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -97,6 +99,7 @@ func NewKeyedTransactor(key *ecdsa.PrivateKey) *TransactOpts {
|
||||
}
|
||||
return tx.WithSignature(signer, signature)
|
||||
},
|
||||
Context: context.Background(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,7 +123,7 @@ func NewKeyStoreTransactorWithChainID(keystore *keystore.KeyStore, account accou
|
||||
if chainID == nil {
|
||||
return nil, ErrNoChainID
|
||||
}
|
||||
signer := types.NewEIP155Signer(chainID)
|
||||
signer := types.LatestSignerForChainID(chainID)
|
||||
return &TransactOpts{
|
||||
From: account.Address,
|
||||
Signer: func(address common.Address, tx *types.Transaction) (*types.Transaction, error) {
|
||||
@@ -133,6 +136,7 @@ func NewKeyStoreTransactorWithChainID(keystore *keystore.KeyStore, account accou
|
||||
}
|
||||
return tx.WithSignature(signer, signature)
|
||||
},
|
||||
Context: context.Background(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -143,7 +147,7 @@ func NewKeyedTransactorWithChainID(key *ecdsa.PrivateKey, chainID *big.Int) (*Tr
|
||||
if chainID == nil {
|
||||
return nil, ErrNoChainID
|
||||
}
|
||||
signer := types.NewEIP155Signer(chainID)
|
||||
signer := types.LatestSignerForChainID(chainID)
|
||||
return &TransactOpts{
|
||||
From: keyAddr,
|
||||
Signer: func(address common.Address, tx *types.Transaction) (*types.Transaction, error) {
|
||||
@@ -156,6 +160,7 @@ func NewKeyedTransactorWithChainID(key *ecdsa.PrivateKey, chainID *big.Int) (*Tr
|
||||
}
|
||||
return tx.WithSignature(signer, signature)
|
||||
},
|
||||
Context: context.Background(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -170,5 +175,6 @@ func NewClefTransactor(clef *external.ExternalSigner, account accounts.Account)
|
||||
}
|
||||
return clef.SignTx(account, transaction, nil) // Clef enforces its own chain id
|
||||
},
|
||||
Context: context.Background(),
|
||||
}
|
||||
}
|
||||
|
@@ -32,12 +32,12 @@ var (
|
||||
// have any code associated with it (i.e. suicided).
|
||||
ErrNoCode = errors.New("no contract code at given address")
|
||||
|
||||
// This error is raised when attempting to perform a pending state action
|
||||
// ErrNoPendingState is raised when attempting to perform a pending state action
|
||||
// on a backend that doesn't implement PendingContractCaller.
|
||||
ErrNoPendingState = errors.New("backend does not support pending state")
|
||||
|
||||
// This error is returned by WaitDeployed if contract creation leaves an
|
||||
// empty contract behind.
|
||||
// ErrNoCodeAfterDeploy is returned by WaitDeployed if contract creation leaves
|
||||
// an empty contract behind.
|
||||
ErrNoCodeAfterDeploy = errors.New("no contract code after deployment")
|
||||
)
|
||||
|
||||
@@ -47,7 +47,8 @@ type ContractCaller interface {
|
||||
// CodeAt returns the code of the given account. This is needed to differentiate
|
||||
// between contract internal errors and the local chain being out of sync.
|
||||
CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error)
|
||||
// ContractCall executes an Ethereum contract call with the specified data as the
|
||||
|
||||
// CallContract executes an Ethereum contract call with the specified data as the
|
||||
// input.
|
||||
CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error)
|
||||
}
|
||||
@@ -58,6 +59,7 @@ type ContractCaller interface {
|
||||
type PendingContractCaller interface {
|
||||
// PendingCodeAt returns the code of the given account in the pending state.
|
||||
PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error)
|
||||
|
||||
// PendingCallContract executes an Ethereum contract call against the pending state.
|
||||
PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error)
|
||||
}
|
||||
@@ -67,19 +69,31 @@ type PendingContractCaller interface {
|
||||
// used when the user does not provide some needed values, but rather leaves it up
|
||||
// to the transactor to decide.
|
||||
type ContractTransactor interface {
|
||||
// HeaderByNumber returns a block header from the current canonical chain. If
|
||||
// number is nil, the latest known header is returned.
|
||||
HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error)
|
||||
|
||||
// PendingCodeAt returns the code of the given account in the pending state.
|
||||
PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error)
|
||||
|
||||
// PendingNonceAt retrieves the current pending nonce associated with an account.
|
||||
PendingNonceAt(ctx context.Context, account common.Address) (uint64, error)
|
||||
|
||||
// SuggestGasPrice retrieves the currently suggested gas price to allow a timely
|
||||
// execution of a transaction.
|
||||
SuggestGasPrice(ctx context.Context) (*big.Int, error)
|
||||
|
||||
// SuggestGasTipCap retrieves the currently suggested 1559 priority fee to allow
|
||||
// a timely execution of a transaction.
|
||||
SuggestGasTipCap(ctx context.Context) (*big.Int, error)
|
||||
|
||||
// EstimateGas tries to estimate the gas needed to execute a specific
|
||||
// transaction based on the current pending state of the backend blockchain.
|
||||
// There is no guarantee that this is the true gas limit requirement as other
|
||||
// transactions may be added or removed by miners, but it should provide a basis
|
||||
// for setting a reasonable default.
|
||||
EstimateGas(ctx context.Context, call ethereum.CallMsg) (gas uint64, err error)
|
||||
|
||||
// SendTransaction injects the transaction into the pending pool for execution.
|
||||
SendTransaction(ctx context.Context, tx *types.Transaction) error
|
||||
}
|
||||
|
@@ -86,7 +86,7 @@ func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.Genesis
|
||||
config: genesis.Config,
|
||||
events: filters.NewEventSystem(&filterBackend{database, blockchain}, false),
|
||||
}
|
||||
backend.rollback()
|
||||
backend.rollback(blockchain.CurrentBlock())
|
||||
return backend
|
||||
}
|
||||
|
||||
@@ -112,7 +112,9 @@ func (b *SimulatedBackend) Commit() {
|
||||
if _, err := b.blockchain.InsertChain([]*types.Block{b.pendingBlock}); err != nil {
|
||||
panic(err) // This cannot happen unless the simulator is wrong, fail in that case
|
||||
}
|
||||
b.rollback()
|
||||
// Using the last inserted block here makes it possible to build on a side
|
||||
// chain after a fork.
|
||||
b.rollback(b.pendingBlock)
|
||||
}
|
||||
|
||||
// Rollback aborts all pending transactions, reverting to the last committed state.
|
||||
@@ -120,15 +122,41 @@ func (b *SimulatedBackend) Rollback() {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
b.rollback()
|
||||
b.rollback(b.blockchain.CurrentBlock())
|
||||
}
|
||||
|
||||
func (b *SimulatedBackend) rollback() {
|
||||
blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(int, *core.BlockGen) {})
|
||||
stateDB, _ := b.blockchain.State()
|
||||
func (b *SimulatedBackend) rollback(parent *types.Block) {
|
||||
blocks, _ := core.GenerateChain(b.config, parent, ethash.NewFaker(), b.database, 1, func(int, *core.BlockGen) {})
|
||||
|
||||
b.pendingBlock = blocks[0]
|
||||
b.pendingState, _ = state.New(b.pendingBlock.Root(), stateDB.Database(), nil)
|
||||
b.pendingState, _ = state.New(b.pendingBlock.Root(), b.blockchain.StateCache(), nil)
|
||||
}
|
||||
|
||||
// Fork creates a side-chain that can be used to simulate reorgs.
|
||||
//
|
||||
// This function should be called with the ancestor block where the new side
|
||||
// chain should be started. Transactions (old and new) can then be applied on
|
||||
// top and Commit-ed.
|
||||
//
|
||||
// Note, the side-chain will only become canonical (and trigger the events) when
|
||||
// it becomes longer. Until then CallContract will still operate on the current
|
||||
// canonical chain.
|
||||
//
|
||||
// There is a % chance that the side chain becomes canonical at the same length
|
||||
// to simulate live network behavior.
|
||||
func (b *SimulatedBackend) Fork(ctx context.Context, parent common.Hash) error {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
if len(b.pendingBlock.Transactions()) != 0 {
|
||||
return errors.New("pending block dirty")
|
||||
}
|
||||
block, err := b.blockByHash(ctx, parent)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b.rollback(block)
|
||||
return nil
|
||||
}
|
||||
|
||||
// stateByBlockNumber retrieves a state by a given blocknumber.
|
||||
@@ -136,7 +164,7 @@ func (b *SimulatedBackend) stateByBlockNumber(ctx context.Context, blockNumber *
|
||||
if blockNumber == nil || blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) == 0 {
|
||||
return b.blockchain.State()
|
||||
}
|
||||
block, err := b.blockByNumberNoLock(ctx, blockNumber)
|
||||
block, err := b.blockByNumber(ctx, blockNumber)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -229,6 +257,11 @@ func (b *SimulatedBackend) BlockByHash(ctx context.Context, hash common.Hash) (*
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
return b.blockByHash(ctx, hash)
|
||||
}
|
||||
|
||||
// blockByHash retrieves a block based on the block hash without Locking.
|
||||
func (b *SimulatedBackend) blockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
|
||||
if hash == b.pendingBlock.Hash() {
|
||||
return b.pendingBlock, nil
|
||||
}
|
||||
@@ -247,12 +280,12 @@ func (b *SimulatedBackend) BlockByNumber(ctx context.Context, number *big.Int) (
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
return b.blockByNumberNoLock(ctx, number)
|
||||
return b.blockByNumber(ctx, number)
|
||||
}
|
||||
|
||||
// blockByNumberNoLock retrieves a block from the database by number, caching it
|
||||
// blockByNumber retrieves a block from the database by number, caching it
|
||||
// (associated with its hash) if found without Lock.
|
||||
func (b *SimulatedBackend) blockByNumberNoLock(ctx context.Context, number *big.Int) (*types.Block, error) {
|
||||
func (b *SimulatedBackend) blockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
|
||||
if number == nil || number.Cmp(b.pendingBlock.Number()) == 0 {
|
||||
return b.blockchain.CurrentBlock(), nil
|
||||
}
|
||||
@@ -432,6 +465,12 @@ func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error
|
||||
return big.NewInt(1), nil
|
||||
}
|
||||
|
||||
// SuggestGasTipCap implements ContractTransactor.SuggestGasTipCap. Since the simulated
|
||||
// chain doesn't have miners, we just return a gas tip of 1 for any call.
|
||||
func (b *SimulatedBackend) SuggestGasTipCap(ctx context.Context) (*big.Int, error) {
|
||||
return big.NewInt(1), nil
|
||||
}
|
||||
|
||||
// EstimateGas executes the requested code against the currently pending block/state and
|
||||
// returns the used amount of gas.
|
||||
func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) {
|
||||
@@ -449,8 +488,19 @@ func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMs
|
||||
} else {
|
||||
hi = b.pendingBlock.GasLimit()
|
||||
}
|
||||
// Normalize the max fee per gas the call is willing to spend.
|
||||
var feeCap *big.Int
|
||||
if call.GasPrice != nil && (call.GasFeeCap != nil || call.GasTipCap != nil) {
|
||||
return 0, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
|
||||
} else if call.GasPrice != nil {
|
||||
feeCap = call.GasPrice
|
||||
} else if call.GasFeeCap != nil {
|
||||
feeCap = call.GasFeeCap
|
||||
} else {
|
||||
feeCap = common.Big0
|
||||
}
|
||||
// Recap the highest gas allowance with account's balance.
|
||||
if call.GasPrice != nil && call.GasPrice.BitLen() != 0 {
|
||||
if feeCap.BitLen() != 0 {
|
||||
balance := b.pendingState.GetBalance(call.From) // from can't be nil
|
||||
available := new(big.Int).Set(balance)
|
||||
if call.Value != nil {
|
||||
@@ -459,14 +509,14 @@ func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMs
|
||||
}
|
||||
available.Sub(available, call.Value)
|
||||
}
|
||||
allowance := new(big.Int).Div(available, call.GasPrice)
|
||||
allowance := new(big.Int).Div(available, feeCap)
|
||||
if allowance.IsUint64() && hi > allowance.Uint64() {
|
||||
transfer := call.Value
|
||||
if transfer == nil {
|
||||
transfer = new(big.Int)
|
||||
}
|
||||
log.Warn("Gas estimation capped by limited funds", "original", hi, "balance", balance,
|
||||
"sent", transfer, "gasprice", call.GasPrice, "fundable", allowance)
|
||||
"sent", transfer, "feecap", feeCap, "fundable", allowance)
|
||||
hi = allowance.Uint64()
|
||||
}
|
||||
}
|
||||
@@ -528,10 +578,38 @@ func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMs
|
||||
// callContract implements common code between normal and pending contract calls.
|
||||
// state is modified during execution, make sure to copy it if necessary.
|
||||
func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, stateDB *state.StateDB) (*core.ExecutionResult, error) {
|
||||
// Ensure message is initialized properly.
|
||||
if call.GasPrice == nil {
|
||||
call.GasPrice = big.NewInt(1)
|
||||
// Gas prices post 1559 need to be initialized
|
||||
if call.GasPrice != nil && (call.GasFeeCap != nil || call.GasTipCap != nil) {
|
||||
return nil, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
|
||||
}
|
||||
head := b.blockchain.CurrentHeader()
|
||||
if !b.blockchain.Config().IsLondon(head.Number) {
|
||||
// If there's no basefee, then it must be a non-1559 execution
|
||||
if call.GasPrice == nil {
|
||||
call.GasPrice = new(big.Int)
|
||||
}
|
||||
call.GasFeeCap, call.GasTipCap = call.GasPrice, call.GasPrice
|
||||
} else {
|
||||
// A basefee is provided, necessitating 1559-type execution
|
||||
if call.GasPrice != nil {
|
||||
// User specified the legacy gas field, convert to 1559 gas typing
|
||||
call.GasFeeCap, call.GasTipCap = call.GasPrice, call.GasPrice
|
||||
} else {
|
||||
// User specified 1559 gas feilds (or none), use those
|
||||
if call.GasFeeCap == nil {
|
||||
call.GasFeeCap = new(big.Int)
|
||||
}
|
||||
if call.GasTipCap == nil {
|
||||
call.GasTipCap = new(big.Int)
|
||||
}
|
||||
// Backfill the legacy gasPrice for EVM execution, unless we're all zeroes
|
||||
call.GasPrice = new(big.Int)
|
||||
if call.GasFeeCap.BitLen() > 0 || call.GasTipCap.BitLen() > 0 {
|
||||
call.GasPrice = math.BigMin(new(big.Int).Add(call.GasTipCap, head.BaseFee), call.GasFeeCap)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Ensure message is initialized properly.
|
||||
if call.Gas == 0 {
|
||||
call.Gas = 50000000
|
||||
}
|
||||
@@ -548,7 +626,7 @@ func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallM
|
||||
evmContext := core.NewEVMBlockContext(block.Header(), b.blockchain, nil)
|
||||
// Create a new environment which holds all relevant information
|
||||
// about the transaction and calling mechanisms.
|
||||
vmEnv := vm.NewEVM(evmContext, txContext, stateDB, b.config, vm.Config{})
|
||||
vmEnv := vm.NewEVM(evmContext, txContext, stateDB, b.config, vm.Config{NoBaseFee: true})
|
||||
gasPool := new(core.GasPool).AddGas(math.MaxUint64)
|
||||
|
||||
return core.NewStateTransition(vmEnv, msg, gasPool).TransitionDb()
|
||||
@@ -560,7 +638,14 @@ func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transa
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
sender, err := types.Sender(types.NewEIP155Signer(b.config.ChainID), tx)
|
||||
// Get the last block
|
||||
block, err := b.blockByHash(ctx, b.pendingBlock.ParentHash())
|
||||
if err != nil {
|
||||
panic("could not fetch parent")
|
||||
}
|
||||
// Check transaction validity
|
||||
signer := types.MakeSigner(b.blockchain.Config(), block.Number())
|
||||
sender, err := types.Sender(signer, tx)
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("invalid transaction: %v", err))
|
||||
}
|
||||
@@ -568,8 +653,8 @@ func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transa
|
||||
if tx.Nonce() != nonce {
|
||||
panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce))
|
||||
}
|
||||
|
||||
blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
|
||||
// Include tx in chain
|
||||
blocks, _ := core.GenerateChain(b.config, block, ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
|
||||
for _, tx := range b.pendingBlock.Transactions() {
|
||||
block.AddTxWithChain(b.blockchain, tx)
|
||||
}
|
||||
@@ -708,14 +793,17 @@ type callMsg struct {
|
||||
ethereum.CallMsg
|
||||
}
|
||||
|
||||
func (m callMsg) From() common.Address { return m.CallMsg.From }
|
||||
func (m callMsg) Nonce() uint64 { return 0 }
|
||||
func (m callMsg) CheckNonce() bool { return false }
|
||||
func (m callMsg) To() *common.Address { return m.CallMsg.To }
|
||||
func (m callMsg) GasPrice() *big.Int { return m.CallMsg.GasPrice }
|
||||
func (m callMsg) Gas() uint64 { return m.CallMsg.Gas }
|
||||
func (m callMsg) Value() *big.Int { return m.CallMsg.Value }
|
||||
func (m callMsg) Data() []byte { return m.CallMsg.Data }
|
||||
func (m callMsg) From() common.Address { return m.CallMsg.From }
|
||||
func (m callMsg) Nonce() uint64 { return 0 }
|
||||
func (m callMsg) IsFake() bool { return true }
|
||||
func (m callMsg) To() *common.Address { return m.CallMsg.To }
|
||||
func (m callMsg) GasPrice() *big.Int { return m.CallMsg.GasPrice }
|
||||
func (m callMsg) GasFeeCap() *big.Int { return m.CallMsg.GasFeeCap }
|
||||
func (m callMsg) GasTipCap() *big.Int { return m.CallMsg.GasTipCap }
|
||||
func (m callMsg) Gas() uint64 { return m.CallMsg.Gas }
|
||||
func (m callMsg) Value() *big.Int { return m.CallMsg.Value }
|
||||
func (m callMsg) Data() []byte { return m.CallMsg.Data }
|
||||
func (m callMsg) AccessList() types.AccessList { return m.CallMsg.AccessList }
|
||||
|
||||
// filterBackend implements filters.Backend to support filtering for logs without
|
||||
// taking bloom-bits acceleration structures into account.
|
||||
|
@@ -21,6 +21,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"math/big"
|
||||
"math/rand"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -58,9 +59,12 @@ func TestSimulatedBackend(t *testing.T) {
|
||||
}
|
||||
|
||||
// generate a transaction and confirm you can retrieve it
|
||||
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
||||
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
||||
|
||||
code := `6060604052600a8060106000396000f360606040526008565b00`
|
||||
var gas uint64 = 3000000
|
||||
tx := types.NewContractCreation(0, big.NewInt(0), gas, big.NewInt(1), common.FromHex(code))
|
||||
tx := types.NewContractCreation(0, big.NewInt(0), gas, gasPrice, common.FromHex(code))
|
||||
tx, _ = types.SignTx(tx, types.HomesteadSigner{}, key)
|
||||
|
||||
err = sim.SendTransaction(context.Background(), tx)
|
||||
@@ -110,14 +114,14 @@ var expectedReturn = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
|
||||
func simTestBackend(testAddr common.Address) *SimulatedBackend {
|
||||
return NewSimulatedBackend(
|
||||
core.GenesisAlloc{
|
||||
testAddr: {Balance: big.NewInt(10000000000)},
|
||||
testAddr: {Balance: big.NewInt(10000000000000000)},
|
||||
}, 10000000,
|
||||
)
|
||||
}
|
||||
|
||||
func TestNewSimulatedBackend(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
expectedBal := big.NewInt(10000000000)
|
||||
expectedBal := big.NewInt(10000000000000000)
|
||||
sim := simTestBackend(testAddr)
|
||||
defer sim.Close()
|
||||
|
||||
@@ -136,7 +140,7 @@ func TestNewSimulatedBackend(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_AdjustTime(t *testing.T) {
|
||||
func TestAdjustTime(t *testing.T) {
|
||||
sim := NewSimulatedBackend(
|
||||
core.GenesisAlloc{}, 10000000,
|
||||
)
|
||||
@@ -153,11 +157,15 @@ func TestSimulatedBackend_AdjustTime(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewSimulatedBackend_AdjustTimeFail(t *testing.T) {
|
||||
func TestNewAdjustTimeFail(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
sim := simTestBackend(testAddr)
|
||||
|
||||
// Create tx and send
|
||||
tx := types.NewTransaction(0, testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
|
||||
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
||||
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
||||
|
||||
tx := types.NewTransaction(0, testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
||||
signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
||||
if err != nil {
|
||||
t.Errorf("could not sign tx: %v", err)
|
||||
@@ -178,7 +186,7 @@ func TestNewSimulatedBackend_AdjustTimeFail(t *testing.T) {
|
||||
t.Errorf("adjusted time not equal to a minute. prev: %v, new: %v", prevTime, newTime)
|
||||
}
|
||||
// Put a transaction after adjusting time
|
||||
tx2 := types.NewTransaction(1, testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
|
||||
tx2 := types.NewTransaction(1, testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
||||
signedTx2, err := types.SignTx(tx2, types.HomesteadSigner{}, testKey)
|
||||
if err != nil {
|
||||
t.Errorf("could not sign tx: %v", err)
|
||||
@@ -191,9 +199,9 @@ func TestNewSimulatedBackend_AdjustTimeFail(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_BalanceAt(t *testing.T) {
|
||||
func TestBalanceAt(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
expectedBal := big.NewInt(10000000000)
|
||||
expectedBal := big.NewInt(10000000000000000)
|
||||
sim := simTestBackend(testAddr)
|
||||
defer sim.Close()
|
||||
bgCtx := context.Background()
|
||||
@@ -208,7 +216,7 @@ func TestSimulatedBackend_BalanceAt(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_BlockByHash(t *testing.T) {
|
||||
func TestBlockByHash(t *testing.T) {
|
||||
sim := NewSimulatedBackend(
|
||||
core.GenesisAlloc{}, 10000000,
|
||||
)
|
||||
@@ -229,7 +237,7 @@ func TestSimulatedBackend_BlockByHash(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_BlockByNumber(t *testing.T) {
|
||||
func TestBlockByNumber(t *testing.T) {
|
||||
sim := NewSimulatedBackend(
|
||||
core.GenesisAlloc{}, 10000000,
|
||||
)
|
||||
@@ -264,7 +272,7 @@ func TestSimulatedBackend_BlockByNumber(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_NonceAt(t *testing.T) {
|
||||
func TestNonceAt(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
|
||||
sim := simTestBackend(testAddr)
|
||||
@@ -281,7 +289,10 @@ func TestSimulatedBackend_NonceAt(t *testing.T) {
|
||||
}
|
||||
|
||||
// create a signed transaction to send
|
||||
tx := types.NewTransaction(nonce, testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
|
||||
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
||||
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
||||
|
||||
tx := types.NewTransaction(nonce, testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
||||
signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
||||
if err != nil {
|
||||
t.Errorf("could not sign tx: %v", err)
|
||||
@@ -314,7 +325,7 @@ func TestSimulatedBackend_NonceAt(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_SendTransaction(t *testing.T) {
|
||||
func TestSendTransaction(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
|
||||
sim := simTestBackend(testAddr)
|
||||
@@ -322,7 +333,10 @@ func TestSimulatedBackend_SendTransaction(t *testing.T) {
|
||||
bgCtx := context.Background()
|
||||
|
||||
// create a signed transaction to send
|
||||
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
|
||||
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
||||
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
||||
|
||||
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
||||
signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
||||
if err != nil {
|
||||
t.Errorf("could not sign tx: %v", err)
|
||||
@@ -345,19 +359,22 @@ func TestSimulatedBackend_SendTransaction(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_TransactionByHash(t *testing.T) {
|
||||
func TestTransactionByHash(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
|
||||
sim := NewSimulatedBackend(
|
||||
core.GenesisAlloc{
|
||||
testAddr: {Balance: big.NewInt(10000000000)},
|
||||
testAddr: {Balance: big.NewInt(10000000000000000)},
|
||||
}, 10000000,
|
||||
)
|
||||
defer sim.Close()
|
||||
bgCtx := context.Background()
|
||||
|
||||
// create a signed transaction to send
|
||||
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
|
||||
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
||||
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
||||
|
||||
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
||||
signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
||||
if err != nil {
|
||||
t.Errorf("could not sign tx: %v", err)
|
||||
@@ -396,7 +413,7 @@ func TestSimulatedBackend_TransactionByHash(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_EstimateGas(t *testing.T) {
|
||||
func TestEstimateGas(t *testing.T) {
|
||||
/*
|
||||
pragma solidity ^0.6.4;
|
||||
contract GasEstimation {
|
||||
@@ -514,7 +531,7 @@ func TestSimulatedBackend_EstimateGas(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_EstimateGasWithPrice(t *testing.T) {
|
||||
func TestEstimateGasWithPrice(t *testing.T) {
|
||||
key, _ := crypto.GenerateKey()
|
||||
addr := crypto.PubkeyToAddress(key.PublicKey)
|
||||
|
||||
@@ -533,7 +550,7 @@ func TestSimulatedBackend_EstimateGasWithPrice(t *testing.T) {
|
||||
To: &recipient,
|
||||
Gas: 0,
|
||||
GasPrice: big.NewInt(0),
|
||||
Value: big.NewInt(1000),
|
||||
Value: big.NewInt(100000000000),
|
||||
Data: nil,
|
||||
}, 21000, nil},
|
||||
|
||||
@@ -541,8 +558,8 @@ func TestSimulatedBackend_EstimateGasWithPrice(t *testing.T) {
|
||||
From: addr,
|
||||
To: &recipient,
|
||||
Gas: 0,
|
||||
GasPrice: big.NewInt(1000),
|
||||
Value: big.NewInt(1000),
|
||||
GasPrice: big.NewInt(100000000000),
|
||||
Value: big.NewInt(100000000000),
|
||||
Data: nil,
|
||||
}, 21000, nil},
|
||||
|
||||
@@ -560,28 +577,51 @@ func TestSimulatedBackend_EstimateGasWithPrice(t *testing.T) {
|
||||
To: &recipient,
|
||||
Gas: 0,
|
||||
GasPrice: big.NewInt(2e14), // gascost = 4.2ether
|
||||
Value: big.NewInt(1000),
|
||||
Value: big.NewInt(100000000000),
|
||||
Data: nil,
|
||||
}, 21000, errors.New("gas required exceeds allowance (10999)")}, // 10999=(2.2ether-1000wei)/(2e14)
|
||||
|
||||
{"EstimateEIP1559WithHighFees", ethereum.CallMsg{
|
||||
From: addr,
|
||||
To: &addr,
|
||||
Gas: 0,
|
||||
GasFeeCap: big.NewInt(1e14), // maxgascost = 2.1ether
|
||||
GasTipCap: big.NewInt(1),
|
||||
Value: big.NewInt(1e17), // the remaining balance for fee is 2.1ether
|
||||
Data: nil,
|
||||
}, params.TxGas, nil},
|
||||
|
||||
{"EstimateEIP1559WithSuperHighFees", ethereum.CallMsg{
|
||||
From: addr,
|
||||
To: &addr,
|
||||
Gas: 0,
|
||||
GasFeeCap: big.NewInt(1e14), // maxgascost = 2.1ether
|
||||
GasTipCap: big.NewInt(1),
|
||||
Value: big.NewInt(1e17 + 1), // the remaining balance for fee is 2.1ether
|
||||
Data: nil,
|
||||
}, params.TxGas, errors.New("gas required exceeds allowance (20999)")}, // 20999=(2.2ether-0.1ether-1wei)/(1e14)
|
||||
}
|
||||
for _, c := range cases {
|
||||
for i, c := range cases {
|
||||
got, err := sim.EstimateGas(context.Background(), c.message)
|
||||
if c.expectError != nil {
|
||||
if err == nil {
|
||||
t.Fatalf("Expect error, got nil")
|
||||
t.Fatalf("test %d: expect error, got nil", i)
|
||||
}
|
||||
if c.expectError.Error() != err.Error() {
|
||||
t.Fatalf("Expect error, want %v, got %v", c.expectError, err)
|
||||
t.Fatalf("test %d: expect error, want %v, got %v", i, c.expectError, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if c.expectError == nil && err != nil {
|
||||
t.Fatalf("test %d: didn't expect error, got %v", i, err)
|
||||
}
|
||||
if got != c.expect {
|
||||
t.Fatalf("Gas estimation mismatch, want %d, got %d", c.expect, got)
|
||||
t.Fatalf("test %d: gas estimation mismatch, want %d, got %d", i, c.expect, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_HeaderByHash(t *testing.T) {
|
||||
func TestHeaderByHash(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
|
||||
sim := simTestBackend(testAddr)
|
||||
@@ -602,7 +642,7 @@ func TestSimulatedBackend_HeaderByHash(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_HeaderByNumber(t *testing.T) {
|
||||
func TestHeaderByNumber(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
|
||||
sim := simTestBackend(testAddr)
|
||||
@@ -649,7 +689,7 @@ func TestSimulatedBackend_HeaderByNumber(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_TransactionCount(t *testing.T) {
|
||||
func TestTransactionCount(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
|
||||
sim := simTestBackend(testAddr)
|
||||
@@ -668,9 +708,11 @@ func TestSimulatedBackend_TransactionCount(t *testing.T) {
|
||||
if count != 0 {
|
||||
t.Errorf("expected transaction count of %v does not match actual count of %v", 0, count)
|
||||
}
|
||||
|
||||
// create a signed transaction to send
|
||||
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
|
||||
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
||||
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
||||
|
||||
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
||||
signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
||||
if err != nil {
|
||||
t.Errorf("could not sign tx: %v", err)
|
||||
@@ -699,7 +741,7 @@ func TestSimulatedBackend_TransactionCount(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_TransactionInBlock(t *testing.T) {
|
||||
func TestTransactionInBlock(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
|
||||
sim := simTestBackend(testAddr)
|
||||
@@ -723,9 +765,11 @@ func TestSimulatedBackend_TransactionInBlock(t *testing.T) {
|
||||
if pendingNonce != uint64(0) {
|
||||
t.Errorf("expected pending nonce of 0 got %v", pendingNonce)
|
||||
}
|
||||
|
||||
// create a signed transaction to send
|
||||
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
|
||||
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
||||
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
||||
|
||||
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
||||
signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
||||
if err != nil {
|
||||
t.Errorf("could not sign tx: %v", err)
|
||||
@@ -762,7 +806,7 @@ func TestSimulatedBackend_TransactionInBlock(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_PendingNonceAt(t *testing.T) {
|
||||
func TestPendingNonceAt(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
|
||||
sim := simTestBackend(testAddr)
|
||||
@@ -780,7 +824,10 @@ func TestSimulatedBackend_PendingNonceAt(t *testing.T) {
|
||||
}
|
||||
|
||||
// create a signed transaction to send
|
||||
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
|
||||
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
||||
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
||||
|
||||
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
||||
signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
||||
if err != nil {
|
||||
t.Errorf("could not sign tx: %v", err)
|
||||
@@ -803,7 +850,7 @@ func TestSimulatedBackend_PendingNonceAt(t *testing.T) {
|
||||
}
|
||||
|
||||
// make a new transaction with a nonce of 1
|
||||
tx = types.NewTransaction(uint64(1), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
|
||||
tx = types.NewTransaction(uint64(1), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
||||
signedTx, err = types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
||||
if err != nil {
|
||||
t.Errorf("could not sign tx: %v", err)
|
||||
@@ -824,7 +871,7 @@ func TestSimulatedBackend_PendingNonceAt(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_TransactionReceipt(t *testing.T) {
|
||||
func TestTransactionReceipt(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
|
||||
sim := simTestBackend(testAddr)
|
||||
@@ -832,7 +879,10 @@ func TestSimulatedBackend_TransactionReceipt(t *testing.T) {
|
||||
bgCtx := context.Background()
|
||||
|
||||
// create a signed transaction to send
|
||||
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
|
||||
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
||||
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
||||
|
||||
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
||||
signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
||||
if err != nil {
|
||||
t.Errorf("could not sign tx: %v", err)
|
||||
@@ -855,7 +905,7 @@ func TestSimulatedBackend_TransactionReceipt(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_SuggestGasPrice(t *testing.T) {
|
||||
func TestSuggestGasPrice(t *testing.T) {
|
||||
sim := NewSimulatedBackend(
|
||||
core.GenesisAlloc{},
|
||||
10000000,
|
||||
@@ -871,7 +921,7 @@ func TestSimulatedBackend_SuggestGasPrice(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_PendingCodeAt(t *testing.T) {
|
||||
func TestPendingCodeAt(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
sim := simTestBackend(testAddr)
|
||||
defer sim.Close()
|
||||
@@ -907,7 +957,7 @@ func TestSimulatedBackend_PendingCodeAt(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatedBackend_CodeAt(t *testing.T) {
|
||||
func TestCodeAt(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
sim := simTestBackend(testAddr)
|
||||
defer sim.Close()
|
||||
@@ -946,7 +996,7 @@ func TestSimulatedBackend_CodeAt(t *testing.T) {
|
||||
|
||||
// When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt:
|
||||
// receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]}
|
||||
func TestSimulatedBackend_PendingAndCallContract(t *testing.T) {
|
||||
func TestPendingAndCallContract(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
sim := simTestBackend(testAddr)
|
||||
defer sim.Close()
|
||||
@@ -1030,7 +1080,7 @@ contract Reverter {
|
||||
}
|
||||
}
|
||||
}*/
|
||||
func TestSimulatedBackend_CallContractRevert(t *testing.T) {
|
||||
func TestCallContractRevert(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
sim := simTestBackend(testAddr)
|
||||
defer sim.Close()
|
||||
@@ -1114,3 +1164,175 @@ func TestSimulatedBackend_CallContractRevert(t *testing.T) {
|
||||
sim.Commit()
|
||||
}
|
||||
}
|
||||
|
||||
// TestFork check that the chain length after a reorg is correct.
|
||||
// Steps:
|
||||
// 1. Save the current block which will serve as parent for the fork.
|
||||
// 2. Mine n blocks with n ∈ [0, 20].
|
||||
// 3. Assert that the chain length is n.
|
||||
// 4. Fork by using the parent block as ancestor.
|
||||
// 5. Mine n+1 blocks which should trigger a reorg.
|
||||
// 6. Assert that the chain length is n+1.
|
||||
// Since Commit() was called 2n+1 times in total,
|
||||
// having a chain length of just n+1 means that a reorg occurred.
|
||||
func TestFork(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
sim := simTestBackend(testAddr)
|
||||
defer sim.Close()
|
||||
// 1.
|
||||
parent := sim.blockchain.CurrentBlock()
|
||||
// 2.
|
||||
n := int(rand.Int31n(21))
|
||||
for i := 0; i < n; i++ {
|
||||
sim.Commit()
|
||||
}
|
||||
// 3.
|
||||
if sim.blockchain.CurrentBlock().NumberU64() != uint64(n) {
|
||||
t.Error("wrong chain length")
|
||||
}
|
||||
// 4.
|
||||
sim.Fork(context.Background(), parent.Hash())
|
||||
// 5.
|
||||
for i := 0; i < n+1; i++ {
|
||||
sim.Commit()
|
||||
}
|
||||
// 6.
|
||||
if sim.blockchain.CurrentBlock().NumberU64() != uint64(n+1) {
|
||||
t.Error("wrong chain length")
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Example contract to test event emission:
|
||||
|
||||
pragma solidity >=0.7.0 <0.9.0;
|
||||
contract Callable {
|
||||
event Called();
|
||||
function Call() public { emit Called(); }
|
||||
}
|
||||
*/
|
||||
const callableAbi = "[{\"anonymous\":false,\"inputs\":[],\"name\":\"Called\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"Call\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"
|
||||
|
||||
const callableBin = "6080604052348015600f57600080fd5b5060998061001e6000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c806334e2292114602d575b600080fd5b60336035565b005b7f81fab7a4a0aa961db47eefc81f143a5220e8c8495260dd65b1356f1d19d3c7b860405160405180910390a156fea2646970667358221220029436d24f3ac598ceca41d4d712e13ced6d70727f4cdc580667de66d2f51d8b64736f6c63430008010033"
|
||||
|
||||
// TestForkLogsReborn check that the simulated reorgs
|
||||
// correctly remove and reborn logs.
|
||||
// Steps:
|
||||
// 1. Deploy the Callable contract.
|
||||
// 2. Set up an event subscription.
|
||||
// 3. Save the current block which will serve as parent for the fork.
|
||||
// 4. Send a transaction.
|
||||
// 5. Check that the event was included.
|
||||
// 6. Fork by using the parent block as ancestor.
|
||||
// 7. Mine two blocks to trigger a reorg.
|
||||
// 8. Check that the event was removed.
|
||||
// 9. Re-send the transaction and mine a block.
|
||||
// 10. Check that the event was reborn.
|
||||
func TestForkLogsReborn(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
sim := simTestBackend(testAddr)
|
||||
defer sim.Close()
|
||||
// 1.
|
||||
parsed, _ := abi.JSON(strings.NewReader(callableAbi))
|
||||
auth, _ := bind.NewKeyedTransactorWithChainID(testKey, big.NewInt(1337))
|
||||
_, _, contract, err := bind.DeployContract(auth, parsed, common.FromHex(callableBin), sim)
|
||||
if err != nil {
|
||||
t.Errorf("deploying contract: %v", err)
|
||||
}
|
||||
sim.Commit()
|
||||
// 2.
|
||||
logs, sub, err := contract.WatchLogs(nil, "Called")
|
||||
if err != nil {
|
||||
t.Errorf("watching logs: %v", err)
|
||||
}
|
||||
defer sub.Unsubscribe()
|
||||
// 3.
|
||||
parent := sim.blockchain.CurrentBlock()
|
||||
// 4.
|
||||
tx, err := contract.Transact(auth, "Call")
|
||||
if err != nil {
|
||||
t.Errorf("transacting: %v", err)
|
||||
}
|
||||
sim.Commit()
|
||||
// 5.
|
||||
log := <-logs
|
||||
if log.TxHash != tx.Hash() {
|
||||
t.Error("wrong event tx hash")
|
||||
}
|
||||
if log.Removed {
|
||||
t.Error("Event should be included")
|
||||
}
|
||||
// 6.
|
||||
if err := sim.Fork(context.Background(), parent.Hash()); err != nil {
|
||||
t.Errorf("forking: %v", err)
|
||||
}
|
||||
// 7.
|
||||
sim.Commit()
|
||||
sim.Commit()
|
||||
// 8.
|
||||
log = <-logs
|
||||
if log.TxHash != tx.Hash() {
|
||||
t.Error("wrong event tx hash")
|
||||
}
|
||||
if !log.Removed {
|
||||
t.Error("Event should be removed")
|
||||
}
|
||||
// 9.
|
||||
if err := sim.SendTransaction(context.Background(), tx); err != nil {
|
||||
t.Errorf("sending transaction: %v", err)
|
||||
}
|
||||
sim.Commit()
|
||||
// 10.
|
||||
log = <-logs
|
||||
if log.TxHash != tx.Hash() {
|
||||
t.Error("wrong event tx hash")
|
||||
}
|
||||
if log.Removed {
|
||||
t.Error("Event should be included")
|
||||
}
|
||||
}
|
||||
|
||||
// TestForkResendTx checks that re-sending a TX after a fork
|
||||
// is possible and does not cause a "nonce mismatch" panic.
|
||||
// Steps:
|
||||
// 1. Save the current block which will serve as parent for the fork.
|
||||
// 2. Send a transaction.
|
||||
// 3. Check that the TX is included in block 1.
|
||||
// 4. Fork by using the parent block as ancestor.
|
||||
// 5. Mine a block, Re-send the transaction and mine another one.
|
||||
// 6. Check that the TX is now included in block 2.
|
||||
func TestForkResendTx(t *testing.T) {
|
||||
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
||||
sim := simTestBackend(testAddr)
|
||||
defer sim.Close()
|
||||
// 1.
|
||||
parent := sim.blockchain.CurrentBlock()
|
||||
// 2.
|
||||
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
||||
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
||||
|
||||
_tx := types.NewTransaction(0, testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
||||
tx, _ := types.SignTx(_tx, types.HomesteadSigner{}, testKey)
|
||||
sim.SendTransaction(context.Background(), tx)
|
||||
sim.Commit()
|
||||
// 3.
|
||||
receipt, _ := sim.TransactionReceipt(context.Background(), tx.Hash())
|
||||
if h := receipt.BlockNumber.Uint64(); h != 1 {
|
||||
t.Errorf("TX included in wrong block: %d", h)
|
||||
}
|
||||
// 4.
|
||||
if err := sim.Fork(context.Background(), parent.Hash()); err != nil {
|
||||
t.Errorf("forking: %v", err)
|
||||
}
|
||||
// 5.
|
||||
sim.Commit()
|
||||
if err := sim.SendTransaction(context.Background(), tx); err != nil {
|
||||
t.Errorf("sending transaction: %v", err)
|
||||
}
|
||||
sim.Commit()
|
||||
// 6.
|
||||
receipt, _ = sim.TransactionReceipt(context.Background(), tx.Hash())
|
||||
if h := receipt.BlockNumber.Uint64(); h != 2 {
|
||||
t.Errorf("TX included in wrong block: %d", h)
|
||||
}
|
||||
}
|
||||
|
@@ -21,6 +21,8 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/ethereum/go-ethereum"
|
||||
"github.com/ethereum/go-ethereum/accounts/abi"
|
||||
@@ -49,11 +51,15 @@ type TransactOpts struct {
|
||||
Nonce *big.Int // Nonce to use for the transaction execution (nil = use pending state)
|
||||
Signer SignerFn // Method to use for signing the transaction (mandatory)
|
||||
|
||||
Value *big.Int // Funds to transfer along the transaction (nil = 0 = no funds)
|
||||
GasPrice *big.Int // Gas price to use for the transaction execution (nil = gas price oracle)
|
||||
GasLimit uint64 // Gas limit to set for the transaction execution (0 = estimate)
|
||||
Value *big.Int // Funds to transfer along the transaction (nil = 0 = no funds)
|
||||
GasPrice *big.Int // Gas price to use for the transaction execution (nil = gas price oracle)
|
||||
GasFeeCap *big.Int // Gas fee cap to use for the 1559 transaction execution (nil = gas price oracle)
|
||||
GasTipCap *big.Int // Gas priority fee cap to use for the 1559 transaction execution (nil = gas price oracle)
|
||||
GasLimit uint64 // Gas limit to set for the transaction execution (0 = estimate)
|
||||
|
||||
Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
|
||||
|
||||
NoSend bool // Do all transact steps but do not send the transaction
|
||||
}
|
||||
|
||||
// FilterOpts is the collection of options to fine tune filtering for events
|
||||
@@ -72,6 +78,29 @@ type WatchOpts struct {
|
||||
Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
|
||||
}
|
||||
|
||||
// MetaData collects all metadata for a bound contract.
|
||||
type MetaData struct {
|
||||
mu sync.Mutex
|
||||
Sigs map[string]string
|
||||
Bin string
|
||||
ABI string
|
||||
ab *abi.ABI
|
||||
}
|
||||
|
||||
func (m *MetaData) GetAbi() (*abi.ABI, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.ab != nil {
|
||||
return m.ab, nil
|
||||
}
|
||||
if parsed, err := abi.JSON(strings.NewReader(m.ABI)); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
m.ab = &parsed
|
||||
}
|
||||
return m.ab, nil
|
||||
}
|
||||
|
||||
// BoundContract is the base wrapper object that reflects a contract on the
|
||||
// Ethereum network. It contains a collection of methods that are used by the
|
||||
// higher level contract bindings to operate.
|
||||
@@ -221,12 +250,42 @@ func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, i
|
||||
} else {
|
||||
nonce = opts.Nonce.Uint64()
|
||||
}
|
||||
// Figure out the gas allowance and gas price values
|
||||
gasPrice := opts.GasPrice
|
||||
if gasPrice == nil {
|
||||
gasPrice, err = c.transactor.SuggestGasPrice(ensureContext(opts.Context))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to suggest gas price: %v", err)
|
||||
// Figure out reasonable gas price values
|
||||
if opts.GasPrice != nil && (opts.GasFeeCap != nil || opts.GasTipCap != nil) {
|
||||
return nil, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
|
||||
}
|
||||
head, err := c.transactor.HeaderByNumber(ensureContext(opts.Context), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if head.BaseFee != nil && opts.GasPrice == nil {
|
||||
if opts.GasTipCap == nil {
|
||||
tip, err := c.transactor.SuggestGasTipCap(ensureContext(opts.Context))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opts.GasTipCap = tip
|
||||
}
|
||||
if opts.GasFeeCap == nil {
|
||||
gasFeeCap := new(big.Int).Add(
|
||||
opts.GasTipCap,
|
||||
new(big.Int).Mul(head.BaseFee, big.NewInt(2)),
|
||||
)
|
||||
opts.GasFeeCap = gasFeeCap
|
||||
}
|
||||
if opts.GasFeeCap.Cmp(opts.GasTipCap) < 0 {
|
||||
return nil, fmt.Errorf("maxFeePerGas (%v) < maxPriorityFeePerGas (%v)", opts.GasFeeCap, opts.GasTipCap)
|
||||
}
|
||||
} else {
|
||||
if opts.GasFeeCap != nil || opts.GasTipCap != nil {
|
||||
return nil, errors.New("maxFeePerGas or maxPriorityFeePerGas specified but london is not active yet")
|
||||
}
|
||||
if opts.GasPrice == nil {
|
||||
price, err := c.transactor.SuggestGasPrice(ensureContext(opts.Context))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opts.GasPrice = price
|
||||
}
|
||||
}
|
||||
gasLimit := opts.GasLimit
|
||||
@@ -240,7 +299,7 @@ func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, i
|
||||
}
|
||||
}
|
||||
// If the contract surely has code (or code is not needed), estimate the transaction
|
||||
msg := ethereum.CallMsg{From: opts.From, To: contract, GasPrice: gasPrice, Value: value, Data: input}
|
||||
msg := ethereum.CallMsg{From: opts.From, To: contract, GasPrice: opts.GasPrice, GasTipCap: opts.GasTipCap, GasFeeCap: opts.GasFeeCap, Value: value, Data: input}
|
||||
gasLimit, err = c.transactor.EstimateGas(ensureContext(opts.Context), msg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to estimate gas needed: %v", err)
|
||||
@@ -248,10 +307,31 @@ func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, i
|
||||
}
|
||||
// Create the transaction, sign it and schedule it for execution
|
||||
var rawTx *types.Transaction
|
||||
if contract == nil {
|
||||
rawTx = types.NewContractCreation(nonce, value, gasLimit, gasPrice, input)
|
||||
if opts.GasFeeCap == nil {
|
||||
baseTx := &types.LegacyTx{
|
||||
Nonce: nonce,
|
||||
GasPrice: opts.GasPrice,
|
||||
Gas: gasLimit,
|
||||
Value: value,
|
||||
Data: input,
|
||||
}
|
||||
if contract != nil {
|
||||
baseTx.To = &c.address
|
||||
}
|
||||
rawTx = types.NewTx(baseTx)
|
||||
} else {
|
||||
rawTx = types.NewTransaction(nonce, c.address, value, gasLimit, gasPrice, input)
|
||||
baseTx := &types.DynamicFeeTx{
|
||||
Nonce: nonce,
|
||||
GasFeeCap: opts.GasFeeCap,
|
||||
GasTipCap: opts.GasTipCap,
|
||||
Gas: gasLimit,
|
||||
Value: value,
|
||||
Data: input,
|
||||
}
|
||||
if contract != nil {
|
||||
baseTx.To = &c.address
|
||||
}
|
||||
rawTx = types.NewTx(baseTx)
|
||||
}
|
||||
if opts.Signer == nil {
|
||||
return nil, errors.New("no signer to authorize the transaction with")
|
||||
@@ -260,6 +340,9 @@ func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, i
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if opts.NoSend {
|
||||
return signedTx, nil
|
||||
}
|
||||
if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -382,7 +465,7 @@ func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event strin
|
||||
// user specified it as such.
|
||||
func ensureContext(ctx context.Context) context.Context {
|
||||
if ctx == nil {
|
||||
return context.TODO()
|
||||
return context.Background()
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
@@ -298,7 +298,7 @@ var bindTests = []struct {
|
||||
key, _ := crypto.GenerateKey()
|
||||
auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000)
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000000000)}}, 10000000)
|
||||
defer sim.Close()
|
||||
|
||||
// Deploy an interaction tester contract and call a transaction on it
|
||||
@@ -353,7 +353,7 @@ var bindTests = []struct {
|
||||
key, _ := crypto.GenerateKey()
|
||||
auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000)
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000000000)}}, 10000000)
|
||||
defer sim.Close()
|
||||
|
||||
// Deploy a tuple tester contract and execute a structured call on it
|
||||
@@ -399,7 +399,7 @@ var bindTests = []struct {
|
||||
key, _ := crypto.GenerateKey()
|
||||
auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000)
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000000000)}}, 10000000)
|
||||
defer sim.Close()
|
||||
|
||||
// Deploy a tuple tester contract and execute a structured call on it
|
||||
@@ -457,7 +457,7 @@ var bindTests = []struct {
|
||||
key, _ := crypto.GenerateKey()
|
||||
auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000)
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000000000)}}, 10000000)
|
||||
defer sim.Close()
|
||||
|
||||
// Deploy a slice tester contract and execute a n array call on it
|
||||
@@ -505,7 +505,7 @@ var bindTests = []struct {
|
||||
key, _ := crypto.GenerateKey()
|
||||
auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000)
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000000000)}}, 10000000)
|
||||
defer sim.Close()
|
||||
|
||||
// Deploy a default method invoker contract and execute its default method
|
||||
@@ -529,6 +529,70 @@ var bindTests = []struct {
|
||||
nil,
|
||||
nil,
|
||||
},
|
||||
// Tests that structs are correctly unpacked
|
||||
{
|
||||
|
||||
`Structs`,
|
||||
`
|
||||
pragma solidity ^0.6.5;
|
||||
pragma experimental ABIEncoderV2;
|
||||
contract Structs {
|
||||
struct A {
|
||||
bytes32 B;
|
||||
}
|
||||
|
||||
function F() public view returns (A[] memory a, uint256[] memory c, bool[] memory d) {
|
||||
A[] memory a = new A[](2);
|
||||
a[0].B = bytes32(uint256(1234) << 96);
|
||||
uint256[] memory c;
|
||||
bool[] memory d;
|
||||
return (a, c, d);
|
||||
}
|
||||
|
||||
function G() public view returns (A[] memory a) {
|
||||
A[] memory a = new A[](2);
|
||||
a[0].B = bytes32(uint256(1234) << 96);
|
||||
return a;
|
||||
}
|
||||
}
|
||||
`,
|
||||
[]string{`608060405234801561001057600080fd5b50610278806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c806328811f591461003b5780636fecb6231461005b575b600080fd5b610043610070565b604051610052939291906101a0565b60405180910390f35b6100636100d6565b6040516100529190610186565b604080516002808252606082810190935282918291829190816020015b610095610131565b81526020019060019003908161008d575050805190915061026960611b9082906000906100be57fe5b60209081029190910101515293606093508392509050565b6040805160028082526060828101909352829190816020015b6100f7610131565b8152602001906001900390816100ef575050805190915061026960611b90829060009061012057fe5b602090810291909101015152905090565b60408051602081019091526000815290565b815260200190565b6000815180845260208085019450808401835b8381101561017b578151518752958201959082019060010161015e565b509495945050505050565b600060208252610199602083018461014b565b9392505050565b6000606082526101b3606083018661014b565b6020838203818501528186516101c98185610239565b91508288019350845b818110156101f3576101e5838651610143565b9484019492506001016101d2565b505084810360408601528551808252908201925081860190845b8181101561022b57825115158552938301939183019160010161020d565b509298975050505050505050565b9081526020019056fea2646970667358221220eb85327e285def14230424c52893aebecec1e387a50bb6b75fc4fdbed647f45f64736f6c63430006050033`},
|
||||
[]string{`[{"inputs":[],"name":"F","outputs":[{"components":[{"internalType":"bytes32","name":"B","type":"bytes32"}],"internalType":"structStructs.A[]","name":"a","type":"tuple[]"},{"internalType":"uint256[]","name":"c","type":"uint256[]"},{"internalType":"bool[]","name":"d","type":"bool[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"G","outputs":[{"components":[{"internalType":"bytes32","name":"B","type":"bytes32"}],"internalType":"structStructs.A[]","name":"a","type":"tuple[]"}],"stateMutability":"view","type":"function"}]`},
|
||||
`
|
||||
"math/big"
|
||||
|
||||
"github.com/ethereum/go-ethereum/accounts/abi/bind"
|
||||
"github.com/ethereum/go-ethereum/accounts/abi/bind/backends"
|
||||
"github.com/ethereum/go-ethereum/core"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
`,
|
||||
`
|
||||
// Generate a new random account and a funded simulator
|
||||
key, _ := crypto.GenerateKey()
|
||||
auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000000000)}}, 10000000)
|
||||
defer sim.Close()
|
||||
|
||||
// Deploy a structs method invoker contract and execute its default method
|
||||
_, _, structs, err := DeployStructs(auth, sim)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to deploy defaulter contract: %v", err)
|
||||
}
|
||||
sim.Commit()
|
||||
opts := bind.CallOpts{}
|
||||
if _, err := structs.F(&opts); err != nil {
|
||||
t.Fatalf("Failed to invoke F method: %v", err)
|
||||
}
|
||||
if _, err := structs.G(&opts); err != nil {
|
||||
t.Fatalf("Failed to invoke G method: %v", err)
|
||||
}
|
||||
`,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
},
|
||||
// Tests that non-existent contracts are reported as such (though only simulator test)
|
||||
{
|
||||
`NonExistent`,
|
||||
@@ -569,6 +633,45 @@ var bindTests = []struct {
|
||||
nil,
|
||||
nil,
|
||||
},
|
||||
{
|
||||
`NonExistentStruct`,
|
||||
`
|
||||
contract NonExistentStruct {
|
||||
function Struct() public view returns(uint256 a, uint256 b) {
|
||||
return (10, 10);
|
||||
}
|
||||
}
|
||||
`,
|
||||
[]string{`6080604052348015600f57600080fd5b5060888061001e6000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c8063d5f6622514602d575b600080fd5b6033604c565b6040805192835260208301919091528051918290030190f35b600a809156fea264697066735822beefbeefbeefbeefbeefbeefbeefbeefbeefbeefbeefbeefbeefbeefbeefbeefbeef64736f6c6343decafe0033`},
|
||||
[]string{`[{"inputs":[],"name":"Struct","outputs":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"uint256","name":"b","type":"uint256"}],"stateMutability":"pure","type":"function"}]`},
|
||||
`
|
||||
"github.com/ethereum/go-ethereum/accounts/abi/bind"
|
||||
"github.com/ethereum/go-ethereum/accounts/abi/bind/backends"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core"
|
||||
`,
|
||||
`
|
||||
// Create a simulator and wrap a non-deployed contract
|
||||
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{}, uint64(10000000000))
|
||||
defer sim.Close()
|
||||
|
||||
nonexistent, err := NewNonExistentStruct(common.Address{}, sim)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to access non-existent contract: %v", err)
|
||||
}
|
||||
// Ensure that contract calls fail with the appropriate error
|
||||
if res, err := nonexistent.Struct(nil); err == nil {
|
||||
t.Fatalf("Call succeeded on non-existent contract: %v", res)
|
||||
} else if (err != bind.ErrNoCode) {
|
||||
t.Fatalf("Error mismatch: have %v, want %v", err, bind.ErrNoCode)
|
||||
}
|
||||
`,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
},
|
||||
// Tests that gas estimation works for contracts with weird gas mechanics too.
|
||||
{
|
||||
`FunkyGasPattern`,
|
||||
@@ -600,7 +703,7 @@ var bindTests = []struct {
|
||||
key, _ := crypto.GenerateKey()
|
||||
auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000)
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000000000)}}, 10000000)
|
||||
defer sim.Close()
|
||||
|
||||
// Deploy a funky gas pattern contract
|
||||
@@ -650,7 +753,7 @@ var bindTests = []struct {
|
||||
key, _ := crypto.GenerateKey()
|
||||
auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000)
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000000000)}}, 10000000)
|
||||
defer sim.Close()
|
||||
|
||||
// Deploy a sender tester contract and execute a structured call on it
|
||||
@@ -725,7 +828,7 @@ var bindTests = []struct {
|
||||
key, _ := crypto.GenerateKey()
|
||||
auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000)
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000000000)}}, 10000000)
|
||||
defer sim.Close()
|
||||
|
||||
// Deploy a underscorer tester contract and execute a structured call on it
|
||||
@@ -819,7 +922,7 @@ var bindTests = []struct {
|
||||
key, _ := crypto.GenerateKey()
|
||||
auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000)
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000000000)}}, 10000000)
|
||||
defer sim.Close()
|
||||
|
||||
// Deploy an eventer contract
|
||||
@@ -1009,7 +1112,7 @@ var bindTests = []struct {
|
||||
key, _ := crypto.GenerateKey()
|
||||
auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000)
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000000000)}}, 10000000)
|
||||
defer sim.Close()
|
||||
|
||||
//deploy the test contract
|
||||
@@ -1144,7 +1247,7 @@ var bindTests = []struct {
|
||||
key, _ := crypto.GenerateKey()
|
||||
auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000)
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000000000)}}, 10000000)
|
||||
defer sim.Close()
|
||||
|
||||
_, _, contract, err := DeployTuple(auth, sim)
|
||||
@@ -1286,7 +1389,7 @@ var bindTests = []struct {
|
||||
key, _ := crypto.GenerateKey()
|
||||
auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000)
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000000000)}}, 10000000)
|
||||
defer sim.Close()
|
||||
|
||||
//deploy the test contract
|
||||
@@ -1351,7 +1454,7 @@ var bindTests = []struct {
|
||||
// Initialize test accounts
|
||||
key, _ := crypto.GenerateKey()
|
||||
auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000)
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000000000)}}, 10000000)
|
||||
defer sim.Close()
|
||||
|
||||
// deploy the test contract
|
||||
@@ -1441,7 +1544,7 @@ var bindTests = []struct {
|
||||
addr := crypto.PubkeyToAddress(key.PublicKey)
|
||||
|
||||
// Deploy registrar contract
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(1000000000)}}, 10000000)
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(10000000000000000)}}, 10000000)
|
||||
defer sim.Close()
|
||||
|
||||
transactOpts, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
@@ -1503,7 +1606,7 @@ var bindTests = []struct {
|
||||
addr := crypto.PubkeyToAddress(key.PublicKey)
|
||||
|
||||
// Deploy registrar contract
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(1000000000)}}, 10000000)
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(10000000000000000)}}, 10000000)
|
||||
defer sim.Close()
|
||||
|
||||
transactOpts, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
@@ -1565,7 +1668,7 @@ var bindTests = []struct {
|
||||
key, _ := crypto.GenerateKey()
|
||||
auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000)
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000000000)}}, 10000000)
|
||||
defer sim.Close()
|
||||
|
||||
// Deploy a tester contract and execute a structured call on it
|
||||
@@ -1601,11 +1704,7 @@ var bindTests = []struct {
|
||||
contract NewFallbacks {
|
||||
event Fallback(bytes data);
|
||||
fallback() external {
|
||||
bytes memory data;
|
||||
assembly {
|
||||
calldatacopy(data, 0, calldatasize())
|
||||
}
|
||||
emit Fallback(data);
|
||||
emit Fallback(msg.data);
|
||||
}
|
||||
|
||||
event Received(address addr, uint value);
|
||||
@@ -1614,7 +1713,7 @@ var bindTests = []struct {
|
||||
}
|
||||
}
|
||||
`,
|
||||
[]string{"60806040523480156100115760006000fd5b50610017565b61016e806100266000396000f3fe60806040526004361061000d575b36610081575b7f88a5966d370b9919b20f3e2c13ff65706f196a4e32cc2c12bf57088f885258743334604051808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a15b005b34801561008e5760006000fd5b505b606036600082377f9043988963722edecc2099c75b0af0ff76af14ffca42ed6bce059a20a2a9f986816040518080602001828103825283818151815260200191508051906020019080838360005b838110156100fa5780820151818401525b6020810190506100de565b50505050905090810190601f1680156101275780820380516001836020036101000a031916815260200191505b509250505060405180910390a1505b00fea26469706673582212205643ca37f40c2b352dc541f42e9e6720de065de756324b7fcc9fb1d67eda4a7d64736f6c63430006040033"},
|
||||
[]string{"6080604052348015600f57600080fd5b506101078061001f6000396000f3fe608060405236605f577f88a5966d370b9919b20f3e2c13ff65706f196a4e32cc2c12bf57088f885258743334604051808373ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a1005b348015606a57600080fd5b507f9043988963722edecc2099c75b0af0ff76af14ffca42ed6bce059a20a2a9f98660003660405180806020018281038252848482818152602001925080828437600081840152601f19601f820116905080830192505050935050505060405180910390a100fea26469706673582212201f994dcfbc53bf610b19176f9a361eafa77b447fd9c796fa2c615dfd0aaf3b8b64736f6c634300060c0033"},
|
||||
[]string{`[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"Fallback","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"addr","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Received","type":"event"},{"stateMutability":"nonpayable","type":"fallback"},{"stateMutability":"payable","type":"receive"}]`},
|
||||
`
|
||||
"bytes"
|
||||
@@ -1629,7 +1728,7 @@ var bindTests = []struct {
|
||||
key, _ := crypto.GenerateKey()
|
||||
addr := crypto.PubkeyToAddress(key.PublicKey)
|
||||
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(1000000000)}}, 1000000)
|
||||
sim := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(10000000000000000)}}, 1000000)
|
||||
defer sim.Close()
|
||||
|
||||
opts, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
||||
@@ -1662,6 +1761,7 @@ var bindTests = []struct {
|
||||
}
|
||||
|
||||
// Test fallback function
|
||||
gotEvent = false
|
||||
opts.Value = nil
|
||||
calldata := []byte{0x01, 0x02, 0x03}
|
||||
c.Fallback(opts, calldata)
|
||||
@@ -1746,11 +1846,16 @@ func TestGolangBindings(t *testing.T) {
|
||||
t.Fatalf("failed to convert binding test to modules: %v\n%s", err, out)
|
||||
}
|
||||
pwd, _ := os.Getwd()
|
||||
replacer := exec.Command(gocmd, "mod", "edit", "-replace", "github.com/ethereum/go-ethereum="+filepath.Join(pwd, "..", "..", "..")) // Repo root
|
||||
replacer := exec.Command(gocmd, "mod", "edit", "-x", "-require", "github.com/ethereum/go-ethereum@v0.0.0", "-replace", "github.com/ethereum/go-ethereum="+filepath.Join(pwd, "..", "..", "..")) // Repo root
|
||||
replacer.Dir = pkg
|
||||
if out, err := replacer.CombinedOutput(); err != nil {
|
||||
t.Fatalf("failed to replace binding test dependency to current source tree: %v\n%s", err, out)
|
||||
}
|
||||
tidier := exec.Command(gocmd, "mod", "tidy")
|
||||
tidier.Dir = pkg
|
||||
if out, err := tidier.CombinedOutput(); err != nil {
|
||||
t.Fatalf("failed to tidy Go module file: %v\n%s", err, out)
|
||||
}
|
||||
// Test the entire package and report any failures
|
||||
cmd := exec.Command(gocmd, "test", "-v", "-count", "1")
|
||||
cmd.Dir = pkg
|
||||
|
@@ -90,6 +90,7 @@ package {{.Package}}
|
||||
import (
|
||||
"math/big"
|
||||
"strings"
|
||||
"errors"
|
||||
|
||||
ethereum "github.com/ethereum/go-ethereum"
|
||||
"github.com/ethereum/go-ethereum/accounts/abi"
|
||||
@@ -101,6 +102,7 @@ import (
|
||||
|
||||
// Reference imports to suppress errors if they are not otherwise used.
|
||||
var (
|
||||
_ = errors.New
|
||||
_ = big.NewInt
|
||||
_ = strings.NewReader
|
||||
_ = ethereum.NotFound
|
||||
@@ -120,32 +122,48 @@ var (
|
||||
{{end}}
|
||||
|
||||
{{range $contract := .Contracts}}
|
||||
// {{.Type}}ABI is the input ABI used to generate the binding from.
|
||||
const {{.Type}}ABI = "{{.InputABI}}"
|
||||
|
||||
{{if $contract.FuncSigs}}
|
||||
// {{.Type}}FuncSigs maps the 4-byte function signature to its string representation.
|
||||
var {{.Type}}FuncSigs = map[string]string{
|
||||
// {{.Type}}MetaData contains all meta data concerning the {{.Type}} contract.
|
||||
var {{.Type}}MetaData = &bind.MetaData{
|
||||
ABI: "{{.InputABI}}",
|
||||
{{if $contract.FuncSigs -}}
|
||||
Sigs: map[string]string{
|
||||
{{range $strsig, $binsig := .FuncSigs}}"{{$binsig}}": "{{$strsig}}",
|
||||
{{end}}
|
||||
}
|
||||
},
|
||||
{{end -}}
|
||||
{{if .InputBin -}}
|
||||
Bin: "0x{{.InputBin}}",
|
||||
{{end}}
|
||||
}
|
||||
// {{.Type}}ABI is the input ABI used to generate the binding from.
|
||||
// Deprecated: Use {{.Type}}MetaData.ABI instead.
|
||||
var {{.Type}}ABI = {{.Type}}MetaData.ABI
|
||||
|
||||
{{if $contract.FuncSigs}}
|
||||
// Deprecated: Use {{.Type}}MetaData.Sigs instead.
|
||||
// {{.Type}}FuncSigs maps the 4-byte function signature to its string representation.
|
||||
var {{.Type}}FuncSigs = {{.Type}}MetaData.Sigs
|
||||
{{end}}
|
||||
|
||||
{{if .InputBin}}
|
||||
// {{.Type}}Bin is the compiled bytecode used for deploying new contracts.
|
||||
var {{.Type}}Bin = "0x{{.InputBin}}"
|
||||
// Deprecated: Use {{.Type}}MetaData.Bin instead.
|
||||
var {{.Type}}Bin = {{.Type}}MetaData.Bin
|
||||
|
||||
// Deploy{{.Type}} deploys a new Ethereum contract, binding an instance of {{.Type}} to it.
|
||||
func Deploy{{.Type}}(auth *bind.TransactOpts, backend bind.ContractBackend {{range .Constructor.Inputs}}, {{.Name}} {{bindtype .Type $structs}}{{end}}) (common.Address, *types.Transaction, *{{.Type}}, error) {
|
||||
parsed, err := abi.JSON(strings.NewReader({{.Type}}ABI))
|
||||
parsed, err := {{.Type}}MetaData.GetAbi()
|
||||
if err != nil {
|
||||
return common.Address{}, nil, nil, err
|
||||
}
|
||||
if parsed == nil {
|
||||
return common.Address{}, nil, nil, errors.New("GetABI returned nil")
|
||||
}
|
||||
{{range $pattern, $name := .Libraries}}
|
||||
{{decapitalise $name}}Addr, _, _, _ := Deploy{{capitalise $name}}(auth, backend)
|
||||
{{$contract.Type}}Bin = strings.Replace({{$contract.Type}}Bin, "__${{$pattern}}$__", {{decapitalise $name}}Addr.String()[2:], -1)
|
||||
{{end}}
|
||||
address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex({{.Type}}Bin), backend {{range .Constructor.Inputs}}, {{.Name}}{{end}})
|
||||
address, tx, contract, err := bind.DeployContract(auth, *parsed, common.FromHex({{.Type}}Bin), backend {{range .Constructor.Inputs}}, {{.Name}}{{end}})
|
||||
if err != nil {
|
||||
return common.Address{}, nil, nil, err
|
||||
}
|
||||
@@ -304,8 +322,11 @@ var (
|
||||
err := _{{$contract.Type}}.contract.Call(opts, &out, "{{.Original.Name}}" {{range .Normalized.Inputs}}, {{.Name}}{{end}})
|
||||
{{if .Structured}}
|
||||
outstruct := new(struct{ {{range .Normalized.Outputs}} {{.Name}} {{bindtype .Type $structs}}; {{end}} })
|
||||
if err != nil {
|
||||
return *outstruct, err
|
||||
}
|
||||
{{range $i, $t := .Normalized.Outputs}}
|
||||
outstruct.{{.Name}} = out[{{$i}}].({{bindtype .Type $structs}}){{end}}
|
||||
outstruct.{{.Name}} = *abi.ConvertType(out[{{$i}}], new({{bindtype .Type $structs}})).(*{{bindtype .Type $structs}}){{end}}
|
||||
|
||||
return *outstruct, err
|
||||
{{else}}
|
||||
|
@@ -56,14 +56,17 @@ func TestWaitDeployed(t *testing.T) {
|
||||
for name, test := range waitDeployedTests {
|
||||
backend := backends.NewSimulatedBackend(
|
||||
core.GenesisAlloc{
|
||||
crypto.PubkeyToAddress(testKey.PublicKey): {Balance: big.NewInt(10000000000)},
|
||||
crypto.PubkeyToAddress(testKey.PublicKey): {Balance: big.NewInt(10000000000000000)},
|
||||
},
|
||||
10000000,
|
||||
)
|
||||
defer backend.Close()
|
||||
|
||||
// Create the transaction.
|
||||
tx := types.NewContractCreation(0, big.NewInt(0), test.gas, big.NewInt(1), common.FromHex(test.code))
|
||||
// Create the transaction
|
||||
head, _ := backend.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
||||
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
||||
|
||||
tx := types.NewContractCreation(0, big.NewInt(0), test.gas, gasPrice, common.FromHex(test.code))
|
||||
tx, _ = types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
||||
|
||||
// Wait for it to get mined in the background.
|
||||
@@ -99,15 +102,18 @@ func TestWaitDeployed(t *testing.T) {
|
||||
func TestWaitDeployedCornerCases(t *testing.T) {
|
||||
backend := backends.NewSimulatedBackend(
|
||||
core.GenesisAlloc{
|
||||
crypto.PubkeyToAddress(testKey.PublicKey): {Balance: big.NewInt(10000000000)},
|
||||
crypto.PubkeyToAddress(testKey.PublicKey): {Balance: big.NewInt(10000000000000000)},
|
||||
},
|
||||
10000000,
|
||||
)
|
||||
defer backend.Close()
|
||||
|
||||
head, _ := backend.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
||||
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
||||
|
||||
// Create a transaction to an account.
|
||||
code := "6060604052600a8060106000396000f360606040526008565b00"
|
||||
tx := types.NewTransaction(0, common.HexToAddress("0x01"), big.NewInt(0), 3000000, big.NewInt(1), common.FromHex(code))
|
||||
tx := types.NewTransaction(0, common.HexToAddress("0x01"), big.NewInt(0), 3000000, gasPrice, common.FromHex(code))
|
||||
tx, _ = types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
@@ -119,7 +125,7 @@ func TestWaitDeployedCornerCases(t *testing.T) {
|
||||
}
|
||||
|
||||
// Create a transaction that is not mined.
|
||||
tx = types.NewContractCreation(1, big.NewInt(0), 3000000, big.NewInt(1), common.FromHex(code))
|
||||
tx = types.NewContractCreation(1, big.NewInt(0), 3000000, gasPrice, common.FromHex(code))
|
||||
tx, _ = types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
||||
|
||||
go func() {
|
||||
|
@@ -113,7 +113,7 @@ type Wallet interface {
|
||||
SignData(account Account, mimeType string, data []byte) ([]byte, error)
|
||||
|
||||
// SignDataWithPassphrase is identical to SignData, but also takes a password
|
||||
// NOTE: there's an chance that an erroneous call might mistake the two strings, and
|
||||
// NOTE: there's a chance that an erroneous call might mistake the two strings, and
|
||||
// supply password in the mimetype field, or vice versa. Thus, an implementation
|
||||
// should never echo the mimetype or return the mimetype in the error-response
|
||||
SignDataWithPassphrase(account Account, passphrase, mimeType string, data []byte) ([]byte, error)
|
||||
@@ -127,7 +127,7 @@ type Wallet interface {
|
||||
// a password to decrypt the account, or a PIN code o verify the transaction),
|
||||
// an AuthNeededError instance will be returned, containing infos for the user
|
||||
// about which fields or actions are needed. The user may retry by providing
|
||||
// the needed details via SignHashWithPassphrase, or by other means (e.g. unlock
|
||||
// the needed details via SignTextWithPassphrase, or by other means (e.g. unlock
|
||||
// the account in a keystore).
|
||||
//
|
||||
// This method should return the signature in 'canonical' format, with v 0 or 1
|
||||
|
44
accounts/external/backend.go
vendored
44
accounts/external/backend.go
vendored
@@ -29,7 +29,7 @@ import (
|
||||
"github.com/ethereum/go-ethereum/event"
|
||||
"github.com/ethereum/go-ethereum/log"
|
||||
"github.com/ethereum/go-ethereum/rpc"
|
||||
"github.com/ethereum/go-ethereum/signer/core"
|
||||
"github.com/ethereum/go-ethereum/signer/core/apitypes"
|
||||
)
|
||||
|
||||
type ExternalBackend struct {
|
||||
@@ -196,6 +196,10 @@ type signTransactionResult struct {
|
||||
Tx *types.Transaction `json:"tx"`
|
||||
}
|
||||
|
||||
// SignTx sends the transaction to the external signer.
|
||||
// If chainID is nil, or tx.ChainID is zero, the chain ID will be assigned
|
||||
// by the external signer. For non-legacy transactions, the chain ID of the
|
||||
// transaction overrides the chainID parameter.
|
||||
func (api *ExternalSigner) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
|
||||
data := hexutil.Bytes(tx.Data())
|
||||
var to *common.MixedcaseAddress
|
||||
@@ -203,14 +207,36 @@ func (api *ExternalSigner) SignTx(account accounts.Account, tx *types.Transactio
|
||||
t := common.NewMixedcaseAddress(*tx.To())
|
||||
to = &t
|
||||
}
|
||||
args := &core.SendTxArgs{
|
||||
Data: &data,
|
||||
Nonce: hexutil.Uint64(tx.Nonce()),
|
||||
Value: hexutil.Big(*tx.Value()),
|
||||
Gas: hexutil.Uint64(tx.Gas()),
|
||||
GasPrice: hexutil.Big(*tx.GasPrice()),
|
||||
To: to,
|
||||
From: common.NewMixedcaseAddress(account.Address),
|
||||
args := &apitypes.SendTxArgs{
|
||||
Data: &data,
|
||||
Nonce: hexutil.Uint64(tx.Nonce()),
|
||||
Value: hexutil.Big(*tx.Value()),
|
||||
Gas: hexutil.Uint64(tx.Gas()),
|
||||
To: to,
|
||||
From: common.NewMixedcaseAddress(account.Address),
|
||||
}
|
||||
switch tx.Type() {
|
||||
case types.LegacyTxType, types.AccessListTxType:
|
||||
args.GasPrice = (*hexutil.Big)(tx.GasPrice())
|
||||
case types.DynamicFeeTxType:
|
||||
args.MaxFeePerGas = (*hexutil.Big)(tx.GasFeeCap())
|
||||
args.MaxPriorityFeePerGas = (*hexutil.Big)(tx.GasTipCap())
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported tx type %d", tx.Type())
|
||||
}
|
||||
// We should request the default chain id that we're operating with
|
||||
// (the chain we're executing on)
|
||||
if chainID != nil && chainID.Sign() != 0 {
|
||||
args.ChainID = (*hexutil.Big)(chainID)
|
||||
}
|
||||
if tx.Type() != types.LegacyTxType {
|
||||
// However, if the user asked for a particular chain id, then we should
|
||||
// use that instead.
|
||||
if tx.ChainId().Sign() != 0 {
|
||||
args.ChainID = (*hexutil.Big)(tx.ChainId())
|
||||
}
|
||||
accessList := tx.AccessList()
|
||||
args.AccessList = &accessList
|
||||
}
|
||||
var res signTransactionResult
|
||||
if err := api.client.Call(&res, "account_signTransaction", args); err != nil {
|
||||
|
@@ -262,7 +262,7 @@ func (ac *accountCache) scanAccounts() error {
|
||||
switch {
|
||||
case err != nil:
|
||||
log.Debug("Failed to decode keystore key", "path", path, "err", err)
|
||||
case (addr == common.Address{}):
|
||||
case addr == common.Address{}:
|
||||
log.Debug("Failed to decode keystore key", "path", path, "err", "missing or zero address")
|
||||
default:
|
||||
return &accounts.Account{
|
||||
|
@@ -32,7 +32,7 @@ import (
|
||||
"github.com/ethereum/go-ethereum/accounts"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/pborman/uuid"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -110,7 +110,10 @@ func (k *Key) UnmarshalJSON(j []byte) (err error) {
|
||||
}
|
||||
|
||||
u := new(uuid.UUID)
|
||||
*u = uuid.Parse(keyJSON.Id)
|
||||
*u, err = uuid.Parse(keyJSON.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
k.Id = *u
|
||||
addr, err := hex.DecodeString(keyJSON.Address)
|
||||
if err != nil {
|
||||
@@ -128,7 +131,10 @@ func (k *Key) UnmarshalJSON(j []byte) (err error) {
|
||||
}
|
||||
|
||||
func newKeyFromECDSA(privateKeyECDSA *ecdsa.PrivateKey) *Key {
|
||||
id := uuid.NewRandom()
|
||||
id, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("Could not create random uuid: %v", err))
|
||||
}
|
||||
key := &Key{
|
||||
Id: id,
|
||||
Address: crypto.PubkeyToAddress(privateKeyECDSA.PublicKey),
|
||||
|
@@ -283,11 +283,9 @@ func (ks *KeyStore) SignTx(a accounts.Account, tx *types.Transaction, chainID *b
|
||||
if !found {
|
||||
return nil, ErrLocked
|
||||
}
|
||||
// Depending on the presence of the chain ID, sign with EIP155 or homestead
|
||||
if chainID != nil {
|
||||
return types.SignTx(tx, types.NewEIP155Signer(chainID), unlockedKey.PrivateKey)
|
||||
}
|
||||
return types.SignTx(tx, types.HomesteadSigner{}, unlockedKey.PrivateKey)
|
||||
// Depending on the presence of the chain ID, sign with 2718 or homestead
|
||||
signer := types.LatestSignerForChainID(chainID)
|
||||
return types.SignTx(tx, signer, unlockedKey.PrivateKey)
|
||||
}
|
||||
|
||||
// SignHashWithPassphrase signs hash if the private key matching the given address
|
||||
@@ -310,12 +308,9 @@ func (ks *KeyStore) SignTxWithPassphrase(a accounts.Account, passphrase string,
|
||||
return nil, err
|
||||
}
|
||||
defer zeroKey(key.PrivateKey)
|
||||
|
||||
// Depending on the presence of the chain ID, sign with EIP155 or homestead
|
||||
if chainID != nil {
|
||||
return types.SignTx(tx, types.NewEIP155Signer(chainID), key.PrivateKey)
|
||||
}
|
||||
return types.SignTx(tx, types.HomesteadSigner{}, key.PrivateKey)
|
||||
// Depending on the presence of the chain ID, sign with or without replay protection.
|
||||
signer := types.LatestSignerForChainID(chainID)
|
||||
return types.SignTx(tx, signer, key.PrivateKey)
|
||||
}
|
||||
|
||||
// Unlock unlocks the given account indefinitely.
|
||||
|
@@ -42,7 +42,7 @@ import (
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/common/math"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/pborman/uuid"
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
"golang.org/x/crypto/scrypt"
|
||||
)
|
||||
@@ -228,9 +228,12 @@ func DecryptKey(keyjson []byte, auth string) (*Key, error) {
|
||||
return nil, err
|
||||
}
|
||||
key := crypto.ToECDSAUnsafe(keyBytes)
|
||||
|
||||
id, err := uuid.FromBytes(keyId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Key{
|
||||
Id: keyId,
|
||||
Id: id,
|
||||
Address: crypto.PubkeyToAddress(key.PublicKey),
|
||||
PrivateKey: key,
|
||||
}, nil
|
||||
@@ -276,7 +279,11 @@ func decryptKeyV3(keyProtected *encryptedKeyJSONV3, auth string) (keyBytes []byt
|
||||
if keyProtected.Version != version {
|
||||
return nil, nil, fmt.Errorf("version not supported: %v", keyProtected.Version)
|
||||
}
|
||||
keyId = uuid.Parse(keyProtected.Id)
|
||||
keyUUID, err := uuid.Parse(keyProtected.Id)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
keyId = keyUUID[:]
|
||||
plainText, err := DecryptDataV3(keyProtected.Crypto, auth)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
@@ -285,7 +292,11 @@ func decryptKeyV3(keyProtected *encryptedKeyJSONV3, auth string) (keyBytes []byt
|
||||
}
|
||||
|
||||
func decryptKeyV1(keyProtected *encryptedKeyJSONV1, auth string) (keyBytes []byte, keyId []byte, err error) {
|
||||
keyId = uuid.Parse(keyProtected.Id)
|
||||
keyUUID, err := uuid.Parse(keyProtected.Id)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
keyId = keyUUID[:]
|
||||
mac, err := hex.DecodeString(keyProtected.Crypto.MAC)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
|
@@ -27,7 +27,7 @@ import (
|
||||
|
||||
"github.com/ethereum/go-ethereum/accounts"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/pborman/uuid"
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
)
|
||||
|
||||
@@ -37,7 +37,10 @@ func importPreSaleKey(keyStore keyStore, keyJSON []byte, password string) (accou
|
||||
if err != nil {
|
||||
return accounts.Account{}, nil, err
|
||||
}
|
||||
key.Id = uuid.NewRandom()
|
||||
key.Id, err = uuid.NewRandom()
|
||||
if err != nil {
|
||||
return accounts.Account{}, nil, err
|
||||
}
|
||||
a := accounts.Account{
|
||||
Address: key.Address,
|
||||
URL: accounts.URL{
|
||||
@@ -86,7 +89,7 @@ func decryptPreSaleKey(fileContent []byte, password string) (key *Key, err error
|
||||
ecKey := crypto.ToECDSAUnsafe(ethPriv)
|
||||
|
||||
key = &Key{
|
||||
Id: nil,
|
||||
Id: uuid.UUID{},
|
||||
Address: crypto.PubkeyToAddress(ecKey.PublicKey),
|
||||
PrivateKey: ecKey,
|
||||
}
|
||||
|
@@ -31,12 +31,16 @@
|
||||
Write down the URL (`keycard://044def09` in this example). Then ask `geth` to open the wallet:
|
||||
|
||||
```
|
||||
> personal.openWallet("keycard://044def09")
|
||||
Please enter the pairing password:
|
||||
> personal.openWallet("keycard://044def09", "pairing password")
|
||||
```
|
||||
|
||||
Enter the pairing password that you have received during card initialization. Same with the PIN that you will subsequently be
|
||||
asked for.
|
||||
The pairing password has been generated during the card initialization process.
|
||||
|
||||
The process needs to be repeated once more with the PIN:
|
||||
|
||||
```
|
||||
> personal.openWallet("keycard://044def09", "PIN number")
|
||||
```
|
||||
|
||||
If everything goes well, you should see your new account when typing `personal` on the console:
|
||||
|
||||
|
@@ -20,6 +20,7 @@ import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/sha512"
|
||||
@@ -27,7 +28,6 @@ import (
|
||||
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
pcsc "github.com/gballet/go-libpcsclite"
|
||||
"github.com/wsddn/go-ecdh"
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
"golang.org/x/text/unicode/norm"
|
||||
)
|
||||
@@ -63,26 +63,19 @@ type SecureChannelSession struct {
|
||||
// NewSecureChannelSession creates a new secure channel for the given card and public key.
|
||||
func NewSecureChannelSession(card *pcsc.Card, keyData []byte) (*SecureChannelSession, error) {
|
||||
// Generate an ECDSA keypair for ourselves
|
||||
gen := ecdh.NewEllipticECDH(crypto.S256())
|
||||
private, public, err := gen.GenerateKey(rand.Reader)
|
||||
key, err := crypto.GenerateKey()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cardPublic, ok := gen.Unmarshal(keyData)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("could not unmarshal public key from card")
|
||||
}
|
||||
|
||||
secret, err := gen.GenerateSharedSecret(private, cardPublic)
|
||||
cardPublic, err := crypto.UnmarshalPubkey(keyData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("could not unmarshal public key from card: %v", err)
|
||||
}
|
||||
|
||||
secret, _ := key.Curve.ScalarMult(cardPublic.X, cardPublic.Y, key.D.Bytes())
|
||||
return &SecureChannelSession{
|
||||
card: card,
|
||||
secret: secret,
|
||||
publicKey: gen.Marshal(public),
|
||||
secret: secret.Bytes(),
|
||||
publicKey: elliptic.Marshal(crypto.S256(), key.PublicKey.X, key.PublicKey.Y),
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
@@ -699,7 +699,7 @@ func (w *Wallet) signHash(account accounts.Account, hash []byte) ([]byte, error)
|
||||
// the needed details via SignTxWithPassphrase, or by other means (e.g. unlock
|
||||
// the account in a keystore).
|
||||
func (w *Wallet) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
|
||||
signer := types.NewEIP155Signer(chainID)
|
||||
signer := types.LatestSignerForChainID(chainID)
|
||||
hash := signer.Hash(tx)
|
||||
sig, err := w.signHash(account, hash[:])
|
||||
if err != nil {
|
||||
|
@@ -64,7 +64,7 @@ func (u URL) String() string {
|
||||
func (u URL) TerminalString() string {
|
||||
url := u.String()
|
||||
if len(url) > 32 {
|
||||
return url[:31] + "…"
|
||||
return url[:31] + ".."
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
@@ -52,8 +52,10 @@ const (
|
||||
ledgerOpRetrieveAddress ledgerOpcode = 0x02 // Returns the public key and Ethereum address for a given BIP 32 path
|
||||
ledgerOpSignTransaction ledgerOpcode = 0x04 // Signs an Ethereum transaction after having the user validate the parameters
|
||||
ledgerOpGetConfiguration ledgerOpcode = 0x06 // Returns specific wallet application configuration
|
||||
ledgerOpSignTypedMessage ledgerOpcode = 0x0c // Signs an Ethereum message following the EIP 712 specification
|
||||
|
||||
ledgerP1DirectlyFetchAddress ledgerParam1 = 0x00 // Return address directly from the wallet
|
||||
ledgerP1InitTypedMessageData ledgerParam1 = 0x00 // First chunk of Typed Message data
|
||||
ledgerP1InitTransactionData ledgerParam1 = 0x00 // First transaction data block for signing
|
||||
ledgerP1ContTransactionData ledgerParam1 = 0x80 // Subsequent transaction data block for signing
|
||||
ledgerP2DiscardAddressChainCode ledgerParam2 = 0x00 // Do not return the chain code along with the address
|
||||
@@ -170,6 +172,24 @@ func (w *ledgerDriver) SignTx(path accounts.DerivationPath, tx *types.Transactio
|
||||
return w.ledgerSign(path, tx, chainID)
|
||||
}
|
||||
|
||||
// SignTypedMessage implements usbwallet.driver, sending the message to the Ledger and
|
||||
// waiting for the user to sign or deny the transaction.
|
||||
//
|
||||
// Note: this was introduced in the ledger 1.5.0 firmware
|
||||
func (w *ledgerDriver) SignTypedMessage(path accounts.DerivationPath, domainHash []byte, messageHash []byte) ([]byte, error) {
|
||||
// If the Ethereum app doesn't run, abort
|
||||
if w.offline() {
|
||||
return nil, accounts.ErrWalletClosed
|
||||
}
|
||||
// Ensure the wallet is capable of signing the given transaction
|
||||
if w.version[0] < 1 && w.version[1] < 5 {
|
||||
//lint:ignore ST1005 brand name displayed on the console
|
||||
return nil, fmt.Errorf("Ledger version >= 1.5.0 required for EIP-712 signing (found version v%d.%d.%d)", w.version[0], w.version[1], w.version[2])
|
||||
}
|
||||
// All infos gathered and metadata checks out, request signing
|
||||
return w.ledgerSignTypedMessage(path, domainHash, messageHash)
|
||||
}
|
||||
|
||||
// ledgerVersion retrieves the current version of the Ethereum wallet app running
|
||||
// on the Ledger wallet.
|
||||
//
|
||||
@@ -367,6 +387,68 @@ func (w *ledgerDriver) ledgerSign(derivationPath []uint32, tx *types.Transaction
|
||||
return sender, signed, nil
|
||||
}
|
||||
|
||||
// ledgerSignTypedMessage sends the transaction to the Ledger wallet, and waits for the user
|
||||
// to confirm or deny the transaction.
|
||||
//
|
||||
// The signing protocol is defined as follows:
|
||||
//
|
||||
// CLA | INS | P1 | P2 | Lc | Le
|
||||
// ----+-----+----+-----------------------------+-----+---
|
||||
// E0 | 0C | 00 | implementation version : 00 | variable | variable
|
||||
//
|
||||
// Where the input is:
|
||||
//
|
||||
// Description | Length
|
||||
// -------------------------------------------------+----------
|
||||
// Number of BIP 32 derivations to perform (max 10) | 1 byte
|
||||
// First derivation index (big endian) | 4 bytes
|
||||
// ... | 4 bytes
|
||||
// Last derivation index (big endian) | 4 bytes
|
||||
// domain hash | 32 bytes
|
||||
// message hash | 32 bytes
|
||||
//
|
||||
//
|
||||
//
|
||||
// And the output data is:
|
||||
//
|
||||
// Description | Length
|
||||
// ------------+---------
|
||||
// signature V | 1 byte
|
||||
// signature R | 32 bytes
|
||||
// signature S | 32 bytes
|
||||
func (w *ledgerDriver) ledgerSignTypedMessage(derivationPath []uint32, domainHash []byte, messageHash []byte) ([]byte, error) {
|
||||
// Flatten the derivation path into the Ledger request
|
||||
path := make([]byte, 1+4*len(derivationPath))
|
||||
path[0] = byte(len(derivationPath))
|
||||
for i, component := range derivationPath {
|
||||
binary.BigEndian.PutUint32(path[1+4*i:], component)
|
||||
}
|
||||
// Create the 712 message
|
||||
payload := append(path, domainHash...)
|
||||
payload = append(payload, messageHash...)
|
||||
|
||||
// Send the request and wait for the response
|
||||
var (
|
||||
op = ledgerP1InitTypedMessageData
|
||||
reply []byte
|
||||
err error
|
||||
)
|
||||
|
||||
// Send the message over, ensuring it's processed correctly
|
||||
reply, err = w.ledgerExchange(ledgerOpSignTypedMessage, op, 0, payload)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Extract the Ethereum signature and do a sanity validation
|
||||
if len(reply) != crypto.SignatureLength {
|
||||
return nil, errors.New("reply lacks signature")
|
||||
}
|
||||
signature := append(reply[1:], reply[0])
|
||||
return signature, nil
|
||||
}
|
||||
|
||||
// ledgerExchange performs a data exchange with the Ledger wallet, sending it a
|
||||
// message and retrieving the response.
|
||||
//
|
||||
|
@@ -185,6 +185,10 @@ func (w *trezorDriver) SignTx(path accounts.DerivationPath, tx *types.Transactio
|
||||
return w.trezorSign(path, tx, chainID)
|
||||
}
|
||||
|
||||
func (w *trezorDriver) SignTypedMessage(path accounts.DerivationPath, domainHash []byte, messageHash []byte) ([]byte, error) {
|
||||
return nil, accounts.ErrNotSupported
|
||||
}
|
||||
|
||||
// trezorDerive sends a derivation request to the Trezor device and returns the
|
||||
// Ethereum address located on that path.
|
||||
func (w *trezorDriver) trezorDerive(derivationPath []uint32) (common.Address, error) {
|
||||
@@ -255,9 +259,11 @@ func (w *trezorDriver) trezorSign(derivationPath []uint32, tx *types.Transaction
|
||||
if chainID == nil {
|
||||
signer = new(types.HomesteadSigner)
|
||||
} else {
|
||||
// Trezor backend does not support typed transactions yet.
|
||||
signer = types.NewEIP155Signer(chainID)
|
||||
signature[64] -= byte(chainID.Uint64()*2 + 35)
|
||||
}
|
||||
|
||||
// Inject the final signature into the transaction and sanity check the sender
|
||||
signed, err := tx.WithSignature(signer, signature)
|
||||
if err != nil {
|
||||
|
@@ -67,6 +67,8 @@ type driver interface {
|
||||
// SignTx sends the transaction to the USB device and waits for the user to confirm
|
||||
// or deny the transaction.
|
||||
SignTx(path accounts.DerivationPath, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error)
|
||||
|
||||
SignTypedMessage(path accounts.DerivationPath, messageHash []byte, domainHash []byte) ([]byte, error)
|
||||
}
|
||||
|
||||
// wallet represents the common functionality shared by all USB hardware
|
||||
@@ -524,7 +526,46 @@ func (w *wallet) signHash(account accounts.Account, hash []byte) ([]byte, error)
|
||||
|
||||
// SignData signs keccak256(data). The mimetype parameter describes the type of data being signed
|
||||
func (w *wallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
|
||||
return w.signHash(account, crypto.Keccak256(data))
|
||||
|
||||
// Unless we are doing 712 signing, simply dispatch to signHash
|
||||
if !(mimeType == accounts.MimetypeTypedData && len(data) == 66 && data[0] == 0x19 && data[1] == 0x01) {
|
||||
return w.signHash(account, crypto.Keccak256(data))
|
||||
}
|
||||
|
||||
// dispatch to 712 signing if the mimetype is TypedData and the format matches
|
||||
w.stateLock.RLock() // Comms have own mutex, this is for the state fields
|
||||
defer w.stateLock.RUnlock()
|
||||
|
||||
// If the wallet is closed, abort
|
||||
if w.device == nil {
|
||||
return nil, accounts.ErrWalletClosed
|
||||
}
|
||||
// Make sure the requested account is contained within
|
||||
path, ok := w.paths[account.Address]
|
||||
if !ok {
|
||||
return nil, accounts.ErrUnknownAccount
|
||||
}
|
||||
// All infos gathered and metadata checks out, request signing
|
||||
<-w.commsLock
|
||||
defer func() { w.commsLock <- struct{}{} }()
|
||||
|
||||
// Ensure the device isn't screwed with while user confirmation is pending
|
||||
// TODO(karalabe): remove if hotplug lands on Windows
|
||||
w.hub.commsLock.Lock()
|
||||
w.hub.commsPend++
|
||||
w.hub.commsLock.Unlock()
|
||||
|
||||
defer func() {
|
||||
w.hub.commsLock.Lock()
|
||||
w.hub.commsPend--
|
||||
w.hub.commsLock.Unlock()
|
||||
}()
|
||||
// Sign the transaction
|
||||
signature, err := w.driver.SignTypedMessage(path, data[2:34], data[34:66])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return signature, nil
|
||||
}
|
||||
|
||||
// SignDataWithPassphrase implements accounts.Wallet, attempting to sign the given
|
||||
|
40
appveyor.yml
40
appveyor.yml
@@ -1,41 +1,29 @@
|
||||
os: Visual Studio 2015
|
||||
|
||||
# Clone directly into GOPATH.
|
||||
clone_folder: C:\gopath\src\github.com\ethereum\go-ethereum
|
||||
os: Visual Studio 2019
|
||||
clone_depth: 5
|
||||
version: "{branch}.{build}"
|
||||
environment:
|
||||
global:
|
||||
GO111MODULE: on
|
||||
GOPATH: C:\gopath
|
||||
CC: gcc.exe
|
||||
matrix:
|
||||
# We use gcc from MSYS2 because it is the most recent compiler version available on
|
||||
# AppVeyor. Note: gcc.exe only works properly if the corresponding bin/ directory is
|
||||
# contained in PATH.
|
||||
- GETH_ARCH: amd64
|
||||
MSYS2_ARCH: x86_64
|
||||
MSYS2_BITS: 64
|
||||
MSYSTEM: MINGW64
|
||||
PATH: C:\msys64\mingw64\bin\;C:\Program Files (x86)\NSIS\;%PATH%
|
||||
GETH_CC: C:\msys64\mingw64\bin\gcc.exe
|
||||
PATH: C:\msys64\mingw64\bin;C:\Program Files (x86)\NSIS\;%PATH%
|
||||
- GETH_ARCH: 386
|
||||
MSYS2_ARCH: i686
|
||||
MSYS2_BITS: 32
|
||||
MSYSTEM: MINGW32
|
||||
PATH: C:\msys64\mingw32\bin\;C:\Program Files (x86)\NSIS\;%PATH%
|
||||
GETH_CC: C:\msys64\mingw32\bin\gcc.exe
|
||||
PATH: C:\msys64\mingw32\bin;C:\Program Files (x86)\NSIS\;%PATH%
|
||||
|
||||
install:
|
||||
- git submodule update --init
|
||||
- rmdir C:\go /s /q
|
||||
- appveyor DownloadFile https://dl.google.com/go/go1.15.5.windows-%GETH_ARCH%.zip
|
||||
- 7z x go1.15.5.windows-%GETH_ARCH%.zip -y -oC:\ > NUL
|
||||
- git submodule update --init --depth 1
|
||||
- go version
|
||||
- gcc --version
|
||||
- "%GETH_CC% --version"
|
||||
|
||||
build_script:
|
||||
- go run build\ci.go install -dlgo
|
||||
- go run build\ci.go install -dlgo -arch %GETH_ARCH% -cc %GETH_CC%
|
||||
|
||||
after_build:
|
||||
- go run build\ci.go archive -type zip -signer WINDOWS_SIGNING_KEY -upload gethstore/builds
|
||||
- go run build\ci.go nsis -signer WINDOWS_SIGNING_KEY -upload gethstore/builds
|
||||
- go run build\ci.go archive -arch %GETH_ARCH% -type zip -signer WINDOWS_SIGNING_KEY -upload gethstore/builds
|
||||
- go run build\ci.go nsis -arch %GETH_ARCH% -signer WINDOWS_SIGNING_KEY -upload gethstore/builds
|
||||
|
||||
test_script:
|
||||
- set CGO_ENABLED=1
|
||||
- go run build\ci.go test -coverage
|
||||
- go run build\ci.go test -dlgo -arch %GETH_ARCH% -cc %GETH_CC% -coverage
|
||||
|
@@ -1,31 +1,33 @@
|
||||
# This file contains sha256 checksums of optional build dependencies.
|
||||
|
||||
890bba73c5e2b19ffb1180e385ea225059eb008eb91b694875dd86ea48675817 go1.15.6.src.tar.gz
|
||||
940a73b45993a3bae5792cf324140dded34af97c548af4864d22fd6d49f3bd9f go1.15.6.darwin-amd64.tar.gz
|
||||
ad187f02158b9a9013ef03f41d14aa69c402477f178825a3940280814bcbb755 go1.15.6.linux-386.tar.gz
|
||||
3918e6cc85e7eaaa6f859f1bdbaac772e7a825b0eb423c63d3ae68b21f84b844 go1.15.6.linux-amd64.tar.gz
|
||||
f87515b9744154ffe31182da9341d0a61eb0795551173d242c8cad209239e492 go1.15.6.linux-arm64.tar.gz
|
||||
40ba9a57764e374195018ef37c38a5fbac9bbce908eab436370631a84bfc5788 go1.15.6.linux-armv6l.tar.gz
|
||||
5872eff6746a0a5f304272b27cbe9ce186f468454e95749cce01e903fbfc0e17 go1.15.6.windows-386.zip
|
||||
b7b3808bb072c2bab73175009187fd5a7f20ffe0a31739937003a14c5c4d9006 go1.15.6.windows-amd64.zip
|
||||
9d9dd5c217c1392f1b2ed5e03e1c71bf4cf8553884e57a38e68fd37fdcfe31a8 go1.15.6.freebsd-386.tar.gz
|
||||
609f065d855aed5a0b40ef0245aacbcc0b4b7882dc3b1e75ae50576cf25265ee go1.15.6.freebsd-amd64.tar.gz
|
||||
d4174fc217e749ac049eacc8827df879689f2246ac230d04991ae7df336f7cb2 go1.15.6.linux-ppc64le.tar.gz
|
||||
839cc6b67687d8bb7cb044e4a9a2eac0c090765cc8ec55ffe714dfb7cd51cf3a go1.15.6.linux-s390x.tar.gz
|
||||
ae4f6b6e2a1677d31817984655a762074b5356da50fb58722b99104870d43503 go1.16.4.src.tar.gz
|
||||
18fe94775763db3878717393b6d41371b0b45206055e49b3838328120c977d13 go1.16.4.darwin-amd64.tar.gz
|
||||
cb6b972cc42e669f3585c648198cd5b6f6d7a0811d413ad64b50c02ba06ccc3a go1.16.4.darwin-arm64.tar.gz
|
||||
cd1b146ef6e9006f27dd99e9687773e7fef30e8c985b7d41bff33e955a3bb53a go1.16.4.linux-386.tar.gz
|
||||
7154e88f5a8047aad4b80ebace58a059e36e7e2e4eb3b383127a28c711b4ff59 go1.16.4.linux-amd64.tar.gz
|
||||
8b18eb05ddda2652d69ab1b1dd1f40dd731799f43c6a58b512ad01ae5b5bba21 go1.16.4.linux-arm64.tar.gz
|
||||
a53391a800ddec749ee90d38992babb27b95cfb864027350c737b9aa8e069494 go1.16.4.linux-armv6l.tar.gz
|
||||
e75c0b114a09eb5499874162b208931dc260de0fedaeedac8621bf263c974605 go1.16.4.windows-386.zip
|
||||
d40139b7ade8a3008e3240a6f86fe8f899a9c465c917e11dac8758af216f5eb0 go1.16.4.windows-amd64.zip
|
||||
7cf2bc8a175d6d656861165bfc554f92dc78d2abf5afe5631db3579555d97409 go1.16.4.freebsd-386.tar.gz
|
||||
ccdd2b76de1941b60734408fda0d750aaa69330d8a07430eed4c56bdb3502f6f go1.16.4.freebsd-amd64.tar.gz
|
||||
80cfac566e344096a8df8f37bbd21f89e76a6fbe601406565d71a87a665fc125 go1.16.4.linux-ppc64le.tar.gz
|
||||
d6431881b3573dc29ecc24fbeab5e5ec25d8c9273aa543769c86a1a3bbac1ddf go1.16.4.linux-s390x.tar.gz
|
||||
|
||||
d998a84eea42f2271aca792a7b027ca5c1edfcba229e8e5a844c9ac3f336df35 golangci-lint-1.27.0-linux-armv7.tar.gz
|
||||
bf781f05b0d393b4bf0a327d9e62926949a4f14d7774d950c4e009fc766ed1d4 golangci-lint.exe-1.27.0-windows-amd64.zip
|
||||
bf781f05b0d393b4bf0a327d9e62926949a4f14d7774d950c4e009fc766ed1d4 golangci-lint-1.27.0-windows-amd64.zip
|
||||
0e2a57d6ba709440d3ed018ef1037465fa010ed02595829092860e5cf863042e golangci-lint-1.27.0-freebsd-386.tar.gz
|
||||
90205fc42ab5ed0096413e790d88ac9b4ed60f4c47e576d13dc0660f7ed4b013 golangci-lint-1.27.0-linux-arm64.tar.gz
|
||||
8d345e4e88520e21c113d81978e89ad77fc5b13bfdf20e5bca86b83fc4261272 golangci-lint-1.27.0-linux-amd64.tar.gz
|
||||
cc619634a77f18dc73df2a0725be13116d64328dc35131ca1737a850d6f76a59 golangci-lint-1.27.0-freebsd-armv7.tar.gz
|
||||
fe683583cfc9eeec83e498c0d6159d87b5e1919dbe4b6c3b3913089642906069 golangci-lint-1.27.0-linux-s390x.tar.gz
|
||||
058f5579bee75bdaacbaf75b75e1369f7ad877fd8b3b145aed17a17545de913e golangci-lint-1.27.0-freebsd-armv6.tar.gz
|
||||
38e1e3dadbe3f56ab62b4de82ee0b88e8fad966d8dfd740a26ef94c2edef9818 golangci-lint-1.27.0-linux-armv6.tar.gz
|
||||
071b34af5516f4e1ddcaea6011e18208f4f043e1af8ba21eeccad4585cb3d095 golangci-lint.exe-1.27.0-windows-386.zip
|
||||
071b34af5516f4e1ddcaea6011e18208f4f043e1af8ba21eeccad4585cb3d095 golangci-lint-1.27.0-windows-386.zip
|
||||
5f37e2b33914ecddb7cad38186ef4ec61d88172fc04f930fa0267c91151ff306 golangci-lint-1.27.0-linux-386.tar.gz
|
||||
4d94cfb51fdebeb205f1d5a349ac2b683c30591c5150708073c1c329e15965f0 golangci-lint-1.27.0-freebsd-amd64.tar.gz
|
||||
52572ba8ff07d5169c2365d3de3fec26dc55a97522094d13d1596199580fa281 golangci-lint-1.27.0-linux-ppc64le.tar.gz
|
||||
3fb1a1683a29c6c0a8cd76135f62b606fbdd538d5a7aeab94af1af70ffdc2fd4 golangci-lint-1.27.0-darwin-amd64.tar.gz
|
||||
7e9a47ab540aa3e8472fbf8120d28bed3b9d9cf625b955818e8bc69628d7187c golangci-lint-1.39.0-darwin-amd64.tar.gz
|
||||
574daa2c9c299b01672a6daeb1873b5f12e413cdb6dc0e30f2ff163956778064 golangci-lint-1.39.0-darwin-arm64.tar.gz
|
||||
6225f7014987324ab78e9b511f294e3f25be013728283c33918c67c8576d543e golangci-lint-1.39.0-freebsd-386.tar.gz
|
||||
6b3e76e1e5eaf0159411c8e2727f8d533989d3bb19f10e9caa6e0b9619ee267d golangci-lint-1.39.0-freebsd-amd64.tar.gz
|
||||
a301cacfff87ed9b00313d95278533c25a4527a06b040a17d969b4b7e1b8a90d golangci-lint-1.39.0-freebsd-armv7.tar.gz
|
||||
25bfd96a29c3112f508d5e4fc860dbad7afce657233c343acfa20715717d51e7 golangci-lint-1.39.0-freebsd-armv6.tar.gz
|
||||
9687e4ff15545cfc722b0e46107a94195166a505023b48a316579af25ad09505 golangci-lint-1.39.0-linux-armv7.tar.gz
|
||||
a7fa7ab2bfc99cbe5e5bcbf5684f5a997f920afbbe2f253d2feb1001d5e3c8b3 golangci-lint-1.39.0-linux-armv6.tar.gz
|
||||
c8f9634115beddb4ed9129c1f7ecd4c97c99d07aeef33e3707234097eeb51b7b golangci-lint-1.39.0-linux-mips64le.tar.gz
|
||||
d1234c213b74751f1af413302dde0e9a6d4d29aecef034af7abb07dc1b6e887f golangci-lint-1.39.0-linux-arm64.tar.gz
|
||||
df25d9267168323b163147acb823ab0215a8a3bb6898a4a9320afdfedde66817 golangci-lint-1.39.0-linux-386.tar.gz
|
||||
1767e75fba357b7651b1a796d38453558f371c60af805505ec99e166908c04b5 golangci-lint-1.39.0-linux-ppc64le.tar.gz
|
||||
25fd75bf3186b3d930ecae10185689968fd18fd8fa6f9f555d6beb04348c20f6 golangci-lint-1.39.0-linux-s390x.tar.gz
|
||||
3a73aa7468087caa62673c8adea99b4e4dff846dc72707222db85f8679b40cbf golangci-lint-1.39.0-linux-amd64.tar.gz
|
||||
578caceccf81739bda67dbfec52816709d03608c6878888ecdc0e186a094a41b golangci-lint-1.39.0-linux-mips64.tar.gz
|
||||
494b66ba0e32c8ddf6c4f6b1d05729b110900f6017eda943057e43598c17d7a8 golangci-lint-1.39.0-windows-386.zip
|
||||
52ec2e13a3cbb47147244dff8cfc35103563deb76e0459133058086fc35fb2c7 golangci-lint-1.39.0-windows-amd64.zip
|
||||
|
405
build/ci.go
405
build/ci.go
@@ -54,6 +54,7 @@ import (
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -115,7 +116,6 @@ var (
|
||||
}
|
||||
|
||||
// A debian package is created for all executables listed here.
|
||||
|
||||
debEthereum = debPackage{
|
||||
Name: "ethereum",
|
||||
Version: params.Version,
|
||||
@@ -137,11 +137,12 @@ var (
|
||||
// Note: disco is unsupported because it was officially deprecated on Launchpad.
|
||||
// Note: eoan is unsupported because it was officially deprecated on Launchpad.
|
||||
debDistroGoBoots = map[string]string{
|
||||
"trusty": "golang-1.11",
|
||||
"xenial": "golang-go",
|
||||
"bionic": "golang-go",
|
||||
"focal": "golang-go",
|
||||
"groovy": "golang-go",
|
||||
"trusty": "golang-1.11",
|
||||
"xenial": "golang-go",
|
||||
"bionic": "golang-go",
|
||||
"focal": "golang-go",
|
||||
"groovy": "golang-go",
|
||||
"hirsute": "golang-go",
|
||||
}
|
||||
|
||||
debGoBootPaths = map[string]string{
|
||||
@@ -152,7 +153,7 @@ var (
|
||||
// This is the version of go that will be downloaded by
|
||||
//
|
||||
// go run ci.go install -dlgo
|
||||
dlgoVersion = "1.15.6"
|
||||
dlgoVersion = "1.16.4"
|
||||
)
|
||||
|
||||
var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin"))
|
||||
@@ -182,6 +183,8 @@ func main() {
|
||||
doLint(os.Args[2:])
|
||||
case "archive":
|
||||
doArchive(os.Args[2:])
|
||||
case "docker":
|
||||
doDocker(os.Args[2:])
|
||||
case "debsrc":
|
||||
doDebianSource(os.Args[2:])
|
||||
case "nsis":
|
||||
@@ -208,58 +211,25 @@ func doInstall(cmdline []string) {
|
||||
cc = flag.String("cc", "", "C compiler to cross build with")
|
||||
)
|
||||
flag.CommandLine.Parse(cmdline)
|
||||
|
||||
// Configure the toolchain.
|
||||
tc := build.GoToolchain{GOARCH: *arch, CC: *cc}
|
||||
if *dlgo {
|
||||
csdb := build.MustLoadChecksums("build/checksums.txt")
|
||||
tc.Root = build.DownloadGo(csdb, dlgoVersion)
|
||||
}
|
||||
|
||||
// Configure the build.
|
||||
env := build.Env()
|
||||
|
||||
// Check local Go version. People regularly open issues about compilation
|
||||
// failure with outdated Go. This should save them the trouble.
|
||||
if !strings.Contains(runtime.Version(), "devel") {
|
||||
// Figure out the minor version number since we can't textually compare (1.10 < 1.9)
|
||||
var minor int
|
||||
fmt.Sscanf(strings.TrimPrefix(runtime.Version(), "go1."), "%d", &minor)
|
||||
if minor < 13 {
|
||||
log.Println("You have Go version", runtime.Version())
|
||||
log.Println("go-ethereum requires at least Go version 1.13 and cannot")
|
||||
log.Println("be compiled with an earlier version. Please upgrade your Go installation.")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// Choose which go command we're going to use.
|
||||
var gobuild *exec.Cmd
|
||||
if !*dlgo {
|
||||
// Default behavior: use the go version which runs ci.go right now.
|
||||
gobuild = goTool("build")
|
||||
} else {
|
||||
// Download of Go requested. This is for build environments where the
|
||||
// installed version is too old and cannot be upgraded easily.
|
||||
cachedir := filepath.Join("build", "cache")
|
||||
goroot := downloadGo(runtime.GOARCH, runtime.GOOS, cachedir)
|
||||
gobuild = localGoTool(goroot, "build")
|
||||
}
|
||||
|
||||
// Configure environment for cross build.
|
||||
if *arch != "" || *arch != runtime.GOARCH {
|
||||
gobuild.Env = append(gobuild.Env, "CGO_ENABLED=1")
|
||||
gobuild.Env = append(gobuild.Env, "GOARCH="+*arch)
|
||||
}
|
||||
|
||||
// Configure C compiler.
|
||||
if *cc != "" {
|
||||
gobuild.Env = append(gobuild.Env, "CC="+*cc)
|
||||
} else if os.Getenv("CC") != "" {
|
||||
gobuild.Env = append(gobuild.Env, "CC="+os.Getenv("CC"))
|
||||
}
|
||||
gobuild := tc.Go("build", buildFlags(env)...)
|
||||
|
||||
// arm64 CI builders are memory-constrained and can't handle concurrent builds,
|
||||
// better disable it. This check isn't the best, it should probably
|
||||
// check for something in env instead.
|
||||
if runtime.GOARCH == "arm64" {
|
||||
if env.CI && runtime.GOARCH == "arm64" {
|
||||
gobuild.Args = append(gobuild.Args, "-p", "1")
|
||||
}
|
||||
|
||||
// Put the default settings in.
|
||||
gobuild.Args = append(gobuild.Args, buildFlags(env)...)
|
||||
|
||||
// We use -trimpath to avoid leaking local paths into the built executables.
|
||||
gobuild.Args = append(gobuild.Args, "-trimpath")
|
||||
|
||||
@@ -301,53 +271,30 @@ func buildFlags(env build.Environment) (flags []string) {
|
||||
return flags
|
||||
}
|
||||
|
||||
// goTool returns the go tool. This uses the Go version which runs ci.go.
|
||||
func goTool(subcmd string, args ...string) *exec.Cmd {
|
||||
cmd := build.GoTool(subcmd, args...)
|
||||
goToolSetEnv(cmd)
|
||||
return cmd
|
||||
}
|
||||
|
||||
// localGoTool returns the go tool from the given GOROOT.
|
||||
func localGoTool(goroot string, subcmd string, args ...string) *exec.Cmd {
|
||||
gotool := filepath.Join(goroot, "bin", "go")
|
||||
cmd := exec.Command(gotool, subcmd)
|
||||
goToolSetEnv(cmd)
|
||||
cmd.Env = append(cmd.Env, "GOROOT="+goroot)
|
||||
cmd.Args = append(cmd.Args, args...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
// goToolSetEnv forwards the build environment to the go tool.
|
||||
func goToolSetEnv(cmd *exec.Cmd) {
|
||||
cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
|
||||
for _, e := range os.Environ() {
|
||||
if strings.HasPrefix(e, "GOBIN=") || strings.HasPrefix(e, "CC=") {
|
||||
continue
|
||||
}
|
||||
cmd.Env = append(cmd.Env, e)
|
||||
}
|
||||
}
|
||||
|
||||
// Running The Tests
|
||||
//
|
||||
// "tests" also includes static analysis tools such as vet.
|
||||
|
||||
func doTest(cmdline []string) {
|
||||
coverage := flag.Bool("coverage", false, "Whether to record code coverage")
|
||||
verbose := flag.Bool("v", false, "Whether to log verbosely")
|
||||
var (
|
||||
dlgo = flag.Bool("dlgo", false, "Download Go and build with it")
|
||||
arch = flag.String("arch", "", "Run tests for given architecture")
|
||||
cc = flag.String("cc", "", "Sets C compiler binary")
|
||||
coverage = flag.Bool("coverage", false, "Whether to record code coverage")
|
||||
verbose = flag.Bool("v", false, "Whether to log verbosely")
|
||||
)
|
||||
flag.CommandLine.Parse(cmdline)
|
||||
env := build.Env()
|
||||
|
||||
packages := []string{"./..."}
|
||||
if len(flag.CommandLine.Args()) > 0 {
|
||||
packages = flag.CommandLine.Args()
|
||||
// Configure the toolchain.
|
||||
tc := build.GoToolchain{GOARCH: *arch, CC: *cc}
|
||||
if *dlgo {
|
||||
csdb := build.MustLoadChecksums("build/checksums.txt")
|
||||
tc.Root = build.DownloadGo(csdb, dlgoVersion)
|
||||
}
|
||||
gotest := tc.Go("test")
|
||||
|
||||
// Run the actual tests.
|
||||
// Test a single package at a time. CI builders are slow
|
||||
// and some tests run into timeouts under load.
|
||||
gotest := goTool("test", buildFlags(env)...)
|
||||
gotest.Args = append(gotest.Args, "-p", "1")
|
||||
if *coverage {
|
||||
gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
|
||||
@@ -356,6 +303,10 @@ func doTest(cmdline []string) {
|
||||
gotest.Args = append(gotest.Args, "-v")
|
||||
}
|
||||
|
||||
packages := []string{"./..."}
|
||||
if len(flag.CommandLine.Args()) > 0 {
|
||||
packages = flag.CommandLine.Args()
|
||||
}
|
||||
gotest.Args = append(gotest.Args, packages...)
|
||||
build.MustRun(gotest)
|
||||
}
|
||||
@@ -379,7 +330,7 @@ func doLint(cmdline []string) {
|
||||
|
||||
// downloadLinter downloads and unpacks golangci-lint.
|
||||
func downloadLinter(cachedir string) string {
|
||||
const version = "1.27.0"
|
||||
const version = "1.39.0"
|
||||
|
||||
csdb := build.MustLoadChecksums("build/checksums.txt")
|
||||
base := fmt.Sprintf("golangci-lint-%s-%s-%s", version, runtime.GOOS, runtime.GOARCH)
|
||||
@@ -415,8 +366,7 @@ func doArchive(cmdline []string) {
|
||||
}
|
||||
|
||||
var (
|
||||
env = build.Env()
|
||||
|
||||
env = build.Env()
|
||||
basegeth = archiveBasename(*arch, params.ArchiveVersion(env.Commit))
|
||||
geth = "geth-" + basegeth + ext
|
||||
alltools = "geth-alltools-" + basegeth + ext
|
||||
@@ -492,19 +442,185 @@ func archiveUpload(archive string, blobstore string, signer string, signifyVar s
|
||||
// skips archiving for some build configurations.
|
||||
func maybeSkipArchive(env build.Environment) {
|
||||
if env.IsPullRequest {
|
||||
log.Printf("skipping because this is a PR build")
|
||||
log.Printf("skipping archive creation because this is a PR build")
|
||||
os.Exit(0)
|
||||
}
|
||||
if env.IsCronJob {
|
||||
log.Printf("skipping because this is a cron job")
|
||||
log.Printf("skipping archive creation because this is a cron job")
|
||||
os.Exit(0)
|
||||
}
|
||||
if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
|
||||
log.Printf("skipping because branch %q, tag %q is not on the whitelist", env.Branch, env.Tag)
|
||||
log.Printf("skipping archive creation because branch %q, tag %q is not on the inclusion list", env.Branch, env.Tag)
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
// Builds the docker images and optionally uploads them to Docker Hub.
|
||||
func doDocker(cmdline []string) {
|
||||
var (
|
||||
image = flag.Bool("image", false, `Whether to build and push an arch specific docker image`)
|
||||
manifest = flag.String("manifest", "", `Push a multi-arch docker image for the specified architectures (usually "amd64,arm64")`)
|
||||
upload = flag.String("upload", "", `Where to upload the docker image (usually "ethereum/client-go")`)
|
||||
)
|
||||
flag.CommandLine.Parse(cmdline)
|
||||
|
||||
// Skip building and pushing docker images for PR builds
|
||||
env := build.Env()
|
||||
maybeSkipArchive(env)
|
||||
|
||||
// Retrieve the upload credentials and authenticate
|
||||
user := getenvBase64("DOCKER_HUB_USERNAME")
|
||||
pass := getenvBase64("DOCKER_HUB_PASSWORD")
|
||||
|
||||
if len(user) > 0 && len(pass) > 0 {
|
||||
auther := exec.Command("docker", "login", "-u", string(user), "--password-stdin")
|
||||
auther.Stdin = bytes.NewReader(pass)
|
||||
build.MustRun(auther)
|
||||
}
|
||||
// Retrieve the version infos to build and push to the following paths:
|
||||
// - ethereum/client-go:latest - Pushes to the master branch, Geth only
|
||||
// - ethereum/client-go:stable - Version tag publish on GitHub, Geth only
|
||||
// - ethereum/client-go:alltools-latest - Pushes to the master branch, Geth & tools
|
||||
// - ethereum/client-go:alltools-stable - Version tag publish on GitHub, Geth & tools
|
||||
// - ethereum/client-go:release-<major>.<minor> - Version tag publish on GitHub, Geth only
|
||||
// - ethereum/client-go:alltools-release-<major>.<minor> - Version tag publish on GitHub, Geth & tools
|
||||
// - ethereum/client-go:v<major>.<minor>.<patch> - Version tag publish on GitHub, Geth only
|
||||
// - ethereum/client-go:alltools-v<major>.<minor>.<patch> - Version tag publish on GitHub, Geth & tools
|
||||
var tags []string
|
||||
|
||||
switch {
|
||||
case env.Branch == "master":
|
||||
tags = []string{"latest"}
|
||||
case strings.HasPrefix(env.Tag, "v1."):
|
||||
tags = []string{"stable", fmt.Sprintf("release-1.%d", params.VersionMinor), "v" + params.Version}
|
||||
}
|
||||
// If architecture specific image builds are requested, build and push them
|
||||
if *image {
|
||||
build.MustRunCommand("docker", "build", "--build-arg", "COMMIT="+env.Commit, "--build-arg", "VERSION="+params.VersionWithMeta, "--build-arg", "BUILDNUM="+env.Buildnum, "--tag", fmt.Sprintf("%s:TAG", *upload), ".")
|
||||
build.MustRunCommand("docker", "build", "--build-arg", "COMMIT="+env.Commit, "--build-arg", "VERSION="+params.VersionWithMeta, "--build-arg", "BUILDNUM="+env.Buildnum, "--tag", fmt.Sprintf("%s:alltools-TAG", *upload), "-f", "Dockerfile.alltools", ".")
|
||||
|
||||
// Tag and upload the images to Docker Hub
|
||||
for _, tag := range tags {
|
||||
gethImage := fmt.Sprintf("%s:%s-%s", *upload, tag, runtime.GOARCH)
|
||||
toolImage := fmt.Sprintf("%s:alltools-%s-%s", *upload, tag, runtime.GOARCH)
|
||||
|
||||
// If the image already exists (non version tag), check the build
|
||||
// number to prevent overwriting a newer commit if concurrent builds
|
||||
// are running. This is still a tiny bit racey if two published are
|
||||
// done at the same time, but that's extremely unlikely even on the
|
||||
// master branch.
|
||||
for _, img := range []string{gethImage, toolImage} {
|
||||
if exec.Command("docker", "pull", img).Run() != nil {
|
||||
continue // Generally the only failure is a missing image, which is good
|
||||
}
|
||||
buildnum, err := exec.Command("docker", "inspect", "--format", "{{index .Config.Labels \"buildnum\"}}", img).CombinedOutput()
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to inspect container: %v\nOutput: %s", err, string(buildnum))
|
||||
}
|
||||
buildnum = bytes.TrimSpace(buildnum)
|
||||
|
||||
if len(buildnum) > 0 && len(env.Buildnum) > 0 {
|
||||
oldnum, err := strconv.Atoi(string(buildnum))
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to parse old image build number: %v", err)
|
||||
}
|
||||
newnum, err := strconv.Atoi(env.Buildnum)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to parse current build number: %v", err)
|
||||
}
|
||||
if oldnum > newnum {
|
||||
log.Fatalf("Current build number %d not newer than existing %d", newnum, oldnum)
|
||||
} else {
|
||||
log.Printf("Updating %s from build %d to %d", img, oldnum, newnum)
|
||||
}
|
||||
}
|
||||
}
|
||||
build.MustRunCommand("docker", "image", "tag", fmt.Sprintf("%s:TAG", *upload), gethImage)
|
||||
build.MustRunCommand("docker", "image", "tag", fmt.Sprintf("%s:alltools-TAG", *upload), toolImage)
|
||||
build.MustRunCommand("docker", "push", gethImage)
|
||||
build.MustRunCommand("docker", "push", toolImage)
|
||||
}
|
||||
}
|
||||
// If multi-arch image manifest push is requested, assemble it
|
||||
if len(*manifest) != 0 {
|
||||
// Since different architectures are pushed by different builders, wait
|
||||
// until all required images are updated.
|
||||
var mismatch bool
|
||||
for i := 0; i < 2; i++ { // 2 attempts, second is race check
|
||||
mismatch = false // hope there's no mismatch now
|
||||
|
||||
for _, tag := range tags {
|
||||
for _, arch := range strings.Split(*manifest, ",") {
|
||||
gethImage := fmt.Sprintf("%s:%s-%s", *upload, tag, arch)
|
||||
toolImage := fmt.Sprintf("%s:alltools-%s-%s", *upload, tag, arch)
|
||||
|
||||
for _, img := range []string{gethImage, toolImage} {
|
||||
if out, err := exec.Command("docker", "pull", img).CombinedOutput(); err != nil {
|
||||
log.Printf("Required image %s unavailable: %v\nOutput: %s", img, err, out)
|
||||
mismatch = true
|
||||
break
|
||||
}
|
||||
buildnum, err := exec.Command("docker", "inspect", "--format", "{{index .Config.Labels \"buildnum\"}}", img).CombinedOutput()
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to inspect container: %v\nOutput: %s", err, string(buildnum))
|
||||
}
|
||||
buildnum = bytes.TrimSpace(buildnum)
|
||||
|
||||
if string(buildnum) != env.Buildnum {
|
||||
log.Printf("Build number mismatch on %s: want %s, have %s", img, env.Buildnum, buildnum)
|
||||
mismatch = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if mismatch {
|
||||
break
|
||||
}
|
||||
}
|
||||
if mismatch {
|
||||
break
|
||||
}
|
||||
}
|
||||
if mismatch {
|
||||
// Build numbers mismatching, retry in a short time to
|
||||
// avoid concurrent failes in both publisher images. If
|
||||
// however the retry failed too, it means the concurrent
|
||||
// builder is still crunching, let that do the publish.
|
||||
if i == 0 {
|
||||
time.Sleep(30 * time.Second)
|
||||
}
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
if mismatch {
|
||||
log.Println("Relinquishing publish to other builder")
|
||||
return
|
||||
}
|
||||
// Assemble and push the Geth manifest image
|
||||
for _, tag := range tags {
|
||||
gethImage := fmt.Sprintf("%s:%s", *upload, tag)
|
||||
|
||||
var gethSubImages []string
|
||||
for _, arch := range strings.Split(*manifest, ",") {
|
||||
gethSubImages = append(gethSubImages, gethImage+"-"+arch)
|
||||
}
|
||||
build.MustRunCommand("docker", append([]string{"manifest", "create", gethImage}, gethSubImages...)...)
|
||||
build.MustRunCommand("docker", "manifest", "push", gethImage)
|
||||
}
|
||||
// Assemble and push the alltools manifest image
|
||||
for _, tag := range tags {
|
||||
toolImage := fmt.Sprintf("%s:alltools-%s", *upload, tag)
|
||||
|
||||
var toolSubImages []string
|
||||
for _, arch := range strings.Split(*manifest, ",") {
|
||||
toolSubImages = append(toolSubImages, toolImage+"-"+arch)
|
||||
}
|
||||
build.MustRunCommand("docker", append([]string{"manifest", "create", toolImage}, toolSubImages...)...)
|
||||
build.MustRunCommand("docker", "manifest", "push", toolImage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Debian Packaging
|
||||
func doDebianSource(cmdline []string) {
|
||||
var (
|
||||
@@ -518,6 +634,7 @@ func doDebianSource(cmdline []string) {
|
||||
flag.CommandLine.Parse(cmdline)
|
||||
*workdir = makeWorkdir(*workdir)
|
||||
env := build.Env()
|
||||
tc := new(build.GoToolchain)
|
||||
maybeSkipArchive(env)
|
||||
|
||||
// Import the signing key.
|
||||
@@ -531,12 +648,12 @@ func doDebianSource(cmdline []string) {
|
||||
gobundle := downloadGoSources(*cachedir)
|
||||
|
||||
// Download all the dependencies needed to build the sources and run the ci script
|
||||
srcdepfetch := goTool("mod", "download")
|
||||
srcdepfetch.Env = append(os.Environ(), "GOPATH="+filepath.Join(*workdir, "modgopath"))
|
||||
srcdepfetch := tc.Go("mod", "download")
|
||||
srcdepfetch.Env = append(srcdepfetch.Env, "GOPATH="+filepath.Join(*workdir, "modgopath"))
|
||||
build.MustRun(srcdepfetch)
|
||||
|
||||
cidepfetch := goTool("run", "./build/ci.go")
|
||||
cidepfetch.Env = append(os.Environ(), "GOPATH="+filepath.Join(*workdir, "modgopath"))
|
||||
cidepfetch := tc.Go("run", "./build/ci.go")
|
||||
cidepfetch.Env = append(cidepfetch.Env, "GOPATH="+filepath.Join(*workdir, "modgopath"))
|
||||
cidepfetch.Run() // Command fails, don't care, we only need the deps to start it
|
||||
|
||||
// Create Debian packages and upload them.
|
||||
@@ -564,16 +681,17 @@ func doDebianSource(cmdline []string) {
|
||||
build.MustRun(debuild)
|
||||
|
||||
var (
|
||||
basename = fmt.Sprintf("%s_%s", meta.Name(), meta.VersionString())
|
||||
source = filepath.Join(*workdir, basename+".tar.xz")
|
||||
dsc = filepath.Join(*workdir, basename+".dsc")
|
||||
changes = filepath.Join(*workdir, basename+"_source.changes")
|
||||
basename = fmt.Sprintf("%s_%s", meta.Name(), meta.VersionString())
|
||||
source = filepath.Join(*workdir, basename+".tar.xz")
|
||||
dsc = filepath.Join(*workdir, basename+".dsc")
|
||||
changes = filepath.Join(*workdir, basename+"_source.changes")
|
||||
buildinfo = filepath.Join(*workdir, basename+"_source.buildinfo")
|
||||
)
|
||||
if *signer != "" {
|
||||
build.MustRunCommand("debsign", changes)
|
||||
}
|
||||
if *upload != "" {
|
||||
ppaUpload(*workdir, *upload, *sshUser, []string{source, dsc, changes})
|
||||
ppaUpload(*workdir, *upload, *sshUser, []string{source, dsc, changes, buildinfo})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -591,41 +709,6 @@ func downloadGoSources(cachedir string) string {
|
||||
return dst
|
||||
}
|
||||
|
||||
// downloadGo downloads the Go binary distribution and unpacks it into a temporary
|
||||
// directory. It returns the GOROOT of the unpacked toolchain.
|
||||
func downloadGo(goarch, goos, cachedir string) string {
|
||||
if goarch == "arm" {
|
||||
goarch = "armv6l"
|
||||
}
|
||||
|
||||
csdb := build.MustLoadChecksums("build/checksums.txt")
|
||||
file := fmt.Sprintf("go%s.%s-%s", dlgoVersion, goos, goarch)
|
||||
if goos == "windows" {
|
||||
file += ".zip"
|
||||
} else {
|
||||
file += ".tar.gz"
|
||||
}
|
||||
url := "https://golang.org/dl/" + file
|
||||
dst := filepath.Join(cachedir, file)
|
||||
if err := csdb.DownloadFile(url, dst); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
ucache, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
godir := filepath.Join(ucache, fmt.Sprintf("geth-go-%s-%s-%s", dlgoVersion, goos, goarch))
|
||||
if err := build.ExtractArchive(dst, godir); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
goroot, err := filepath.Abs(filepath.Join(godir, "go"))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return goroot
|
||||
}
|
||||
|
||||
func ppaUpload(workdir, ppa, sshUser string, files []string) {
|
||||
p := strings.Split(ppa, "/")
|
||||
if len(p) != 2 {
|
||||
@@ -900,13 +983,23 @@ func doAndroidArchive(cmdline []string) {
|
||||
)
|
||||
flag.CommandLine.Parse(cmdline)
|
||||
env := build.Env()
|
||||
tc := new(build.GoToolchain)
|
||||
|
||||
// Sanity check that the SDK and NDK are installed and set
|
||||
if os.Getenv("ANDROID_HOME") == "" {
|
||||
log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
|
||||
}
|
||||
|
||||
// Build gomobile.
|
||||
install := tc.Install(GOBIN, "golang.org/x/mobile/cmd/gomobile@latest", "golang.org/x/mobile/cmd/gobind@latest")
|
||||
install.Env = append(install.Env)
|
||||
build.MustRun(install)
|
||||
|
||||
// Ensure all dependencies are available. This is required to make
|
||||
// gomobile bind work because it expects go.sum to contain all checksums.
|
||||
build.MustRun(tc.Go("mod", "download"))
|
||||
|
||||
// Build the Android archive and Maven resources
|
||||
build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
|
||||
build.MustRun(gomobileTool("bind", "-ldflags", "-s -w", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/ethereum/go-ethereum/mobile"))
|
||||
|
||||
if *local {
|
||||
@@ -1026,10 +1119,16 @@ func doXCodeFramework(cmdline []string) {
|
||||
)
|
||||
flag.CommandLine.Parse(cmdline)
|
||||
env := build.Env()
|
||||
tc := new(build.GoToolchain)
|
||||
|
||||
// Build gomobile.
|
||||
build.MustRun(tc.Install(GOBIN, "golang.org/x/mobile/cmd/gomobile@latest", "golang.org/x/mobile/cmd/gobind@latest"))
|
||||
|
||||
// Ensure all dependencies are available. This is required to make
|
||||
// gomobile bind work because it expects go.sum to contain all checksums.
|
||||
build.MustRun(tc.Go("mod", "download"))
|
||||
|
||||
// Build the iOS XCode framework
|
||||
build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
|
||||
build.MustRun(gomobileTool("init"))
|
||||
bind := gomobileTool("bind", "-ldflags", "-s -w", "--target", "ios", "-v", "github.com/ethereum/go-ethereum/mobile")
|
||||
|
||||
if *local {
|
||||
@@ -1038,17 +1137,17 @@ func doXCodeFramework(cmdline []string) {
|
||||
build.MustRun(bind)
|
||||
return
|
||||
}
|
||||
|
||||
// Create the archive.
|
||||
maybeSkipArchive(env)
|
||||
archive := "geth-" + archiveBasename("ios", params.ArchiveVersion(env.Commit))
|
||||
if err := os.Mkdir(archive, os.ModePerm); err != nil {
|
||||
if err := os.MkdirAll(archive, 0755); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
bind.Dir, _ = filepath.Abs(archive)
|
||||
build.MustRun(bind)
|
||||
build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive)
|
||||
|
||||
// Skip CocoaPods deploy and Azure upload for PR builds
|
||||
maybeSkipArchive(env)
|
||||
|
||||
// Sign and upload the framework to Azure
|
||||
if err := archiveUpload(archive+".tar.gz", *upload, *signer, *signify); err != nil {
|
||||
log.Fatal(err)
|
||||
@@ -1114,10 +1213,10 @@ func doXgo(cmdline []string) {
|
||||
)
|
||||
flag.CommandLine.Parse(cmdline)
|
||||
env := build.Env()
|
||||
var tc build.GoToolchain
|
||||
|
||||
// Make sure xgo is available for cross compilation
|
||||
gogetxgo := goTool("get", "github.com/karalabe/xgo")
|
||||
build.MustRun(gogetxgo)
|
||||
build.MustRun(tc.Install(GOBIN, "github.com/karalabe/xgo@latest"))
|
||||
|
||||
// If all tools building is requested, build everything the builder wants
|
||||
args := append(buildFlags(env), flag.Args()...)
|
||||
@@ -1128,27 +1227,23 @@ func doXgo(cmdline []string) {
|
||||
if strings.HasPrefix(res, GOBIN) {
|
||||
// Binary tool found, cross build it explicitly
|
||||
args = append(args, "./"+filepath.Join("cmd", filepath.Base(res)))
|
||||
xgo := xgoTool(args)
|
||||
build.MustRun(xgo)
|
||||
build.MustRun(xgoTool(args))
|
||||
args = args[:len(args)-1]
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
// Otherwise xxecute the explicit cross compilation
|
||||
|
||||
// Otherwise execute the explicit cross compilation
|
||||
path := args[len(args)-1]
|
||||
args = append(args[:len(args)-1], []string{"--dest", GOBIN, path}...)
|
||||
|
||||
xgo := xgoTool(args)
|
||||
build.MustRun(xgo)
|
||||
build.MustRun(xgoTool(args))
|
||||
}
|
||||
|
||||
func xgoTool(args []string) *exec.Cmd {
|
||||
cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
|
||||
cmd.Env = os.Environ()
|
||||
cmd.Env = append(cmd.Env, []string{
|
||||
"GOBIN=" + GOBIN,
|
||||
}...)
|
||||
cmd.Env = append(cmd.Env, []string{"GOBIN=" + GOBIN}...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
@@ -43,7 +43,7 @@
|
||||
!ifndef Un${StrFuncName}_INCLUDED
|
||||
${Un${StrFuncName}}
|
||||
!endif
|
||||
!define un.${StrFuncName} "${Un${StrFuncName}}"
|
||||
!define un.${StrFuncName} '${Un${StrFuncName}}'
|
||||
!macroend
|
||||
|
||||
!insertmacro _IncludeStrFunction StrTok
|
||||
|
@@ -23,7 +23,7 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/ethereum/go-ethereum/signer/core"
|
||||
"github.com/ethereum/go-ethereum/signer/core/apitypes"
|
||||
"github.com/ethereum/go-ethereum/signer/fourbyte"
|
||||
)
|
||||
|
||||
@@ -41,7 +41,7 @@ func parse(data []byte) {
|
||||
if err != nil {
|
||||
die(err)
|
||||
}
|
||||
messages := core.ValidationMessages{}
|
||||
messages := apitypes.ValidationMessages{}
|
||||
db.ValidateCallData(nil, data, &messages)
|
||||
for _, m := range messages.Messages {
|
||||
fmt.Printf("%v: %v\n", m.Typ, m.Message)
|
||||
|
@@ -96,7 +96,7 @@ var (
|
||||
}
|
||||
aliasFlag = cli.StringFlag{
|
||||
Name: "alias",
|
||||
Usage: "Comma separated aliases for function and event renaming, e.g. foo=bar",
|
||||
Usage: "Comma separated aliases for function and event renaming, e.g. original1=alias1, original2=alias2",
|
||||
}
|
||||
)
|
||||
|
||||
|
@@ -28,7 +28,6 @@ import (
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/log"
|
||||
"github.com/ethereum/go-ethereum/p2p/discover"
|
||||
"github.com/ethereum/go-ethereum/p2p/discv5"
|
||||
"github.com/ethereum/go-ethereum/p2p/enode"
|
||||
"github.com/ethereum/go-ethereum/p2p/nat"
|
||||
"github.com/ethereum/go-ethereum/p2p/netutil"
|
||||
@@ -121,17 +120,17 @@ func main() {
|
||||
|
||||
printNotice(&nodeKey.PublicKey, *realaddr)
|
||||
|
||||
db, _ := enode.OpenDB("")
|
||||
ln := enode.NewLocalNode(db, nodeKey)
|
||||
cfg := discover.Config{
|
||||
PrivateKey: nodeKey,
|
||||
NetRestrict: restrictList,
|
||||
}
|
||||
if *runv5 {
|
||||
if _, err := discv5.ListenUDP(nodeKey, conn, "", restrictList); err != nil {
|
||||
if _, err := discover.ListenV5(conn, ln, cfg); err != nil {
|
||||
utils.Fatalf("%v", err)
|
||||
}
|
||||
} else {
|
||||
db, _ := enode.OpenDB("")
|
||||
ln := enode.NewLocalNode(db, nodeKey)
|
||||
cfg := discover.Config{
|
||||
PrivateKey: nodeKey,
|
||||
NetRestrict: restrictList,
|
||||
}
|
||||
if _, err := discover.ListenUDP(conn, ln, cfg); err != nil {
|
||||
utils.Fatalf("%v", err)
|
||||
}
|
||||
|
@@ -919,4 +919,4 @@ There are a couple of implementation for a UI. We'll try to keep this list up to
|
||||
| QtSigner| https://github.com/holiman/qtsigner/| Python3/QT-based| :+1:| :+1:| :+1:| :+1:| :+1:| :x: | :+1: (partially)|
|
||||
| GtkSigner| https://github.com/holiman/gtksigner| Python3/GTK-based| :+1:| :x:| :x:| :+1:| :+1:| :x: | :x: |
|
||||
| Frame | https://github.com/floating/frame/commits/go-signer| Electron-based| :x:| :x:| :x:| :x:| ?| :x: | :x: |
|
||||
| Clef UI| https://github.com/kyokan/clef-ui| Golang/QT-based| :+1:| :+1:| :x:| :+1:| :+1:| :x: | :+1: (approve tx only)|
|
||||
| Clef UI| https://github.com/ethereum/clef-ui| Golang/QT-based| :+1:| :+1:| :x:| :+1:| :+1:| :x: | :+1: (approve tx only)|
|
||||
|
@@ -50,10 +50,10 @@ import (
|
||||
"github.com/ethereum/go-ethereum/rlp"
|
||||
"github.com/ethereum/go-ethereum/rpc"
|
||||
"github.com/ethereum/go-ethereum/signer/core"
|
||||
"github.com/ethereum/go-ethereum/signer/core/apitypes"
|
||||
"github.com/ethereum/go-ethereum/signer/fourbyte"
|
||||
"github.com/ethereum/go-ethereum/signer/rules"
|
||||
"github.com/ethereum/go-ethereum/signer/storage"
|
||||
|
||||
"github.com/mattn/go-colorable"
|
||||
"github.com/mattn/go-isatty"
|
||||
"gopkg.in/urfave/cli.v1"
|
||||
@@ -107,11 +107,6 @@ var (
|
||||
Usage: "HTTP-RPC server listening port",
|
||||
Value: node.DefaultHTTPPort + 5,
|
||||
}
|
||||
legacyRPCPortFlag = cli.IntFlag{
|
||||
Name: "rpcport",
|
||||
Usage: "HTTP-RPC server listening port (Deprecated, please use --http.port).",
|
||||
Value: node.DefaultHTTPPort + 5,
|
||||
}
|
||||
signerSecretFlag = cli.StringFlag{
|
||||
Name: "signersecret",
|
||||
Usage: "A file containing the (encrypted) master seed to encrypt Clef data, e.g. keystore credentials and ruleset hash",
|
||||
@@ -250,12 +245,6 @@ var AppHelpFlagGroups = []flags.FlagGroup{
|
||||
acceptFlag,
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "ALIASED (deprecated)",
|
||||
Flags: []cli.Flag{
|
||||
legacyRPCPortFlag,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -283,7 +272,6 @@ func init() {
|
||||
testFlag,
|
||||
advancedMode,
|
||||
acceptFlag,
|
||||
legacyRPCPortFlag,
|
||||
}
|
||||
app.Action = signer
|
||||
app.Commands = []cli.Command{initCommand,
|
||||
@@ -669,7 +657,7 @@ func signer(c *cli.Context) error {
|
||||
cors := utils.SplitAndTrim(c.GlobalString(utils.HTTPCORSDomainFlag.Name))
|
||||
|
||||
srv := rpc.NewServer()
|
||||
err := node.RegisterApisFromWhitelist(rpcAPI, []string{"account"}, srv, false)
|
||||
err := node.RegisterApis(rpcAPI, []string{"account"}, srv, false)
|
||||
if err != nil {
|
||||
utils.Fatalf("Could not register API: %w", err)
|
||||
}
|
||||
@@ -677,12 +665,6 @@ func signer(c *cli.Context) error {
|
||||
|
||||
// set port
|
||||
port := c.Int(rpcPortFlag.Name)
|
||||
if c.GlobalIsSet(legacyRPCPortFlag.Name) {
|
||||
if !c.GlobalIsSet(rpcPortFlag.Name) {
|
||||
port = c.Int(legacyRPCPortFlag.Name)
|
||||
}
|
||||
log.Warn("The flag --rpcport is deprecated and will be removed in the future, please use --http.port")
|
||||
}
|
||||
|
||||
// start http server
|
||||
httpEndpoint := fmt.Sprintf("%s:%d", c.GlobalString(utils.HTTPListenAddrFlag.Name), port)
|
||||
@@ -805,14 +787,16 @@ func readMasterKey(ctx *cli.Context, ui core.UIClientAPI) ([]byte, error) {
|
||||
|
||||
// checkFile is a convenience function to check if a file
|
||||
// * exists
|
||||
// * is mode 0400
|
||||
// * is mode 0400 (unix only)
|
||||
func checkFile(filename string) error {
|
||||
info, err := os.Stat(filename)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed stat on %s: %v", filename, err)
|
||||
}
|
||||
// Check the unix permission bits
|
||||
if info.Mode().Perm()&0377 != 0 {
|
||||
// However, on windows, we cannot use the unix perm-bits, see
|
||||
// https://github.com/ethereum/go-ethereum/issues/20123
|
||||
if runtime.GOOS != "windows" && info.Mode().Perm()&0377 != 0 {
|
||||
return fmt.Errorf("file (%v) has insecure file permissions (%v)", filename, info.Mode().String())
|
||||
}
|
||||
return nil
|
||||
@@ -939,13 +923,13 @@ func testExternalUI(api *core.SignerAPI) {
|
||||
time.Sleep(delay)
|
||||
data := hexutil.Bytes([]byte{})
|
||||
to := common.NewMixedcaseAddress(a)
|
||||
tx := core.SendTxArgs{
|
||||
tx := apitypes.SendTxArgs{
|
||||
Data: &data,
|
||||
Nonce: 0x1,
|
||||
Value: hexutil.Big(*big.NewInt(6)),
|
||||
From: common.NewMixedcaseAddress(a),
|
||||
To: &to,
|
||||
GasPrice: hexutil.Big(*big.NewInt(5)),
|
||||
GasPrice: (*hexutil.Big)(big.NewInt(5)),
|
||||
Gas: 1000,
|
||||
Input: nil,
|
||||
}
|
||||
@@ -1071,17 +1055,17 @@ func GenDoc(ctx *cli.Context) {
|
||||
data := hexutil.Bytes([]byte{0x01, 0x02, 0x03, 0x04})
|
||||
add("SignTxRequest", desc, &core.SignTxRequest{
|
||||
Meta: meta,
|
||||
Callinfo: []core.ValidationInfo{
|
||||
Callinfo: []apitypes.ValidationInfo{
|
||||
{Typ: "Warning", Message: "Something looks odd, show this message as a warning"},
|
||||
{Typ: "Info", Message: "User should see this as well"},
|
||||
},
|
||||
Transaction: core.SendTxArgs{
|
||||
Transaction: apitypes.SendTxArgs{
|
||||
Data: &data,
|
||||
Nonce: 0x1,
|
||||
Value: hexutil.Big(*big.NewInt(6)),
|
||||
From: common.NewMixedcaseAddress(a),
|
||||
To: nil,
|
||||
GasPrice: hexutil.Big(*big.NewInt(5)),
|
||||
GasPrice: (*hexutil.Big)(big.NewInt(5)),
|
||||
Gas: 1000,
|
||||
Input: nil,
|
||||
}})
|
||||
@@ -1091,13 +1075,13 @@ func GenDoc(ctx *cli.Context) {
|
||||
add("SignTxResponse - approve", "Response to request to sign a transaction. This response needs to contain the `transaction`"+
|
||||
", because the UI is free to make modifications to the transaction.",
|
||||
&core.SignTxResponse{Approved: true,
|
||||
Transaction: core.SendTxArgs{
|
||||
Transaction: apitypes.SendTxArgs{
|
||||
Data: &data,
|
||||
Nonce: 0x4,
|
||||
Value: hexutil.Big(*big.NewInt(6)),
|
||||
From: common.NewMixedcaseAddress(a),
|
||||
To: nil,
|
||||
GasPrice: hexutil.Big(*big.NewInt(5)),
|
||||
GasPrice: (*hexutil.Big)(big.NewInt(5)),
|
||||
Gas: 1000,
|
||||
Input: nil,
|
||||
}})
|
||||
@@ -1122,7 +1106,7 @@ func GenDoc(ctx *cli.Context) {
|
||||
|
||||
rlpdata := common.FromHex("0xf85d640101948a8eafb1cf62bfbeb1741769dae1a9dd47996192018026a0716bd90515acb1e68e5ac5867aa11a1e65399c3349d479f5fb698554ebc6f293a04e8a4ebfff434e971e0ef12c5bf3a881b06fd04fc3f8b8a7291fb67a26a1d4ed")
|
||||
var tx types.Transaction
|
||||
rlp.DecodeBytes(rlpdata, &tx)
|
||||
tx.UnmarshalBinary(rlpdata)
|
||||
add("OnApproved - SignTransactionResult", desc, ðapi.SignTransactionResult{Raw: rlpdata, Tx: &tx})
|
||||
|
||||
}
|
||||
|
Binary file not shown.
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 20 KiB |
16
cmd/clef/testdata/sign_1559_missing_field_exp_fail.json
vendored
Normal file
16
cmd/clef/testdata/sign_1559_missing_field_exp_fail.json
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "account_signTransaction",
|
||||
"params": [
|
||||
{
|
||||
"from": "0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192",
|
||||
"to": "0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192",
|
||||
"gas": "0x333",
|
||||
"maxFeePerGas": "0x123",
|
||||
"nonce": "0x0",
|
||||
"value": "0x10",
|
||||
"data": "0x4401a6e40000000000000000000000000000000000000000000000000000000000000012"
|
||||
}
|
||||
],
|
||||
"id": 67
|
||||
}
|
16
cmd/clef/testdata/sign_1559_missing_maxfeepergas_exp_fail.json
vendored
Normal file
16
cmd/clef/testdata/sign_1559_missing_maxfeepergas_exp_fail.json
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "account_signTransaction",
|
||||
"params": [
|
||||
{
|
||||
"from": "0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192",
|
||||
"to": "0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192",
|
||||
"gas": "0x333",
|
||||
"maxPriorityFeePerGas": "0x123",
|
||||
"nonce": "0x0",
|
||||
"value": "0x10",
|
||||
"data": "0x4401a6e40000000000000000000000000000000000000000000000000000000000000012"
|
||||
}
|
||||
],
|
||||
"id": 67
|
||||
}
|
17
cmd/clef/testdata/sign_1559_tx.json
vendored
Normal file
17
cmd/clef/testdata/sign_1559_tx.json
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "account_signTransaction",
|
||||
"params": [
|
||||
{
|
||||
"from": "0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192",
|
||||
"to": "0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192",
|
||||
"gas": "0x333",
|
||||
"maxPriorityFeePerGas": "0x123",
|
||||
"maxFeePerGas": "0x123",
|
||||
"nonce": "0x0",
|
||||
"value": "0x10",
|
||||
"data": "0x4401a6e40000000000000000000000000000000000000000000000000000000000000012"
|
||||
}
|
||||
],
|
||||
"id": 67
|
||||
}
|
17
cmd/clef/testdata/sign_bad_checksum_exp_fail.json
vendored
Normal file
17
cmd/clef/testdata/sign_bad_checksum_exp_fail.json
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "account_signTransaction",
|
||||
"params": [
|
||||
{
|
||||
"from":"0x8a8eafb1cf62bfbeb1741769dae1a9dd47996192",
|
||||
"to":"0x8a8eafb1cf62bfbeb1741769dae1a9dd47996192",
|
||||
"gas": "0x333",
|
||||
"gasPrice": "0x123",
|
||||
"nonce": "0x0",
|
||||
"value": "0x10",
|
||||
"data":
|
||||
"0x4401a6e40000000000000000000000000000000000000000000000000000000000000012"
|
||||
}
|
||||
],
|
||||
"id": 67
|
||||
}
|
17
cmd/clef/testdata/sign_normal_exp_ok.json
vendored
Normal file
17
cmd/clef/testdata/sign_normal_exp_ok.json
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "account_signTransaction",
|
||||
"params": [
|
||||
{
|
||||
"from":"0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192",
|
||||
"to":"0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192",
|
||||
"gas": "0x333",
|
||||
"gasPrice": "0x123",
|
||||
"nonce": "0x0",
|
||||
"value": "0x10",
|
||||
"data":
|
||||
"0x4401a6e40000000000000000000000000000000000000000000000000000000000000012"
|
||||
}
|
||||
],
|
||||
"id": 67
|
||||
}
|
@@ -30,6 +30,29 @@ Run `devp2p dns to-route53 <directory>` to publish a tree to Amazon Route53.
|
||||
|
||||
You can find more information about these commands in the [DNS Discovery Setup Guide][dns-tutorial].
|
||||
|
||||
### Node Set Utilities
|
||||
|
||||
There are several commands for working with JSON node set files. These files are generated
|
||||
by the discovery crawlers and DNS client commands. Node sets also used as the input of the
|
||||
DNS deployer commands.
|
||||
|
||||
Run `devp2p nodeset info <nodes.json>` to display statistics of a node set.
|
||||
|
||||
Run `devp2p nodeset filter <nodes.json> <filter flags...>` to write a new, filtered node
|
||||
set to standard output. The following filters are supported:
|
||||
|
||||
- `-limit <N>` limits the output set to N entries, taking the top N nodes by score
|
||||
- `-ip <CIDR>` filters nodes by IP subnet
|
||||
- `-min-age <duration>` filters nodes by 'first seen' time
|
||||
- `-eth-network <mainnet/rinkeby/goerli/ropsten>` filters nodes by "eth" ENR entry
|
||||
- `-les-server` filters nodes by LES server support
|
||||
- `-snap` filters nodes by snap protocol support
|
||||
|
||||
For example, given a node set in `nodes.json`, you could create a filtered set containing
|
||||
up to 20 eth mainnet nodes which also support snap sync using this command:
|
||||
|
||||
devp2p nodeset filter nodes.json -eth-network mainnet -snap -limit 20
|
||||
|
||||
### Discovery v4 Utilities
|
||||
|
||||
The `devp2p discv4 ...` command family deals with the [Node Discovery v4][discv4]
|
||||
@@ -94,11 +117,23 @@ To run the eth protocol test suite against your implementation, the node needs t
|
||||
geth --datadir <datadir> --nodiscover --nat=none --networkid 19763 --verbosity 5
|
||||
```
|
||||
|
||||
Then, run the following command, replacing `<enode ID>` with the enode of the geth node:
|
||||
Then, run the following command, replacing `<enode>` with the enode of the geth node:
|
||||
```
|
||||
devp2p rlpx eth-test <enode ID> cmd/devp2p/internal/ethtest/testdata/fullchain.rlp cmd/devp2p/internal/ethtest/testdata/genesis.json
|
||||
devp2p rlpx eth-test <enode> cmd/devp2p/internal/ethtest/testdata/chain.rlp cmd/devp2p/internal/ethtest/testdata/genesis.json
|
||||
```
|
||||
|
||||
|
||||
Repeat the above process (re-initialising the node) in order to run the Eth Protocol test suite again.
|
||||
|
||||
#### Eth66 Test Suite
|
||||
|
||||
The Eth66 test suite is also a conformance test suite for the eth 66 protocol version specifically.
|
||||
To run the eth66 protocol test suite, initialize a geth node as described above and run the following command,
|
||||
replacing `<enode>` with the enode of the geth node:
|
||||
|
||||
```
|
||||
devp2p rlpx eth66-test <enode> cmd/devp2p/internal/ethtest/testdata/chain.rlp cmd/devp2p/internal/ethtest/testdata/genesis.json
|
||||
```
|
||||
|
||||
[eth]: https://github.com/ethereum/devp2p/blob/master/caps/eth.md
|
||||
[dns-tutorial]: https://geth.ethereum.org/docs/developers/dns-discovery-setup
|
||||
[discv4]: https://github.com/ethereum/devp2p/tree/master/discv4.md
|
||||
|
@@ -17,6 +17,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
@@ -79,7 +80,7 @@ func (c *cloudflareClient) checkZone(name string) error {
|
||||
c.zoneID = id
|
||||
}
|
||||
log.Info(fmt.Sprintf("Checking Permissions on zone %s", c.zoneID))
|
||||
zone, err := c.ZoneDetails(c.zoneID)
|
||||
zone, err := c.ZoneDetails(context.Background(), c.zoneID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -112,7 +113,7 @@ func (c *cloudflareClient) uploadRecords(name string, records map[string]string)
|
||||
records = lrecords
|
||||
|
||||
log.Info(fmt.Sprintf("Retrieving existing TXT records on %s", name))
|
||||
entries, err := c.DNSRecords(c.zoneID, cloudflare.DNSRecord{Type: "TXT"})
|
||||
entries, err := c.DNSRecords(context.Background(), c.zoneID, cloudflare.DNSRecord{Type: "TXT"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -134,14 +135,15 @@ func (c *cloudflareClient) uploadRecords(name string, records map[string]string)
|
||||
if path != name {
|
||||
ttl = treeNodeTTL // Max TTL permitted by Cloudflare
|
||||
}
|
||||
_, err = c.CreateDNSRecord(c.zoneID, cloudflare.DNSRecord{Type: "TXT", Name: path, Content: val, TTL: ttl})
|
||||
record := cloudflare.DNSRecord{Type: "TXT", Name: path, Content: val, TTL: ttl}
|
||||
_, err = c.CreateDNSRecord(context.Background(), c.zoneID, record)
|
||||
} else if old.Content != val {
|
||||
// Entry already exists, only change its content.
|
||||
log.Info(fmt.Sprintf("Updating %s from %q to %q", path, old.Content, val))
|
||||
old.Content = val
|
||||
err = c.UpdateDNSRecord(c.zoneID, old.ID, old)
|
||||
err = c.UpdateDNSRecord(context.Background(), c.zoneID, old.ID, old)
|
||||
} else {
|
||||
log.Info(fmt.Sprintf("Skipping %s = %q", path, val))
|
||||
log.Debug(fmt.Sprintf("Skipping %s = %q", path, val))
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to publish %s: %v", path, err)
|
||||
@@ -155,7 +157,7 @@ func (c *cloudflareClient) uploadRecords(name string, records map[string]string)
|
||||
}
|
||||
// Stale entry, nuke it.
|
||||
log.Info(fmt.Sprintf("Deleting %s = %q", path, entry.Content))
|
||||
if err := c.DeleteDNSRecord(c.zoneID, entry.ID); err != nil {
|
||||
if err := c.DeleteDNSRecord(context.Background(), c.zoneID, entry.ID); err != nil {
|
||||
return fmt.Errorf("failed to delete %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
@@ -17,16 +17,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/aws/aws-sdk-go/service/route53"
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/config"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/route53"
|
||||
"github.com/aws/aws-sdk-go-v2/service/route53/types"
|
||||
"github.com/ethereum/go-ethereum/log"
|
||||
"github.com/ethereum/go-ethereum/p2p/dnsdisc"
|
||||
"gopkg.in/urfave/cli.v1"
|
||||
@@ -38,6 +41,7 @@ const (
|
||||
// https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html#limits-api-requests-changeresourcerecordsets
|
||||
route53ChangeSizeLimit = 32000
|
||||
route53ChangeCountLimit = 1000
|
||||
maxRetryLimit = 60
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -55,10 +59,15 @@ var (
|
||||
Name: "zone-id",
|
||||
Usage: "Route53 Zone ID",
|
||||
}
|
||||
route53RegionFlag = cli.StringFlag{
|
||||
Name: "aws-region",
|
||||
Usage: "AWS Region",
|
||||
Value: "eu-central-1",
|
||||
}
|
||||
)
|
||||
|
||||
type route53Client struct {
|
||||
api *route53.Route53
|
||||
api *route53.Client
|
||||
zoneID string
|
||||
}
|
||||
|
||||
@@ -72,15 +81,16 @@ func newRoute53Client(ctx *cli.Context) *route53Client {
|
||||
akey := ctx.String(route53AccessKeyFlag.Name)
|
||||
asec := ctx.String(route53AccessSecretFlag.Name)
|
||||
if akey == "" || asec == "" {
|
||||
exit(fmt.Errorf("need Route53 Access Key ID and secret proceed"))
|
||||
exit(fmt.Errorf("need Route53 Access Key ID and secret to proceed"))
|
||||
}
|
||||
config := &aws.Config{Credentials: credentials.NewStaticCredentials(akey, asec, "")}
|
||||
session, err := session.NewSession(config)
|
||||
creds := aws.NewCredentialsCache(credentials.NewStaticCredentialsProvider(akey, asec, ""))
|
||||
cfg, err := config.LoadDefaultConfig(context.Background(), config.WithCredentialsProvider(creds))
|
||||
if err != nil {
|
||||
exit(fmt.Errorf("can't create AWS session: %v", err))
|
||||
exit(fmt.Errorf("can't initialize AWS configuration: %v", err))
|
||||
}
|
||||
cfg.Region = ctx.String(route53RegionFlag.Name)
|
||||
return &route53Client{
|
||||
api: route53.New(session),
|
||||
api: route53.NewFromConfig(cfg),
|
||||
zoneID: ctx.String(route53ZoneIDFlag.Name),
|
||||
}
|
||||
}
|
||||
@@ -97,31 +107,74 @@ func (c *route53Client) deploy(name string, t *dnsdisc.Tree) error {
|
||||
return err
|
||||
}
|
||||
log.Info(fmt.Sprintf("Found %d TXT records", len(existing)))
|
||||
|
||||
records := t.ToTXT(name)
|
||||
changes := c.computeChanges(name, records, existing)
|
||||
|
||||
// Submit to API.
|
||||
comment := fmt.Sprintf("enrtree update of %s at seq %d", name, t.Seq())
|
||||
return c.submitChanges(changes, comment)
|
||||
}
|
||||
|
||||
// deleteDomain removes all TXT records of the given domain.
|
||||
func (c *route53Client) deleteDomain(name string) error {
|
||||
if err := c.checkZone(name); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Compute DNS changes.
|
||||
existing, err := c.collectRecords(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Info(fmt.Sprintf("Found %d TXT records", len(existing)))
|
||||
changes := makeDeletionChanges(existing, nil)
|
||||
|
||||
// Submit to API.
|
||||
comment := "enrtree delete of " + name
|
||||
return c.submitChanges(changes, comment)
|
||||
}
|
||||
|
||||
// submitChanges submits the given DNS changes to Route53.
|
||||
func (c *route53Client) submitChanges(changes []types.Change, comment string) error {
|
||||
if len(changes) == 0 {
|
||||
log.Info("No DNS changes needed")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Submit change batches.
|
||||
var err error
|
||||
batches := splitChanges(changes, route53ChangeSizeLimit, route53ChangeCountLimit)
|
||||
changesToCheck := make([]*route53.ChangeResourceRecordSetsOutput, len(batches))
|
||||
for i, changes := range batches {
|
||||
log.Info(fmt.Sprintf("Submitting %d changes to Route53", len(changes)))
|
||||
batch := new(route53.ChangeBatch)
|
||||
batch.SetChanges(changes)
|
||||
batch.SetComment(fmt.Sprintf("enrtree update %d/%d of %s at seq %d", i+1, len(batches), name, t.Seq()))
|
||||
batch := &types.ChangeBatch{
|
||||
Changes: changes,
|
||||
Comment: aws.String(fmt.Sprintf("%s (%d/%d)", comment, i+1, len(batches))),
|
||||
}
|
||||
req := &route53.ChangeResourceRecordSetsInput{HostedZoneId: &c.zoneID, ChangeBatch: batch}
|
||||
resp, err := c.api.ChangeResourceRecordSets(req)
|
||||
changesToCheck[i], err = c.api.ChangeResourceRecordSets(context.TODO(), req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
log.Info(fmt.Sprintf("Waiting for change request %s", *resp.ChangeInfo.Id))
|
||||
wreq := &route53.GetChangeInput{Id: resp.ChangeInfo.Id}
|
||||
if err := c.api.WaitUntilResourceRecordSetsChanged(wreq); err != nil {
|
||||
return err
|
||||
// Wait for all change batches to propagate.
|
||||
for _, change := range changesToCheck {
|
||||
log.Info(fmt.Sprintf("Waiting for change request %s", *change.ChangeInfo.Id))
|
||||
wreq := &route53.GetChangeInput{Id: change.ChangeInfo.Id}
|
||||
var count int
|
||||
for {
|
||||
wresp, err := c.api.GetChange(context.TODO(), wreq)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
count++
|
||||
|
||||
if wresp.ChangeInfo.Status == types.ChangeStatusInsync || count >= maxRetryLimit {
|
||||
break
|
||||
}
|
||||
|
||||
time.Sleep(30 * time.Second)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -140,7 +193,7 @@ func (c *route53Client) findZoneID(name string) (string, error) {
|
||||
log.Info(fmt.Sprintf("Finding Route53 Zone ID for %s", name))
|
||||
var req route53.ListHostedZonesByNameInput
|
||||
for {
|
||||
resp, err := c.api.ListHostedZonesByName(&req)
|
||||
resp, err := c.api.ListHostedZonesByName(context.TODO(), &req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -149,7 +202,7 @@ func (c *route53Client) findZoneID(name string) (string, error) {
|
||||
return *zone.Id, nil
|
||||
}
|
||||
}
|
||||
if !*resp.IsTruncated {
|
||||
if !resp.IsTruncated {
|
||||
break
|
||||
}
|
||||
req.DNSName = resp.NextDNSName
|
||||
@@ -158,8 +211,9 @@ func (c *route53Client) findZoneID(name string) (string, error) {
|
||||
return "", errors.New("can't find zone ID for " + name)
|
||||
}
|
||||
|
||||
// computeChanges creates DNS changes for the given record.
|
||||
func (c *route53Client) computeChanges(name string, records map[string]string, existing map[string]recordSet) []*route53.Change {
|
||||
// computeChanges creates DNS changes for the given set of DNS discovery records.
|
||||
// The 'existing' arg is the set of records that already exist on Route53.
|
||||
func (c *route53Client) computeChanges(name string, records map[string]string, existing map[string]recordSet) []types.Change {
|
||||
// Convert all names to lowercase.
|
||||
lrecords := make(map[string]string, len(records))
|
||||
for name, r := range records {
|
||||
@@ -167,58 +221,70 @@ func (c *route53Client) computeChanges(name string, records map[string]string, e
|
||||
}
|
||||
records = lrecords
|
||||
|
||||
var changes []*route53.Change
|
||||
for path, val := range records {
|
||||
var changes []types.Change
|
||||
for path, newValue := range records {
|
||||
prevRecords, exists := existing[path]
|
||||
prevValue := strings.Join(prevRecords.values, "")
|
||||
|
||||
// prevValue contains quoted strings, encode newValue to compare.
|
||||
newValue = splitTXT(newValue)
|
||||
|
||||
// Assign TTL.
|
||||
ttl := int64(rootTTL)
|
||||
if path != name {
|
||||
ttl = int64(treeNodeTTL)
|
||||
}
|
||||
|
||||
prevRecords, exists := existing[path]
|
||||
prevValue := strings.Join(prevRecords.values, "")
|
||||
if !exists {
|
||||
// Entry is unknown, push a new one
|
||||
log.Info(fmt.Sprintf("Creating %s = %q", path, val))
|
||||
changes = append(changes, newTXTChange("CREATE", path, ttl, splitTXT(val)))
|
||||
} else if prevValue != val || prevRecords.ttl != ttl {
|
||||
log.Info(fmt.Sprintf("Creating %s = %s", path, newValue))
|
||||
changes = append(changes, newTXTChange("CREATE", path, ttl, newValue))
|
||||
} else if prevValue != newValue || prevRecords.ttl != ttl {
|
||||
// Entry already exists, only change its content.
|
||||
log.Info(fmt.Sprintf("Updating %s from %q to %q", path, prevValue, val))
|
||||
changes = append(changes, newTXTChange("UPSERT", path, ttl, splitTXT(val)))
|
||||
log.Info(fmt.Sprintf("Updating %s from %s to %s", path, prevValue, newValue))
|
||||
changes = append(changes, newTXTChange("UPSERT", path, ttl, newValue))
|
||||
} else {
|
||||
log.Info(fmt.Sprintf("Skipping %s = %q", path, val))
|
||||
log.Debug(fmt.Sprintf("Skipping %s = %s", path, newValue))
|
||||
}
|
||||
}
|
||||
|
||||
// Iterate over the old records and delete anything stale.
|
||||
for path, set := range existing {
|
||||
if _, ok := records[path]; ok {
|
||||
continue
|
||||
}
|
||||
// Stale entry, nuke it.
|
||||
log.Info(fmt.Sprintf("Deleting %s = %q", path, strings.Join(set.values, "")))
|
||||
changes = append(changes, newTXTChange("DELETE", path, set.ttl, set.values...))
|
||||
}
|
||||
changes = append(changes, makeDeletionChanges(existing, records)...)
|
||||
|
||||
// Ensure changes are in the correct order.
|
||||
sortChanges(changes)
|
||||
return changes
|
||||
}
|
||||
|
||||
// makeDeletionChanges creates record changes which delete all records not contained in 'keep'.
|
||||
func makeDeletionChanges(records map[string]recordSet, keep map[string]string) []types.Change {
|
||||
var changes []types.Change
|
||||
for path, set := range records {
|
||||
if _, ok := keep[path]; ok {
|
||||
continue
|
||||
}
|
||||
log.Info(fmt.Sprintf("Deleting %s = %s", path, strings.Join(set.values, "")))
|
||||
changes = append(changes, newTXTChange("DELETE", path, set.ttl, set.values...))
|
||||
}
|
||||
return changes
|
||||
}
|
||||
|
||||
// sortChanges ensures DNS changes are in leaf-added -> root-changed -> leaf-deleted order.
|
||||
func sortChanges(changes []*route53.Change) {
|
||||
func sortChanges(changes []types.Change) {
|
||||
score := map[string]int{"CREATE": 1, "UPSERT": 2, "DELETE": 3}
|
||||
sort.Slice(changes, func(i, j int) bool {
|
||||
if *changes[i].Action == *changes[j].Action {
|
||||
if changes[i].Action == changes[j].Action {
|
||||
return *changes[i].ResourceRecordSet.Name < *changes[j].ResourceRecordSet.Name
|
||||
}
|
||||
return score[*changes[i].Action] < score[*changes[j].Action]
|
||||
return score[string(changes[i].Action)] < score[string(changes[j].Action)]
|
||||
})
|
||||
}
|
||||
|
||||
// splitChanges splits up DNS changes such that each change batch
|
||||
// is smaller than the given RDATA limit.
|
||||
func splitChanges(changes []*route53.Change, sizeLimit, countLimit int) [][]*route53.Change {
|
||||
func splitChanges(changes []types.Change, sizeLimit, countLimit int) [][]types.Change {
|
||||
var (
|
||||
batches [][]*route53.Change
|
||||
batches [][]types.Change
|
||||
batchSize int
|
||||
batchCount int
|
||||
)
|
||||
@@ -241,7 +307,7 @@ func splitChanges(changes []*route53.Change, sizeLimit, countLimit int) [][]*rou
|
||||
}
|
||||
|
||||
// changeSize returns the RDATA size of a DNS change.
|
||||
func changeSize(ch *route53.Change) int {
|
||||
func changeSize(ch types.Change) int {
|
||||
size := 0
|
||||
for _, rr := range ch.ResourceRecordSet.ResourceRecords {
|
||||
if rr.Value != nil {
|
||||
@@ -251,8 +317,8 @@ func changeSize(ch *route53.Change) int {
|
||||
return size
|
||||
}
|
||||
|
||||
func changeCount(ch *route53.Change) int {
|
||||
if *ch.Action == "UPSERT" {
|
||||
func changeCount(ch types.Change) int {
|
||||
if ch.Action == types.ChangeActionUpsert {
|
||||
return 2
|
||||
}
|
||||
return 1
|
||||
@@ -260,13 +326,17 @@ func changeCount(ch *route53.Change) int {
|
||||
|
||||
// collectRecords collects all TXT records below the given name.
|
||||
func (c *route53Client) collectRecords(name string) (map[string]recordSet, error) {
|
||||
log.Info(fmt.Sprintf("Retrieving existing TXT records on %s (%s)", name, c.zoneID))
|
||||
var req route53.ListResourceRecordSetsInput
|
||||
req.SetHostedZoneId(c.zoneID)
|
||||
req.HostedZoneId = &c.zoneID
|
||||
existing := make(map[string]recordSet)
|
||||
err := c.api.ListResourceRecordSetsPages(&req, func(resp *route53.ListResourceRecordSetsOutput, last bool) bool {
|
||||
for page := 0; ; page++ {
|
||||
log.Info("Loading existing TXT records", "name", name, "zone", c.zoneID, "page", page)
|
||||
resp, err := c.api.ListResourceRecordSets(context.TODO(), &req)
|
||||
if err != nil {
|
||||
return existing, err
|
||||
}
|
||||
for _, set := range resp.ResourceRecordSets {
|
||||
if !isSubdomain(*set.Name, name) || *set.Type != "TXT" {
|
||||
if !isSubdomain(*set.Name, name) || set.Type != types.RRTypeTxt {
|
||||
continue
|
||||
}
|
||||
s := recordSet{ttl: *set.TTL}
|
||||
@@ -276,28 +346,44 @@ func (c *route53Client) collectRecords(name string) (map[string]recordSet, error
|
||||
name := strings.TrimSuffix(*set.Name, ".")
|
||||
existing[name] = s
|
||||
}
|
||||
return true
|
||||
})
|
||||
return existing, err
|
||||
|
||||
if !resp.IsTruncated {
|
||||
break
|
||||
}
|
||||
// Set the cursor to the next batch. From the AWS docs:
|
||||
//
|
||||
// To display the next page of results, get the values of NextRecordName,
|
||||
// NextRecordType, and NextRecordIdentifier (if any) from the response. Then submit
|
||||
// another ListResourceRecordSets request, and specify those values for
|
||||
// StartRecordName, StartRecordType, and StartRecordIdentifier.
|
||||
req.StartRecordIdentifier = resp.NextRecordIdentifier
|
||||
req.StartRecordName = resp.NextRecordName
|
||||
req.StartRecordType = resp.NextRecordType
|
||||
}
|
||||
|
||||
return existing, nil
|
||||
}
|
||||
|
||||
// newTXTChange creates a change to a TXT record.
|
||||
func newTXTChange(action, name string, ttl int64, values ...string) *route53.Change {
|
||||
var c route53.Change
|
||||
var r route53.ResourceRecordSet
|
||||
var rrs []*route53.ResourceRecord
|
||||
func newTXTChange(action, name string, ttl int64, values ...string) types.Change {
|
||||
r := types.ResourceRecordSet{
|
||||
Type: types.RRTypeTxt,
|
||||
Name: &name,
|
||||
TTL: &ttl,
|
||||
}
|
||||
var rrs []types.ResourceRecord
|
||||
for _, val := range values {
|
||||
rr := new(route53.ResourceRecord)
|
||||
rr.SetValue(val)
|
||||
var rr types.ResourceRecord
|
||||
rr.Value = aws.String(val)
|
||||
rrs = append(rrs, rr)
|
||||
}
|
||||
r.SetType("TXT")
|
||||
r.SetName(name)
|
||||
r.SetTTL(ttl)
|
||||
r.SetResourceRecords(rrs)
|
||||
c.SetAction(action)
|
||||
c.SetResourceRecordSet(&r)
|
||||
return &c
|
||||
|
||||
r.ResourceRecords = rrs
|
||||
|
||||
return types.Change{
|
||||
Action: types.ChangeAction(action),
|
||||
ResourceRecordSet: &r,
|
||||
}
|
||||
}
|
||||
|
||||
// isSubdomain returns true if name is a subdomain of domain.
|
||||
|
@@ -20,7 +20,7 @@ import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go/service/route53"
|
||||
"github.com/aws/aws-sdk-go-v2/service/route53/types"
|
||||
)
|
||||
|
||||
// This test checks that computeChanges/splitChanges create DNS changes in
|
||||
@@ -43,93 +43,93 @@ func TestRoute53ChangeSort(t *testing.T) {
|
||||
"MHTDO6TMUBRIA2XWG5LUDACK24.n": "enr:-HW4QLAYqmrwllBEnzWWs7I5Ev2IAs7x_dZlbYdRdMUx5EyKHDXp7AV5CkuPGUPdvbv1_Ms1CPfhcGCvSElSosZmyoqAgmlkgnY0iXNlY3AyNTZrMaECriawHKWdDRk2xeZkrOXBQ0dfMFLHY4eENZwdufn1S1o",
|
||||
}
|
||||
|
||||
wantChanges := []*route53.Change{
|
||||
wantChanges := []types.Change{
|
||||
{
|
||||
Action: sp("CREATE"),
|
||||
ResourceRecordSet: &route53.ResourceRecordSet{
|
||||
Action: "CREATE",
|
||||
ResourceRecordSet: &types.ResourceRecordSet{
|
||||
Name: sp("2xs2367yhaxjfglzhvawlqd4zy.n"),
|
||||
ResourceRecords: []*route53.ResourceRecord{{
|
||||
ResourceRecords: []types.ResourceRecord{{
|
||||
Value: sp(`"enr:-HW4QOFzoVLaFJnNhbgMoDXPnOvcdVuj7pDpqRvh6BRDO68aVi5ZcjB3vzQRZH2IcLBGHzo8uUN3snqmgTiE56CH3AMBgmlkgnY0iXNlY3AyNTZrMaECC2_24YYkYHEgdzxlSNKQEnHhuNAbNlMlWJxrJxbAFvA"`),
|
||||
}},
|
||||
TTL: ip(treeNodeTTL),
|
||||
Type: sp("TXT"),
|
||||
Type: "TXT",
|
||||
},
|
||||
},
|
||||
{
|
||||
Action: sp("CREATE"),
|
||||
ResourceRecordSet: &route53.ResourceRecordSet{
|
||||
Action: "CREATE",
|
||||
ResourceRecordSet: &types.ResourceRecordSet{
|
||||
Name: sp("c7hrfpf3blgf3yr4dy5kx3smbe.n"),
|
||||
ResourceRecords: []*route53.ResourceRecord{{
|
||||
ResourceRecords: []types.ResourceRecord{{
|
||||
Value: sp(`"enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.example.org"`),
|
||||
}},
|
||||
TTL: ip(treeNodeTTL),
|
||||
Type: sp("TXT"),
|
||||
Type: "TXT",
|
||||
},
|
||||
},
|
||||
{
|
||||
Action: sp("CREATE"),
|
||||
ResourceRecordSet: &route53.ResourceRecordSet{
|
||||
Action: "CREATE",
|
||||
ResourceRecordSet: &types.ResourceRecordSet{
|
||||
Name: sp("h4fht4b454p6uxfd7jcyq5pwdy.n"),
|
||||
ResourceRecords: []*route53.ResourceRecord{{
|
||||
ResourceRecords: []types.ResourceRecord{{
|
||||
Value: sp(`"enr:-HW4QAggRauloj2SDLtIHN1XBkvhFZ1vtf1raYQp9TBW2RD5EEawDzbtSmlXUfnaHcvwOizhVYLtr7e6vw7NAf6mTuoCgmlkgnY0iXNlY3AyNTZrMaECjrXI8TLNXU0f8cthpAMxEshUyQlK-AM0PW2wfrnacNI"`),
|
||||
}},
|
||||
TTL: ip(treeNodeTTL),
|
||||
Type: sp("TXT"),
|
||||
Type: "TXT",
|
||||
},
|
||||
},
|
||||
{
|
||||
Action: sp("CREATE"),
|
||||
ResourceRecordSet: &route53.ResourceRecordSet{
|
||||
Action: "CREATE",
|
||||
ResourceRecordSet: &types.ResourceRecordSet{
|
||||
Name: sp("jwxydbpxywg6fx3gmdibfa6cj4.n"),
|
||||
ResourceRecords: []*route53.ResourceRecord{{
|
||||
ResourceRecords: []types.ResourceRecord{{
|
||||
Value: sp(`"enrtree-branch:2XS2367YHAXJFGLZHVAWLQD4ZY,H4FHT4B454P6UXFD7JCYQ5PWDY,MHTDO6TMUBRIA2XWG5LUDACK24"`),
|
||||
}},
|
||||
TTL: ip(treeNodeTTL),
|
||||
Type: sp("TXT"),
|
||||
Type: "TXT",
|
||||
},
|
||||
},
|
||||
{
|
||||
Action: sp("CREATE"),
|
||||
ResourceRecordSet: &route53.ResourceRecordSet{
|
||||
Action: "CREATE",
|
||||
ResourceRecordSet: &types.ResourceRecordSet{
|
||||
Name: sp("mhtdo6tmubria2xwg5ludack24.n"),
|
||||
ResourceRecords: []*route53.ResourceRecord{{
|
||||
ResourceRecords: []types.ResourceRecord{{
|
||||
Value: sp(`"enr:-HW4QLAYqmrwllBEnzWWs7I5Ev2IAs7x_dZlbYdRdMUx5EyKHDXp7AV5CkuPGUPdvbv1_Ms1CPfhcGCvSElSosZmyoqAgmlkgnY0iXNlY3AyNTZrMaECriawHKWdDRk2xeZkrOXBQ0dfMFLHY4eENZwdufn1S1o"`),
|
||||
}},
|
||||
TTL: ip(treeNodeTTL),
|
||||
Type: sp("TXT"),
|
||||
Type: "TXT",
|
||||
},
|
||||
},
|
||||
{
|
||||
Action: sp("UPSERT"),
|
||||
ResourceRecordSet: &route53.ResourceRecordSet{
|
||||
Action: "UPSERT",
|
||||
ResourceRecordSet: &types.ResourceRecordSet{
|
||||
Name: sp("n"),
|
||||
ResourceRecords: []*route53.ResourceRecord{{
|
||||
ResourceRecords: []types.ResourceRecord{{
|
||||
Value: sp(`"enrtree-root:v1 e=JWXYDBPXYWG6FX3GMDIBFA6CJ4 l=C7HRFPF3BLGF3YR4DY5KX3SMBE seq=1 sig=o908WmNp7LibOfPsr4btQwatZJ5URBr2ZAuxvK4UWHlsB9sUOTJQaGAlLPVAhM__XJesCHxLISo94z5Z2a463gA"`),
|
||||
}},
|
||||
TTL: ip(rootTTL),
|
||||
Type: sp("TXT"),
|
||||
Type: "TXT",
|
||||
},
|
||||
},
|
||||
{
|
||||
Action: sp("DELETE"),
|
||||
ResourceRecordSet: &route53.ResourceRecordSet{
|
||||
Action: "DELETE",
|
||||
ResourceRecordSet: &types.ResourceRecordSet{
|
||||
Name: sp("2kfjogvxdqtxxugbh7gs7naaai.n"),
|
||||
ResourceRecords: []*route53.ResourceRecord{
|
||||
ResourceRecords: []types.ResourceRecord{
|
||||
{Value: sp(`"enr:-HW4QO1ml1DdXLeZLsUxewnthhUy8eROqkDyoMTyavfks9JlYQIlMFEUoM78PovJDPQrAkrb3LRJ-""vtrymDguKCOIAWAgmlkgnY0iXNlY3AyNTZrMaEDffaGfJzgGhUif1JqFruZlYmA31HzathLSWxfbq_QoQ4"`)},
|
||||
},
|
||||
TTL: ip(3333),
|
||||
Type: sp("TXT"),
|
||||
Type: "TXT",
|
||||
},
|
||||
},
|
||||
{
|
||||
Action: sp("DELETE"),
|
||||
ResourceRecordSet: &route53.ResourceRecordSet{
|
||||
Action: "DELETE",
|
||||
ResourceRecordSet: &types.ResourceRecordSet{
|
||||
Name: sp("fdxn3sn67na5dka4j2gok7bvqi.n"),
|
||||
ResourceRecords: []*route53.ResourceRecord{{
|
||||
ResourceRecords: []types.ResourceRecord{{
|
||||
Value: sp(`"enrtree-branch:"`),
|
||||
}},
|
||||
TTL: ip(treeNodeTTL),
|
||||
Type: sp("TXT"),
|
||||
Type: "TXT",
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -141,7 +141,7 @@ func TestRoute53ChangeSort(t *testing.T) {
|
||||
}
|
||||
|
||||
// Check splitting according to size.
|
||||
wantSplit := [][]*route53.Change{
|
||||
wantSplit := [][]types.Change{
|
||||
wantChanges[:4],
|
||||
wantChanges[4:6],
|
||||
wantChanges[6:],
|
||||
@@ -152,7 +152,7 @@ func TestRoute53ChangeSort(t *testing.T) {
|
||||
}
|
||||
|
||||
// Check splitting according to count.
|
||||
wantSplit = [][]*route53.Change{
|
||||
wantSplit = [][]types.Change{
|
||||
wantChanges[:5],
|
||||
wantChanges[5:],
|
||||
}
|
||||
@@ -162,5 +162,29 @@ func TestRoute53ChangeSort(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// This test checks that computeChanges compares the quoted value of the records correctly.
|
||||
func TestRoute53NoChange(t *testing.T) {
|
||||
// Existing record set.
|
||||
testTree0 := map[string]recordSet{
|
||||
"n": {ttl: rootTTL, values: []string{
|
||||
`"enrtree-root:v1 e=JWXYDBPXYWG6FX3GMDIBFA6CJ4 l=C7HRFPF3BLGF3YR4DY5KX3SMBE seq=1 sig=o908WmNp7LibOfPsr4btQwatZJ5URBr2ZAuxvK4UWHlsB9sUOTJQaGAlLPVAhM__XJesCHxLISo94z5Z2a463gA"`,
|
||||
}},
|
||||
"2xs2367yhaxjfglzhvawlqd4zy.n": {ttl: treeNodeTTL, values: []string{
|
||||
`"enr:-HW4QOFzoVLaFJnNhbgMoDXPnOvcdVuj7pDpqRvh6BRDO68aVi5ZcjB3vzQRZH2IcLBGHzo8uUN3snqmgTiE56CH3AMBgmlkgnY0iXNlY3AyNTZrMaECC2_24YYkYHEgdzxlSNKQEnHhuNAbNlMlWJxrJxbAFvA"`,
|
||||
}},
|
||||
}
|
||||
// New set.
|
||||
testTree1 := map[string]string{
|
||||
"n": "enrtree-root:v1 e=JWXYDBPXYWG6FX3GMDIBFA6CJ4 l=C7HRFPF3BLGF3YR4DY5KX3SMBE seq=1 sig=o908WmNp7LibOfPsr4btQwatZJ5URBr2ZAuxvK4UWHlsB9sUOTJQaGAlLPVAhM__XJesCHxLISo94z5Z2a463gA",
|
||||
"2XS2367YHAXJFGLZHVAWLQD4ZY.n": "enr:-HW4QOFzoVLaFJnNhbgMoDXPnOvcdVuj7pDpqRvh6BRDO68aVi5ZcjB3vzQRZH2IcLBGHzo8uUN3snqmgTiE56CH3AMBgmlkgnY0iXNlY3AyNTZrMaECC2_24YYkYHEgdzxlSNKQEnHhuNAbNlMlWJxrJxbAFvA",
|
||||
}
|
||||
|
||||
var client route53Client
|
||||
changes := client.computeChanges("n", testTree1, testTree0)
|
||||
if len(changes) > 0 {
|
||||
t.Fatalf("wrong changes (got %d, want 0)", len(changes))
|
||||
}
|
||||
}
|
||||
|
||||
func sp(s string) *string { return &s }
|
||||
func ip(i int64) *int64 { return &i }
|
||||
|
@@ -43,6 +43,7 @@ var (
|
||||
dnsTXTCommand,
|
||||
dnsCloudflareCommand,
|
||||
dnsRoute53Command,
|
||||
dnsRoute53NukeCommand,
|
||||
},
|
||||
}
|
||||
dnsSyncCommand = cli.Command{
|
||||
@@ -77,7 +78,24 @@ var (
|
||||
Usage: "Deploy DNS TXT records to Amazon Route53",
|
||||
ArgsUsage: "<tree-directory>",
|
||||
Action: dnsToRoute53,
|
||||
Flags: []cli.Flag{route53AccessKeyFlag, route53AccessSecretFlag, route53ZoneIDFlag},
|
||||
Flags: []cli.Flag{
|
||||
route53AccessKeyFlag,
|
||||
route53AccessSecretFlag,
|
||||
route53ZoneIDFlag,
|
||||
route53RegionFlag,
|
||||
},
|
||||
}
|
||||
dnsRoute53NukeCommand = cli.Command{
|
||||
Name: "nuke-route53",
|
||||
Usage: "Deletes DNS TXT records of a subdomain on Amazon Route53",
|
||||
ArgsUsage: "<domain>",
|
||||
Action: dnsNukeRoute53,
|
||||
Flags: []cli.Flag{
|
||||
route53AccessKeyFlag,
|
||||
route53AccessSecretFlag,
|
||||
route53ZoneIDFlag,
|
||||
route53RegionFlag,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
@@ -169,6 +187,9 @@ func dnsSign(ctx *cli.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// directoryName returns the directory name of the given path.
|
||||
// For example, when dir is "foo/bar", it returns "bar".
|
||||
// When dir is ".", and the working directory is "example/foo", it returns "foo".
|
||||
func directoryName(dir string) string {
|
||||
abs, err := filepath.Abs(dir)
|
||||
if err != nil {
|
||||
@@ -177,7 +198,7 @@ func directoryName(dir string) string {
|
||||
return filepath.Base(abs)
|
||||
}
|
||||
|
||||
// dnsToTXT peforms dnsTXTCommand.
|
||||
// dnsToTXT performs dnsTXTCommand.
|
||||
func dnsToTXT(ctx *cli.Context) error {
|
||||
if ctx.NArg() < 1 {
|
||||
return fmt.Errorf("need tree definition directory as argument")
|
||||
@@ -194,9 +215,9 @@ func dnsToTXT(ctx *cli.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// dnsToCloudflare peforms dnsCloudflareCommand.
|
||||
// dnsToCloudflare performs dnsCloudflareCommand.
|
||||
func dnsToCloudflare(ctx *cli.Context) error {
|
||||
if ctx.NArg() < 1 {
|
||||
if ctx.NArg() != 1 {
|
||||
return fmt.Errorf("need tree definition directory as argument")
|
||||
}
|
||||
domain, t, err := loadTreeDefinitionForExport(ctx.Args().Get(0))
|
||||
@@ -207,9 +228,9 @@ func dnsToCloudflare(ctx *cli.Context) error {
|
||||
return client.deploy(domain, t)
|
||||
}
|
||||
|
||||
// dnsToRoute53 peforms dnsRoute53Command.
|
||||
// dnsToRoute53 performs dnsRoute53Command.
|
||||
func dnsToRoute53(ctx *cli.Context) error {
|
||||
if ctx.NArg() < 1 {
|
||||
if ctx.NArg() != 1 {
|
||||
return fmt.Errorf("need tree definition directory as argument")
|
||||
}
|
||||
domain, t, err := loadTreeDefinitionForExport(ctx.Args().Get(0))
|
||||
@@ -220,6 +241,15 @@ func dnsToRoute53(ctx *cli.Context) error {
|
||||
return client.deploy(domain, t)
|
||||
}
|
||||
|
||||
// dnsNukeRoute53 performs dnsRoute53NukeCommand.
|
||||
func dnsNukeRoute53(ctx *cli.Context) error {
|
||||
if ctx.NArg() != 1 {
|
||||
return fmt.Errorf("need domain name as argument")
|
||||
}
|
||||
client := newRoute53Client(ctx)
|
||||
return client.deleteDomain(ctx.Args().First())
|
||||
}
|
||||
|
||||
// loadSigningKey loads a private key in Ethereum keystore format.
|
||||
func loadSigningKey(keyfile string) *ecdsa.PrivateKey {
|
||||
keyjson, err := ioutil.ReadFile(keyfile)
|
||||
|
@@ -34,6 +34,7 @@ import (
|
||||
)
|
||||
|
||||
type Chain struct {
|
||||
genesis core.Genesis
|
||||
blocks []*types.Block
|
||||
chainConfig *params.ChainConfig
|
||||
}
|
||||
@@ -53,10 +54,24 @@ func (c *Chain) Len() int {
|
||||
return len(c.blocks)
|
||||
}
|
||||
|
||||
// TD calculates the total difficulty of the chain.
|
||||
func (c *Chain) TD(height int) *big.Int { // TODO later on channge scheme so that the height is included in range
|
||||
// TD calculates the total difficulty of the chain at the
|
||||
// chain head.
|
||||
func (c *Chain) TD() *big.Int {
|
||||
sum := big.NewInt(0)
|
||||
for _, block := range c.blocks[:height] {
|
||||
for _, block := range c.blocks[:c.Len()] {
|
||||
sum.Add(sum, block.Difficulty())
|
||||
}
|
||||
return sum
|
||||
}
|
||||
|
||||
// TotalDifficultyAt calculates the total difficulty of the chain
|
||||
// at the given block height.
|
||||
func (c *Chain) TotalDifficultyAt(height int) *big.Int {
|
||||
sum := big.NewInt(0)
|
||||
if height >= c.Len() {
|
||||
return sum
|
||||
}
|
||||
for _, block := range c.blocks[:height+1] {
|
||||
sum.Add(sum, block.Difficulty())
|
||||
}
|
||||
return sum
|
||||
@@ -124,16 +139,34 @@ func (c *Chain) GetHeaders(req GetBlockHeaders) (BlockHeaders, error) {
|
||||
// loadChain takes the given chain.rlp file, and decodes and returns
|
||||
// the blocks from the file.
|
||||
func loadChain(chainfile string, genesis string) (*Chain, error) {
|
||||
chainConfig, err := ioutil.ReadFile(genesis)
|
||||
gen, err := loadGenesis(genesis)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var gen core.Genesis
|
||||
if err := json.Unmarshal(chainConfig, &gen); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
gblock := gen.ToBlock(nil)
|
||||
|
||||
blocks, err := blocksFromFile(chainfile, gblock)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c := &Chain{genesis: gen, blocks: blocks, chainConfig: gen.Config}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func loadGenesis(genesisFile string) (core.Genesis, error) {
|
||||
chainConfig, err := ioutil.ReadFile(genesisFile)
|
||||
if err != nil {
|
||||
return core.Genesis{}, err
|
||||
}
|
||||
var gen core.Genesis
|
||||
if err := json.Unmarshal(chainConfig, &gen); err != nil {
|
||||
return core.Genesis{}, err
|
||||
}
|
||||
return gen, nil
|
||||
}
|
||||
|
||||
func blocksFromFile(chainfile string, gblock *types.Block) ([]*types.Block, error) {
|
||||
// Load chain.rlp.
|
||||
fh, err := os.Open(chainfile)
|
||||
if err != nil {
|
||||
@@ -161,7 +194,5 @@ func loadChain(chainfile string, genesis string) (*Chain, error) {
|
||||
}
|
||||
blocks = append(blocks, &b)
|
||||
}
|
||||
|
||||
c := &Chain{blocks: blocks, chainConfig: gen.Config}
|
||||
return c, nil
|
||||
return blocks, nil
|
||||
}
|
||||
|
@@ -21,6 +21,7 @@ import (
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/ethereum/go-ethereum/eth/protocols/eth"
|
||||
"github.com/ethereum/go-ethereum/p2p"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
@@ -34,7 +35,9 @@ func TestEthProtocolNegotiation(t *testing.T) {
|
||||
expected uint32
|
||||
}{
|
||||
{
|
||||
conn: &Conn{},
|
||||
conn: &Conn{
|
||||
ourHighestProtoVersion: 65,
|
||||
},
|
||||
caps: []p2p.Cap{
|
||||
{Name: "eth", Version: 63},
|
||||
{Name: "eth", Version: 64},
|
||||
@@ -43,7 +46,42 @@ func TestEthProtocolNegotiation(t *testing.T) {
|
||||
expected: uint32(65),
|
||||
},
|
||||
{
|
||||
conn: &Conn{},
|
||||
conn: &Conn{
|
||||
ourHighestProtoVersion: 65,
|
||||
},
|
||||
caps: []p2p.Cap{
|
||||
{Name: "eth", Version: 63},
|
||||
{Name: "eth", Version: 64},
|
||||
{Name: "eth", Version: 65},
|
||||
},
|
||||
expected: uint32(65),
|
||||
},
|
||||
{
|
||||
conn: &Conn{
|
||||
ourHighestProtoVersion: 65,
|
||||
},
|
||||
caps: []p2p.Cap{
|
||||
{Name: "eth", Version: 63},
|
||||
{Name: "eth", Version: 64},
|
||||
{Name: "eth", Version: 65},
|
||||
},
|
||||
expected: uint32(65),
|
||||
},
|
||||
{
|
||||
conn: &Conn{
|
||||
ourHighestProtoVersion: 64,
|
||||
},
|
||||
caps: []p2p.Cap{
|
||||
{Name: "eth", Version: 63},
|
||||
{Name: "eth", Version: 64},
|
||||
{Name: "eth", Version: 65},
|
||||
},
|
||||
expected: 64,
|
||||
},
|
||||
{
|
||||
conn: &Conn{
|
||||
ourHighestProtoVersion: 65,
|
||||
},
|
||||
caps: []p2p.Cap{
|
||||
{Name: "eth", Version: 0},
|
||||
{Name: "eth", Version: 89},
|
||||
@@ -52,7 +90,20 @@ func TestEthProtocolNegotiation(t *testing.T) {
|
||||
expected: uint32(65),
|
||||
},
|
||||
{
|
||||
conn: &Conn{},
|
||||
conn: &Conn{
|
||||
ourHighestProtoVersion: 64,
|
||||
},
|
||||
caps: []p2p.Cap{
|
||||
{Name: "eth", Version: 63},
|
||||
{Name: "eth", Version: 64},
|
||||
{Name: "wrongProto", Version: 65},
|
||||
},
|
||||
expected: uint32(64),
|
||||
},
|
||||
{
|
||||
conn: &Conn{
|
||||
ourHighestProtoVersion: 65,
|
||||
},
|
||||
caps: []p2p.Cap{
|
||||
{Name: "eth", Version: 63},
|
||||
{Name: "eth", Version: 64},
|
||||
@@ -65,7 +116,7 @@ func TestEthProtocolNegotiation(t *testing.T) {
|
||||
for i, tt := range tests {
|
||||
t.Run(strconv.Itoa(i), func(t *testing.T) {
|
||||
tt.conn.negotiateEthProtocol(tt.caps)
|
||||
assert.Equal(t, tt.expected, uint32(tt.conn.ethProtocolVersion))
|
||||
assert.Equal(t, tt.expected, uint32(tt.conn.negotiatedProtoVersion))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -93,7 +144,7 @@ func TestChain_GetHeaders(t *testing.T) {
|
||||
}{
|
||||
{
|
||||
req: GetBlockHeaders{
|
||||
Origin: hashOrNumber{
|
||||
Origin: eth.HashOrNumber{
|
||||
Number: uint64(2),
|
||||
},
|
||||
Amount: uint64(5),
|
||||
@@ -110,7 +161,7 @@ func TestChain_GetHeaders(t *testing.T) {
|
||||
},
|
||||
{
|
||||
req: GetBlockHeaders{
|
||||
Origin: hashOrNumber{
|
||||
Origin: eth.HashOrNumber{
|
||||
Number: uint64(chain.Len() - 1),
|
||||
},
|
||||
Amount: uint64(3),
|
||||
@@ -125,7 +176,7 @@ func TestChain_GetHeaders(t *testing.T) {
|
||||
},
|
||||
{
|
||||
req: GetBlockHeaders{
|
||||
Origin: hashOrNumber{
|
||||
Origin: eth.HashOrNumber{
|
||||
Hash: chain.Head().Hash(),
|
||||
},
|
||||
Amount: uint64(1),
|
||||
|
749
cmd/devp2p/internal/ethtest/helpers.go
Normal file
749
cmd/devp2p/internal/ethtest/helpers.go
Normal file
@@ -0,0 +1,749 @@
|
||||
// Copyright 2020 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package ethtest
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/eth/protocols/eth"
|
||||
"github.com/ethereum/go-ethereum/internal/utesting"
|
||||
"github.com/ethereum/go-ethereum/p2p"
|
||||
"github.com/ethereum/go-ethereum/p2p/rlpx"
|
||||
)
|
||||
|
||||
var (
|
||||
pretty = spew.ConfigState{
|
||||
Indent: " ",
|
||||
DisableCapacities: true,
|
||||
DisablePointerAddresses: true,
|
||||
SortKeys: true,
|
||||
}
|
||||
timeout = 20 * time.Second
|
||||
)
|
||||
|
||||
// Is_66 checks if the node supports the eth66 protocol version,
|
||||
// and if not, exists the test suite
|
||||
func (s *Suite) Is_66(t *utesting.T) {
|
||||
conn, err := s.dial66()
|
||||
if err != nil {
|
||||
t.Fatalf("dial failed: %v", err)
|
||||
}
|
||||
if err := conn.handshake(); err != nil {
|
||||
t.Fatalf("handshake failed: %v", err)
|
||||
}
|
||||
if conn.negotiatedProtoVersion < 66 {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
|
||||
// dial attempts to dial the given node and perform a handshake,
|
||||
// returning the created Conn if successful.
|
||||
func (s *Suite) dial() (*Conn, error) {
|
||||
// dial
|
||||
fd, err := net.Dial("tcp", fmt.Sprintf("%v:%d", s.Dest.IP(), s.Dest.TCP()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn := Conn{Conn: rlpx.NewConn(fd, s.Dest.Pubkey())}
|
||||
// do encHandshake
|
||||
conn.ourKey, _ = crypto.GenerateKey()
|
||||
_, err = conn.Handshake(conn.ourKey)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
// set default p2p capabilities
|
||||
conn.caps = []p2p.Cap{
|
||||
{Name: "eth", Version: 64},
|
||||
{Name: "eth", Version: 65},
|
||||
}
|
||||
conn.ourHighestProtoVersion = 65
|
||||
return &conn, nil
|
||||
}
|
||||
|
||||
// dial66 attempts to dial the given node and perform a handshake,
|
||||
// returning the created Conn with additional eth66 capabilities if
|
||||
// successful
|
||||
func (s *Suite) dial66() (*Conn, error) {
|
||||
conn, err := s.dial()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("dial failed: %v", err)
|
||||
}
|
||||
conn.caps = append(conn.caps, p2p.Cap{Name: "eth", Version: 66})
|
||||
conn.ourHighestProtoVersion = 66
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// peer performs both the protocol handshake and the status message
|
||||
// exchange with the node in order to peer with it.
|
||||
func (c *Conn) peer(chain *Chain, status *Status) error {
|
||||
if err := c.handshake(); err != nil {
|
||||
return fmt.Errorf("handshake failed: %v", err)
|
||||
}
|
||||
if _, err := c.statusExchange(chain, status); err != nil {
|
||||
return fmt.Errorf("status exchange failed: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// handshake performs a protocol handshake with the node.
|
||||
func (c *Conn) handshake() error {
|
||||
defer c.SetDeadline(time.Time{})
|
||||
c.SetDeadline(time.Now().Add(10 * time.Second))
|
||||
// write hello to client
|
||||
pub0 := crypto.FromECDSAPub(&c.ourKey.PublicKey)[1:]
|
||||
ourHandshake := &Hello{
|
||||
Version: 5,
|
||||
Caps: c.caps,
|
||||
ID: pub0,
|
||||
}
|
||||
if err := c.Write(ourHandshake); err != nil {
|
||||
return fmt.Errorf("write to connection failed: %v", err)
|
||||
}
|
||||
// read hello from client
|
||||
switch msg := c.Read().(type) {
|
||||
case *Hello:
|
||||
// set snappy if version is at least 5
|
||||
if msg.Version >= 5 {
|
||||
c.SetSnappy(true)
|
||||
}
|
||||
c.negotiateEthProtocol(msg.Caps)
|
||||
if c.negotiatedProtoVersion == 0 {
|
||||
return fmt.Errorf("unexpected eth protocol version")
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("bad handshake: %#v", msg)
|
||||
}
|
||||
}
|
||||
|
||||
// negotiateEthProtocol sets the Conn's eth protocol version to highest
|
||||
// advertised capability from peer.
|
||||
func (c *Conn) negotiateEthProtocol(caps []p2p.Cap) {
|
||||
var highestEthVersion uint
|
||||
for _, capability := range caps {
|
||||
if capability.Name != "eth" {
|
||||
continue
|
||||
}
|
||||
if capability.Version > highestEthVersion && capability.Version <= c.ourHighestProtoVersion {
|
||||
highestEthVersion = capability.Version
|
||||
}
|
||||
}
|
||||
c.negotiatedProtoVersion = highestEthVersion
|
||||
}
|
||||
|
||||
// statusExchange performs a `Status` message exchange with the given node.
|
||||
func (c *Conn) statusExchange(chain *Chain, status *Status) (Message, error) {
|
||||
defer c.SetDeadline(time.Time{})
|
||||
c.SetDeadline(time.Now().Add(20 * time.Second))
|
||||
|
||||
// read status message from client
|
||||
var message Message
|
||||
loop:
|
||||
for {
|
||||
switch msg := c.Read().(type) {
|
||||
case *Status:
|
||||
if have, want := msg.Head, chain.blocks[chain.Len()-1].Hash(); have != want {
|
||||
return nil, fmt.Errorf("wrong head block in status, want: %#x (block %d) have %#x",
|
||||
want, chain.blocks[chain.Len()-1].NumberU64(), have)
|
||||
}
|
||||
if have, want := msg.TD.Cmp(chain.TD()), 0; have != want {
|
||||
return nil, fmt.Errorf("wrong TD in status: have %v want %v", have, want)
|
||||
}
|
||||
if have, want := msg.ForkID, chain.ForkID(); !reflect.DeepEqual(have, want) {
|
||||
return nil, fmt.Errorf("wrong fork ID in status: have %v, want %v", have, want)
|
||||
}
|
||||
if have, want := msg.ProtocolVersion, c.ourHighestProtoVersion; have != uint32(want) {
|
||||
return nil, fmt.Errorf("wrong protocol version: have %v, want %v", have, want)
|
||||
}
|
||||
message = msg
|
||||
break loop
|
||||
case *Disconnect:
|
||||
return nil, fmt.Errorf("disconnect received: %v", msg.Reason)
|
||||
case *Ping:
|
||||
c.Write(&Pong{}) // TODO (renaynay): in the future, this should be an error
|
||||
// (PINGs should not be a response upon fresh connection)
|
||||
default:
|
||||
return nil, fmt.Errorf("bad status message: %s", pretty.Sdump(msg))
|
||||
}
|
||||
}
|
||||
// make sure eth protocol version is set for negotiation
|
||||
if c.negotiatedProtoVersion == 0 {
|
||||
return nil, fmt.Errorf("eth protocol version must be set in Conn")
|
||||
}
|
||||
if status == nil {
|
||||
// default status message
|
||||
status = &Status{
|
||||
ProtocolVersion: uint32(c.negotiatedProtoVersion),
|
||||
NetworkID: chain.chainConfig.ChainID.Uint64(),
|
||||
TD: chain.TD(),
|
||||
Head: chain.blocks[chain.Len()-1].Hash(),
|
||||
Genesis: chain.blocks[0].Hash(),
|
||||
ForkID: chain.ForkID(),
|
||||
}
|
||||
}
|
||||
if err := c.Write(status); err != nil {
|
||||
return nil, fmt.Errorf("write to connection failed: %v", err)
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
|
||||
// createSendAndRecvConns creates two connections, one for sending messages to the
|
||||
// node, and one for receiving messages from the node.
|
||||
func (s *Suite) createSendAndRecvConns(isEth66 bool) (*Conn, *Conn, error) {
|
||||
var (
|
||||
sendConn *Conn
|
||||
recvConn *Conn
|
||||
err error
|
||||
)
|
||||
if isEth66 {
|
||||
sendConn, err = s.dial66()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("dial failed: %v", err)
|
||||
}
|
||||
recvConn, err = s.dial66()
|
||||
if err != nil {
|
||||
sendConn.Close()
|
||||
return nil, nil, fmt.Errorf("dial failed: %v", err)
|
||||
}
|
||||
} else {
|
||||
sendConn, err = s.dial()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("dial failed: %v", err)
|
||||
}
|
||||
recvConn, err = s.dial()
|
||||
if err != nil {
|
||||
sendConn.Close()
|
||||
return nil, nil, fmt.Errorf("dial failed: %v", err)
|
||||
}
|
||||
}
|
||||
return sendConn, recvConn, nil
|
||||
}
|
||||
|
||||
// readAndServe serves GetBlockHeaders requests while waiting
|
||||
// on another message from the node.
|
||||
func (c *Conn) readAndServe(chain *Chain, timeout time.Duration) Message {
|
||||
start := time.Now()
|
||||
for time.Since(start) < timeout {
|
||||
c.SetReadDeadline(time.Now().Add(5 * time.Second))
|
||||
switch msg := c.Read().(type) {
|
||||
case *Ping:
|
||||
c.Write(&Pong{})
|
||||
case *GetBlockHeaders:
|
||||
req := *msg
|
||||
headers, err := chain.GetHeaders(req)
|
||||
if err != nil {
|
||||
return errorf("could not get headers for inbound header request: %v", err)
|
||||
}
|
||||
if err := c.Write(headers); err != nil {
|
||||
return errorf("could not write to connection: %v", err)
|
||||
}
|
||||
default:
|
||||
return msg
|
||||
}
|
||||
}
|
||||
return errorf("no message received within %v", timeout)
|
||||
}
|
||||
|
||||
// readAndServe66 serves eth66 GetBlockHeaders requests while waiting
|
||||
// on another message from the node.
|
||||
func (c *Conn) readAndServe66(chain *Chain, timeout time.Duration) (uint64, Message) {
|
||||
start := time.Now()
|
||||
for time.Since(start) < timeout {
|
||||
c.SetReadDeadline(time.Now().Add(10 * time.Second))
|
||||
|
||||
reqID, msg := c.Read66()
|
||||
|
||||
switch msg := msg.(type) {
|
||||
case *Ping:
|
||||
c.Write(&Pong{})
|
||||
case *GetBlockHeaders:
|
||||
headers, err := chain.GetHeaders(*msg)
|
||||
if err != nil {
|
||||
return 0, errorf("could not get headers for inbound header request: %v", err)
|
||||
}
|
||||
resp := ð.BlockHeadersPacket66{
|
||||
RequestId: reqID,
|
||||
BlockHeadersPacket: eth.BlockHeadersPacket(headers),
|
||||
}
|
||||
if err := c.Write66(resp, BlockHeaders{}.Code()); err != nil {
|
||||
return 0, errorf("could not write to connection: %v", err)
|
||||
}
|
||||
default:
|
||||
return reqID, msg
|
||||
}
|
||||
}
|
||||
return 0, errorf("no message received within %v", timeout)
|
||||
}
|
||||
|
||||
// headersRequest executes the given `GetBlockHeaders` request.
|
||||
func (c *Conn) headersRequest(request *GetBlockHeaders, chain *Chain, isEth66 bool, reqID uint64) (BlockHeaders, error) {
|
||||
defer c.SetReadDeadline(time.Time{})
|
||||
c.SetReadDeadline(time.Now().Add(20 * time.Second))
|
||||
// if on eth66 connection, perform eth66 GetBlockHeaders request
|
||||
if isEth66 {
|
||||
return getBlockHeaders66(chain, c, request, reqID)
|
||||
}
|
||||
if err := c.Write(request); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch msg := c.readAndServe(chain, timeout).(type) {
|
||||
case *BlockHeaders:
|
||||
return *msg, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid message: %s", pretty.Sdump(msg))
|
||||
}
|
||||
}
|
||||
|
||||
// getBlockHeaders66 executes the given `GetBlockHeaders` request over the eth66 protocol.
|
||||
func getBlockHeaders66(chain *Chain, conn *Conn, request *GetBlockHeaders, id uint64) (BlockHeaders, error) {
|
||||
// write request
|
||||
packet := eth.GetBlockHeadersPacket(*request)
|
||||
req := ð.GetBlockHeadersPacket66{
|
||||
RequestId: id,
|
||||
GetBlockHeadersPacket: &packet,
|
||||
}
|
||||
if err := conn.Write66(req, GetBlockHeaders{}.Code()); err != nil {
|
||||
return nil, fmt.Errorf("could not write to connection: %v", err)
|
||||
}
|
||||
// wait for response
|
||||
msg := conn.waitForResponse(chain, timeout, req.RequestId)
|
||||
headers, ok := msg.(BlockHeaders)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected message received: %s", pretty.Sdump(msg))
|
||||
}
|
||||
return headers, nil
|
||||
}
|
||||
|
||||
// headersMatch returns whether the received headers match the given request
|
||||
func headersMatch(expected BlockHeaders, headers BlockHeaders) bool {
|
||||
return reflect.DeepEqual(expected, headers)
|
||||
}
|
||||
|
||||
// waitForResponse reads from the connection until a response with the expected
|
||||
// request ID is received.
|
||||
func (c *Conn) waitForResponse(chain *Chain, timeout time.Duration, requestID uint64) Message {
|
||||
for {
|
||||
id, msg := c.readAndServe66(chain, timeout)
|
||||
if id == requestID {
|
||||
return msg
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sendNextBlock broadcasts the next block in the chain and waits
|
||||
// for the node to propagate the block and import it into its chain.
|
||||
func (s *Suite) sendNextBlock(isEth66 bool) error {
|
||||
// set up sending and receiving connections
|
||||
sendConn, recvConn, err := s.createSendAndRecvConns(isEth66)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer sendConn.Close()
|
||||
defer recvConn.Close()
|
||||
if err = sendConn.peer(s.chain, nil); err != nil {
|
||||
return fmt.Errorf("peering failed: %v", err)
|
||||
}
|
||||
if err = recvConn.peer(s.chain, nil); err != nil {
|
||||
return fmt.Errorf("peering failed: %v", err)
|
||||
}
|
||||
// create new block announcement
|
||||
nextBlock := s.fullChain.blocks[s.chain.Len()]
|
||||
blockAnnouncement := &NewBlock{
|
||||
Block: nextBlock,
|
||||
TD: s.fullChain.TotalDifficultyAt(s.chain.Len()),
|
||||
}
|
||||
// send announcement and wait for node to request the header
|
||||
if err = s.testAnnounce(sendConn, recvConn, blockAnnouncement); err != nil {
|
||||
return fmt.Errorf("failed to announce block: %v", err)
|
||||
}
|
||||
// wait for client to update its chain
|
||||
if err = s.waitForBlockImport(recvConn, nextBlock, isEth66); err != nil {
|
||||
return fmt.Errorf("failed to receive confirmation of block import: %v", err)
|
||||
}
|
||||
// update test suite chain
|
||||
s.chain.blocks = append(s.chain.blocks, nextBlock)
|
||||
return nil
|
||||
}
|
||||
|
||||
// testAnnounce writes a block announcement to the node and waits for the node
|
||||
// to propagate it.
|
||||
func (s *Suite) testAnnounce(sendConn, receiveConn *Conn, blockAnnouncement *NewBlock) error {
|
||||
if err := sendConn.Write(blockAnnouncement); err != nil {
|
||||
return fmt.Errorf("could not write to connection: %v", err)
|
||||
}
|
||||
return s.waitAnnounce(receiveConn, blockAnnouncement)
|
||||
}
|
||||
|
||||
// waitAnnounce waits for a NewBlock or NewBlockHashes announcement from the node.
|
||||
func (s *Suite) waitAnnounce(conn *Conn, blockAnnouncement *NewBlock) error {
|
||||
for {
|
||||
switch msg := conn.readAndServe(s.chain, timeout).(type) {
|
||||
case *NewBlock:
|
||||
if !reflect.DeepEqual(blockAnnouncement.Block.Header(), msg.Block.Header()) {
|
||||
return fmt.Errorf("wrong header in block announcement: \nexpected %v "+
|
||||
"\ngot %v", blockAnnouncement.Block.Header(), msg.Block.Header())
|
||||
}
|
||||
if !reflect.DeepEqual(blockAnnouncement.TD, msg.TD) {
|
||||
return fmt.Errorf("wrong TD in announcement: expected %v, got %v", blockAnnouncement.TD, msg.TD)
|
||||
}
|
||||
return nil
|
||||
case *NewBlockHashes:
|
||||
hashes := *msg
|
||||
if blockAnnouncement.Block.Hash() != hashes[0].Hash {
|
||||
return fmt.Errorf("wrong block hash in announcement: expected %v, got %v", blockAnnouncement.Block.Hash(), hashes[0].Hash)
|
||||
}
|
||||
return nil
|
||||
case *NewPooledTransactionHashes:
|
||||
// ignore tx announcements from previous tests
|
||||
continue
|
||||
default:
|
||||
return fmt.Errorf("unexpected: %s", pretty.Sdump(msg))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Suite) waitForBlockImport(conn *Conn, block *types.Block, isEth66 bool) error {
|
||||
defer conn.SetReadDeadline(time.Time{})
|
||||
conn.SetReadDeadline(time.Now().Add(20 * time.Second))
|
||||
// create request
|
||||
req := &GetBlockHeaders{
|
||||
Origin: eth.HashOrNumber{
|
||||
Hash: block.Hash(),
|
||||
},
|
||||
Amount: 1,
|
||||
}
|
||||
// loop until BlockHeaders response contains desired block, confirming the
|
||||
// node imported the block
|
||||
for {
|
||||
var (
|
||||
headers BlockHeaders
|
||||
err error
|
||||
)
|
||||
if isEth66 {
|
||||
requestID := uint64(54)
|
||||
headers, err = conn.headersRequest(req, s.chain, eth66, requestID)
|
||||
} else {
|
||||
headers, err = conn.headersRequest(req, s.chain, eth65, 0)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("GetBlockHeader request failed: %v", err)
|
||||
}
|
||||
// if headers response is empty, node hasn't imported block yet, try again
|
||||
if len(headers) == 0 {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
if !reflect.DeepEqual(block.Header(), headers[0]) {
|
||||
return fmt.Errorf("wrong header returned: wanted %v, got %v", block.Header(), headers[0])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Suite) oldAnnounce(isEth66 bool) error {
|
||||
sendConn, receiveConn, err := s.createSendAndRecvConns(isEth66)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer sendConn.Close()
|
||||
defer receiveConn.Close()
|
||||
if err := sendConn.peer(s.chain, nil); err != nil {
|
||||
return fmt.Errorf("peering failed: %v", err)
|
||||
}
|
||||
if err := receiveConn.peer(s.chain, nil); err != nil {
|
||||
return fmt.Errorf("peering failed: %v", err)
|
||||
}
|
||||
// create old block announcement
|
||||
oldBlockAnnounce := &NewBlock{
|
||||
Block: s.chain.blocks[len(s.chain.blocks)/2],
|
||||
TD: s.chain.blocks[len(s.chain.blocks)/2].Difficulty(),
|
||||
}
|
||||
if err := sendConn.Write(oldBlockAnnounce); err != nil {
|
||||
return fmt.Errorf("could not write to connection: %v", err)
|
||||
}
|
||||
// wait to see if the announcement is propagated
|
||||
switch msg := receiveConn.readAndServe(s.chain, time.Second*8).(type) {
|
||||
case *NewBlock:
|
||||
block := *msg
|
||||
if block.Block.Hash() == oldBlockAnnounce.Block.Hash() {
|
||||
return fmt.Errorf("unexpected: block propagated: %s", pretty.Sdump(msg))
|
||||
}
|
||||
case *NewBlockHashes:
|
||||
hashes := *msg
|
||||
for _, hash := range hashes {
|
||||
if hash.Hash == oldBlockAnnounce.Block.Hash() {
|
||||
return fmt.Errorf("unexpected: block announced: %s", pretty.Sdump(msg))
|
||||
}
|
||||
}
|
||||
case *Error:
|
||||
errMsg := *msg
|
||||
// check to make sure error is timeout (propagation didn't come through == test successful)
|
||||
if !strings.Contains(errMsg.String(), "timeout") {
|
||||
return fmt.Errorf("unexpected error: %v", pretty.Sdump(msg))
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unexpected: %s", pretty.Sdump(msg))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Suite) maliciousHandshakes(t *utesting.T, isEth66 bool) error {
|
||||
var (
|
||||
conn *Conn
|
||||
err error
|
||||
)
|
||||
if isEth66 {
|
||||
conn, err = s.dial66()
|
||||
if err != nil {
|
||||
return fmt.Errorf("dial failed: %v", err)
|
||||
}
|
||||
} else {
|
||||
conn, err = s.dial()
|
||||
if err != nil {
|
||||
return fmt.Errorf("dial failed: %v", err)
|
||||
}
|
||||
}
|
||||
defer conn.Close()
|
||||
// write hello to client
|
||||
pub0 := crypto.FromECDSAPub(&conn.ourKey.PublicKey)[1:]
|
||||
handshakes := []*Hello{
|
||||
{
|
||||
Version: 5,
|
||||
Caps: []p2p.Cap{
|
||||
{Name: largeString(2), Version: 64},
|
||||
},
|
||||
ID: pub0,
|
||||
},
|
||||
{
|
||||
Version: 5,
|
||||
Caps: []p2p.Cap{
|
||||
{Name: "eth", Version: 64},
|
||||
{Name: "eth", Version: 65},
|
||||
},
|
||||
ID: append(pub0, byte(0)),
|
||||
},
|
||||
{
|
||||
Version: 5,
|
||||
Caps: []p2p.Cap{
|
||||
{Name: "eth", Version: 64},
|
||||
{Name: "eth", Version: 65},
|
||||
},
|
||||
ID: append(pub0, pub0...),
|
||||
},
|
||||
{
|
||||
Version: 5,
|
||||
Caps: []p2p.Cap{
|
||||
{Name: "eth", Version: 64},
|
||||
{Name: "eth", Version: 65},
|
||||
},
|
||||
ID: largeBuffer(2),
|
||||
},
|
||||
{
|
||||
Version: 5,
|
||||
Caps: []p2p.Cap{
|
||||
{Name: largeString(2), Version: 64},
|
||||
},
|
||||
ID: largeBuffer(2),
|
||||
},
|
||||
}
|
||||
for i, handshake := range handshakes {
|
||||
t.Logf("Testing malicious handshake %v\n", i)
|
||||
if err := conn.Write(handshake); err != nil {
|
||||
return fmt.Errorf("could not write to connection: %v", err)
|
||||
}
|
||||
// check that the peer disconnected
|
||||
for i := 0; i < 2; i++ {
|
||||
switch msg := conn.readAndServe(s.chain, 20*time.Second).(type) {
|
||||
case *Disconnect:
|
||||
case *Error:
|
||||
case *Hello:
|
||||
// Discard one hello as Hello's are sent concurrently
|
||||
continue
|
||||
default:
|
||||
return fmt.Errorf("unexpected: %s", pretty.Sdump(msg))
|
||||
}
|
||||
}
|
||||
// dial for the next round
|
||||
if isEth66 {
|
||||
conn, err = s.dial66()
|
||||
if err != nil {
|
||||
return fmt.Errorf("dial failed: %v", err)
|
||||
}
|
||||
} else {
|
||||
conn, err = s.dial()
|
||||
if err != nil {
|
||||
return fmt.Errorf("dial failed: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Suite) maliciousStatus(conn *Conn) error {
|
||||
if err := conn.handshake(); err != nil {
|
||||
return fmt.Errorf("handshake failed: %v", err)
|
||||
}
|
||||
status := &Status{
|
||||
ProtocolVersion: uint32(conn.negotiatedProtoVersion),
|
||||
NetworkID: s.chain.chainConfig.ChainID.Uint64(),
|
||||
TD: largeNumber(2),
|
||||
Head: s.chain.blocks[s.chain.Len()-1].Hash(),
|
||||
Genesis: s.chain.blocks[0].Hash(),
|
||||
ForkID: s.chain.ForkID(),
|
||||
}
|
||||
// get status
|
||||
msg, err := conn.statusExchange(s.chain, status)
|
||||
if err != nil {
|
||||
return fmt.Errorf("status exchange failed: %v", err)
|
||||
}
|
||||
switch msg := msg.(type) {
|
||||
case *Status:
|
||||
default:
|
||||
return fmt.Errorf("expected status, got: %#v ", msg)
|
||||
}
|
||||
// wait for disconnect
|
||||
switch msg := conn.readAndServe(s.chain, timeout).(type) {
|
||||
case *Disconnect:
|
||||
return nil
|
||||
case *Error:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("expected disconnect, got: %s", pretty.Sdump(msg))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Suite) hashAnnounce(isEth66 bool) error {
|
||||
// create connections
|
||||
sendConn, recvConn, err := s.createSendAndRecvConns(isEth66)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create connections: %v", err)
|
||||
}
|
||||
defer sendConn.Close()
|
||||
defer recvConn.Close()
|
||||
if err := sendConn.peer(s.chain, nil); err != nil {
|
||||
return fmt.Errorf("peering failed: %v", err)
|
||||
}
|
||||
if err := recvConn.peer(s.chain, nil); err != nil {
|
||||
return fmt.Errorf("peering failed: %v", err)
|
||||
}
|
||||
// create NewBlockHashes announcement
|
||||
type anno struct {
|
||||
Hash common.Hash // Hash of one particular block being announced
|
||||
Number uint64 // Number of one particular block being announced
|
||||
}
|
||||
nextBlock := s.fullChain.blocks[s.chain.Len()]
|
||||
announcement := anno{Hash: nextBlock.Hash(), Number: nextBlock.Number().Uint64()}
|
||||
newBlockHash := &NewBlockHashes{announcement}
|
||||
if err := sendConn.Write(newBlockHash); err != nil {
|
||||
return fmt.Errorf("failed to write to connection: %v", err)
|
||||
}
|
||||
// Announcement sent, now wait for a header request
|
||||
var (
|
||||
id uint64
|
||||
msg Message
|
||||
blockHeaderReq GetBlockHeaders
|
||||
)
|
||||
if isEth66 {
|
||||
id, msg = sendConn.Read66()
|
||||
switch msg := msg.(type) {
|
||||
case GetBlockHeaders:
|
||||
blockHeaderReq = msg
|
||||
default:
|
||||
return fmt.Errorf("unexpected %s", pretty.Sdump(msg))
|
||||
}
|
||||
if blockHeaderReq.Amount != 1 {
|
||||
return fmt.Errorf("unexpected number of block headers requested: %v", blockHeaderReq.Amount)
|
||||
}
|
||||
if blockHeaderReq.Origin.Hash != announcement.Hash {
|
||||
return fmt.Errorf("unexpected block header requested. Announced:\n %v\n Remote request:\n%v",
|
||||
pretty.Sdump(announcement),
|
||||
pretty.Sdump(blockHeaderReq))
|
||||
}
|
||||
if err := sendConn.Write66(ð.BlockHeadersPacket66{
|
||||
RequestId: id,
|
||||
BlockHeadersPacket: eth.BlockHeadersPacket{
|
||||
nextBlock.Header(),
|
||||
},
|
||||
}, BlockHeaders{}.Code()); err != nil {
|
||||
return fmt.Errorf("failed to write to connection: %v", err)
|
||||
}
|
||||
} else {
|
||||
msg = sendConn.Read()
|
||||
switch msg := msg.(type) {
|
||||
case *GetBlockHeaders:
|
||||
blockHeaderReq = *msg
|
||||
default:
|
||||
return fmt.Errorf("unexpected %s", pretty.Sdump(msg))
|
||||
}
|
||||
if blockHeaderReq.Amount != 1 {
|
||||
return fmt.Errorf("unexpected number of block headers requested: %v", blockHeaderReq.Amount)
|
||||
}
|
||||
if blockHeaderReq.Origin.Hash != announcement.Hash {
|
||||
return fmt.Errorf("unexpected block header requested. Announced:\n %v\n Remote request:\n%v",
|
||||
pretty.Sdump(announcement),
|
||||
pretty.Sdump(blockHeaderReq))
|
||||
}
|
||||
if err := sendConn.Write(&BlockHeaders{nextBlock.Header()}); err != nil {
|
||||
return fmt.Errorf("failed to write to connection: %v", err)
|
||||
}
|
||||
}
|
||||
// wait for block announcement
|
||||
msg = recvConn.readAndServe(s.chain, timeout)
|
||||
switch msg := msg.(type) {
|
||||
case *NewBlockHashes:
|
||||
hashes := *msg
|
||||
if len(hashes) != 1 {
|
||||
return fmt.Errorf("unexpected new block hash announcement: wanted 1 announcement, got %d", len(hashes))
|
||||
}
|
||||
if nextBlock.Hash() != hashes[0].Hash {
|
||||
return fmt.Errorf("unexpected block hash announcement, wanted %v, got %v", nextBlock.Hash(),
|
||||
hashes[0].Hash)
|
||||
}
|
||||
case *NewBlock:
|
||||
// node should only propagate NewBlock without having requested the body if the body is empty
|
||||
nextBlockBody := nextBlock.Body()
|
||||
if len(nextBlockBody.Transactions) != 0 || len(nextBlockBody.Uncles) != 0 {
|
||||
return fmt.Errorf("unexpected non-empty new block propagated: %s", pretty.Sdump(msg))
|
||||
}
|
||||
if msg.Block.Hash() != nextBlock.Hash() {
|
||||
return fmt.Errorf("mismatched hash of propagated new block: wanted %v, got %v",
|
||||
nextBlock.Hash(), msg.Block.Hash())
|
||||
}
|
||||
// check to make sure header matches header that was sent to the node
|
||||
if !reflect.DeepEqual(nextBlock.Header(), msg.Block.Header()) {
|
||||
return fmt.Errorf("incorrect header received: wanted %v, got %v", nextBlock.Header(), msg.Block.Header())
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unexpected: %s", pretty.Sdump(msg))
|
||||
}
|
||||
// confirm node imported block
|
||||
if err := s.waitForBlockImport(recvConn, nextBlock, isEth66); err != nil {
|
||||
return fmt.Errorf("error waiting for node to import new block: %v", err)
|
||||
}
|
||||
// update the chain
|
||||
s.chain.blocks = append(s.chain.blocks, nextBlock)
|
||||
return nil
|
||||
}
|
@@ -70,7 +70,7 @@ func largeHeader() *types.Header {
|
||||
GasUsed: 0,
|
||||
Coinbase: common.Address{},
|
||||
GasLimit: 0,
|
||||
UncleHash: randHash(),
|
||||
UncleHash: types.EmptyUncleHash,
|
||||
Time: 1337,
|
||||
ParentHash: randHash(),
|
||||
Root: randHash(),
|
||||
|
File diff suppressed because it is too large
Load Diff
107
cmd/devp2p/internal/ethtest/suite_test.go
Normal file
107
cmd/devp2p/internal/ethtest/suite_test.go
Normal file
@@ -0,0 +1,107 @@
|
||||
// Copyright 2020 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package ethtest
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/eth"
|
||||
"github.com/ethereum/go-ethereum/eth/ethconfig"
|
||||
"github.com/ethereum/go-ethereum/internal/utesting"
|
||||
"github.com/ethereum/go-ethereum/node"
|
||||
"github.com/ethereum/go-ethereum/p2p"
|
||||
)
|
||||
|
||||
var (
|
||||
genesisFile = "./testdata/genesis.json"
|
||||
halfchainFile = "./testdata/halfchain.rlp"
|
||||
fullchainFile = "./testdata/chain.rlp"
|
||||
)
|
||||
|
||||
func TestEthSuite(t *testing.T) {
|
||||
geth, err := runGeth()
|
||||
if err != nil {
|
||||
t.Fatalf("could not run geth: %v", err)
|
||||
}
|
||||
defer geth.Close()
|
||||
|
||||
suite, err := NewSuite(geth.Server().Self(), fullchainFile, genesisFile)
|
||||
if err != nil {
|
||||
t.Fatalf("could not create new test suite: %v", err)
|
||||
}
|
||||
for _, test := range suite.AllEthTests() {
|
||||
t.Run(test.Name, func(t *testing.T) {
|
||||
result := utesting.RunTAP([]utesting.Test{{Name: test.Name, Fn: test.Fn}}, os.Stdout)
|
||||
if result[0].Failed {
|
||||
t.Fatal()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// runGeth creates and starts a geth node
|
||||
func runGeth() (*node.Node, error) {
|
||||
stack, err := node.New(&node.Config{
|
||||
P2P: p2p.Config{
|
||||
ListenAddr: "127.0.0.1:0",
|
||||
NoDiscovery: true,
|
||||
MaxPeers: 10, // in case a test requires multiple connections, can be changed in the future
|
||||
NoDial: true,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = setupGeth(stack)
|
||||
if err != nil {
|
||||
stack.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err = stack.Start(); err != nil {
|
||||
stack.Close()
|
||||
return nil, err
|
||||
}
|
||||
return stack, nil
|
||||
}
|
||||
|
||||
func setupGeth(stack *node.Node) error {
|
||||
chain, err := loadChain(halfchainFile, genesisFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
backend, err := eth.New(stack, ðconfig.Config{
|
||||
Genesis: &chain.genesis,
|
||||
NetworkId: chain.genesis.Config.ChainID.Uint64(), // 19763
|
||||
DatabaseCache: 10,
|
||||
TrieCleanCache: 10,
|
||||
TrieCleanCacheJournal: "",
|
||||
TrieCleanCacheRejournal: 60 * time.Minute,
|
||||
TrieDirtyCache: 16,
|
||||
TrieTimeout: 60 * time.Minute,
|
||||
SnapshotCache: 10,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = backend.BlockChain().InsertChain(chain.blocks[1:])
|
||||
return err
|
||||
}
|
@@ -17,164 +17,403 @@
|
||||
package ethtest
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/internal/utesting"
|
||||
"github.com/ethereum/go-ethereum/params"
|
||||
)
|
||||
|
||||
//var faucetAddr = common.HexToAddress("0x71562b71999873DB5b286dF957af199Ec94617F7")
|
||||
var faucetKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
|
||||
|
||||
func sendSuccessfulTx(t *utesting.T, s *Suite, tx *types.Transaction) {
|
||||
sendConn := s.setupConnection(t)
|
||||
t.Logf("sending tx: %v %v %v\n", tx.Hash().String(), tx.GasPrice(), tx.Gas())
|
||||
// Send the transaction
|
||||
if err := sendConn.Write(Transactions([]*types.Transaction{tx})); err != nil {
|
||||
t.Fatal(err)
|
||||
func (s *Suite) sendSuccessfulTxs(t *utesting.T, isEth66 bool) error {
|
||||
tests := []*types.Transaction{
|
||||
getNextTxFromChain(s),
|
||||
unknownTx(s),
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
recvConn := s.setupConnection(t)
|
||||
for i, tx := range tests {
|
||||
if tx == nil {
|
||||
return fmt.Errorf("could not find tx to send")
|
||||
}
|
||||
t.Logf("Testing tx propagation %d: sending tx %v %v %v\n", i, tx.Hash().String(), tx.GasPrice(), tx.Gas())
|
||||
// get previous tx if exists for reference in case of old tx propagation
|
||||
var prevTx *types.Transaction
|
||||
if i != 0 {
|
||||
prevTx = tests[i-1]
|
||||
}
|
||||
// write tx to connection
|
||||
if err := sendSuccessfulTx(s, tx, prevTx, isEth66); err != nil {
|
||||
return fmt.Errorf("send successful tx test failed: %v", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sendSuccessfulTx(s *Suite, tx *types.Transaction, prevTx *types.Transaction, isEth66 bool) error {
|
||||
sendConn, recvConn, err := s.createSendAndRecvConns(isEth66)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer sendConn.Close()
|
||||
defer recvConn.Close()
|
||||
if err = sendConn.peer(s.chain, nil); err != nil {
|
||||
return fmt.Errorf("peering failed: %v", err)
|
||||
}
|
||||
// Send the transaction
|
||||
if err = sendConn.Write(&Transactions{tx}); err != nil {
|
||||
return fmt.Errorf("failed to write to connection: %v", err)
|
||||
}
|
||||
// peer receiving connection to node
|
||||
if err = recvConn.peer(s.chain, nil); err != nil {
|
||||
return fmt.Errorf("peering failed: %v", err)
|
||||
}
|
||||
// update last nonce seen
|
||||
nonce = tx.Nonce()
|
||||
// Wait for the transaction announcement
|
||||
switch msg := recvConn.ReadAndServe(s.chain, timeout).(type) {
|
||||
case *Transactions:
|
||||
recTxs := *msg
|
||||
if len(recTxs) < 1 {
|
||||
t.Fatalf("received transactions do not match send: %v", recTxs)
|
||||
for {
|
||||
switch msg := recvConn.readAndServe(s.chain, timeout).(type) {
|
||||
case *Transactions:
|
||||
recTxs := *msg
|
||||
// if you receive an old tx propagation, read from connection again
|
||||
if len(recTxs) == 1 && prevTx != nil {
|
||||
if recTxs[0] == prevTx {
|
||||
continue
|
||||
}
|
||||
}
|
||||
for _, gotTx := range recTxs {
|
||||
if gotTx.Hash() == tx.Hash() {
|
||||
// Ok
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("missing transaction: got %v missing %v", recTxs, tx.Hash())
|
||||
case *NewPooledTransactionHashes:
|
||||
txHashes := *msg
|
||||
// if you receive an old tx propagation, read from connection again
|
||||
if len(txHashes) == 1 && prevTx != nil {
|
||||
if txHashes[0] == prevTx.Hash() {
|
||||
continue
|
||||
}
|
||||
}
|
||||
for _, gotHash := range txHashes {
|
||||
if gotHash == tx.Hash() {
|
||||
// Ok
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("missing transaction announcement: got %v missing %v", txHashes, tx.Hash())
|
||||
default:
|
||||
return fmt.Errorf("unexpected message in sendSuccessfulTx: %s", pretty.Sdump(msg))
|
||||
}
|
||||
if tx.Hash() != recTxs[len(recTxs)-1].Hash() {
|
||||
t.Fatalf("received transactions do not match send: got %v want %v", recTxs, tx)
|
||||
}
|
||||
case *NewPooledTransactionHashes:
|
||||
txHashes := *msg
|
||||
if len(txHashes) < 1 {
|
||||
t.Fatalf("received transactions do not match send: %v", txHashes)
|
||||
}
|
||||
if tx.Hash() != txHashes[len(txHashes)-1] {
|
||||
t.Fatalf("wrong announcement received, wanted %v got %v", tx, txHashes)
|
||||
}
|
||||
default:
|
||||
t.Fatalf("unexpected message in sendSuccessfulTx: %s", pretty.Sdump(msg))
|
||||
}
|
||||
}
|
||||
|
||||
func sendFailingTx(t *utesting.T, s *Suite, tx *types.Transaction) {
|
||||
sendConn, recvConn := s.setupConnection(t), s.setupConnection(t)
|
||||
// Wait for a transaction announcement
|
||||
switch msg := recvConn.ReadAndServe(s.chain, timeout).(type) {
|
||||
case *NewPooledTransactionHashes:
|
||||
break
|
||||
default:
|
||||
t.Logf("unexpected message, logging: %v", pretty.Sdump(msg))
|
||||
func (s *Suite) sendMaliciousTxs(t *utesting.T, isEth66 bool) error {
|
||||
badTxs := []*types.Transaction{
|
||||
getOldTxFromChain(s),
|
||||
invalidNonceTx(s),
|
||||
hugeAmount(s),
|
||||
hugeGasPrice(s),
|
||||
hugeData(s),
|
||||
}
|
||||
// Send the transaction
|
||||
if err := sendConn.Write(Transactions([]*types.Transaction{tx})); err != nil {
|
||||
t.Fatal(err)
|
||||
// setup receiving connection before sending malicious txs
|
||||
var (
|
||||
recvConn *Conn
|
||||
err error
|
||||
)
|
||||
if isEth66 {
|
||||
recvConn, err = s.dial66()
|
||||
} else {
|
||||
recvConn, err = s.dial()
|
||||
}
|
||||
// Wait for another transaction announcement
|
||||
switch msg := recvConn.ReadAndServe(s.chain, timeout).(type) {
|
||||
if err != nil {
|
||||
return fmt.Errorf("dial failed: %v", err)
|
||||
}
|
||||
defer recvConn.Close()
|
||||
if err = recvConn.peer(s.chain, nil); err != nil {
|
||||
return fmt.Errorf("peering failed: %v", err)
|
||||
}
|
||||
for i, tx := range badTxs {
|
||||
t.Logf("Testing malicious tx propagation: %v\n", i)
|
||||
if err = sendMaliciousTx(s, tx, isEth66); err != nil {
|
||||
return fmt.Errorf("malicious tx test failed:\ntx: %v\nerror: %v", tx, err)
|
||||
}
|
||||
}
|
||||
// check to make sure bad txs aren't propagated
|
||||
return checkMaliciousTxPropagation(s, badTxs, recvConn)
|
||||
}
|
||||
|
||||
func sendMaliciousTx(s *Suite, tx *types.Transaction, isEth66 bool) error {
|
||||
// setup connection
|
||||
var (
|
||||
conn *Conn
|
||||
err error
|
||||
)
|
||||
if isEth66 {
|
||||
conn, err = s.dial66()
|
||||
} else {
|
||||
conn, err = s.dial()
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("dial failed: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
if err = conn.peer(s.chain, nil); err != nil {
|
||||
return fmt.Errorf("peering failed: %v", err)
|
||||
}
|
||||
// write malicious tx
|
||||
if err = conn.Write(&Transactions{tx}); err != nil {
|
||||
return fmt.Errorf("failed to write to connection: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var nonce = uint64(99)
|
||||
|
||||
// sendMultipleSuccessfulTxs sends the given transactions to the node and
|
||||
// expects the node to accept and propagate them.
|
||||
func sendMultipleSuccessfulTxs(t *utesting.T, s *Suite, txs []*types.Transaction) error {
|
||||
txMsg := Transactions(txs)
|
||||
t.Logf("sending %d txs\n", len(txs))
|
||||
|
||||
sendConn, recvConn, err := s.createSendAndRecvConns(true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer sendConn.Close()
|
||||
defer recvConn.Close()
|
||||
if err = sendConn.peer(s.chain, nil); err != nil {
|
||||
return fmt.Errorf("peering failed: %v", err)
|
||||
}
|
||||
if err = recvConn.peer(s.chain, nil); err != nil {
|
||||
return fmt.Errorf("peering failed: %v", err)
|
||||
}
|
||||
// Send the transactions
|
||||
if err = sendConn.Write(&txMsg); err != nil {
|
||||
return fmt.Errorf("failed to write message to connection: %v", err)
|
||||
}
|
||||
// update nonce
|
||||
nonce = txs[len(txs)-1].Nonce()
|
||||
// Wait for the transaction announcement(s) and make sure all sent txs are being propagated
|
||||
recvHashes := make([]common.Hash, 0)
|
||||
// all txs should be announced within 3 announcements
|
||||
for i := 0; i < 3; i++ {
|
||||
switch msg := recvConn.readAndServe(s.chain, timeout).(type) {
|
||||
case *Transactions:
|
||||
for _, tx := range *msg {
|
||||
recvHashes = append(recvHashes, tx.Hash())
|
||||
}
|
||||
case *NewPooledTransactionHashes:
|
||||
recvHashes = append(recvHashes, *msg...)
|
||||
default:
|
||||
if !strings.Contains(pretty.Sdump(msg), "i/o timeout") {
|
||||
return fmt.Errorf("unexpected message while waiting to receive txs: %s", pretty.Sdump(msg))
|
||||
}
|
||||
}
|
||||
// break once all 2000 txs have been received
|
||||
if len(recvHashes) == 2000 {
|
||||
break
|
||||
}
|
||||
if len(recvHashes) > 0 {
|
||||
_, missingTxs := compareReceivedTxs(recvHashes, txs)
|
||||
if len(missingTxs) > 0 {
|
||||
continue
|
||||
} else {
|
||||
t.Logf("successfully received all %d txs", len(txs))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
_, missingTxs := compareReceivedTxs(recvHashes, txs)
|
||||
if len(missingTxs) > 0 {
|
||||
for _, missing := range missingTxs {
|
||||
t.Logf("missing tx: %v", missing.Hash())
|
||||
}
|
||||
return fmt.Errorf("missing %d txs", len(missingTxs))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkMaliciousTxPropagation checks whether the given malicious transactions were
|
||||
// propagated by the node.
|
||||
func checkMaliciousTxPropagation(s *Suite, txs []*types.Transaction, conn *Conn) error {
|
||||
switch msg := conn.readAndServe(s.chain, time.Second*8).(type) {
|
||||
case *Transactions:
|
||||
t.Fatalf("Received unexpected transaction announcement: %v", msg)
|
||||
// check to see if any of the failing txs were in the announcement
|
||||
recvTxs := make([]common.Hash, len(*msg))
|
||||
for i, recvTx := range *msg {
|
||||
recvTxs[i] = recvTx.Hash()
|
||||
}
|
||||
badTxs, _ := compareReceivedTxs(recvTxs, txs)
|
||||
if len(badTxs) > 0 {
|
||||
return fmt.Errorf("received %d bad txs: \n%v", len(badTxs), badTxs)
|
||||
}
|
||||
case *NewPooledTransactionHashes:
|
||||
t.Fatalf("Received unexpected pooledTx announcement: %v", msg)
|
||||
badTxs, _ := compareReceivedTxs(*msg, txs)
|
||||
if len(badTxs) > 0 {
|
||||
return fmt.Errorf("received %d bad txs: \n%v", len(badTxs), badTxs)
|
||||
}
|
||||
case *Error:
|
||||
// Transaction should not be announced -> wait for timeout
|
||||
return
|
||||
return nil
|
||||
default:
|
||||
t.Fatalf("unexpected message in sendFailingTx: %s", pretty.Sdump(msg))
|
||||
return fmt.Errorf("unexpected message in sendFailingTx: %s", pretty.Sdump(msg))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func unknownTx(t *utesting.T, s *Suite) *types.Transaction {
|
||||
tx := getNextTxFromChain(t, s)
|
||||
// compareReceivedTxs compares the received set of txs against the given set of txs,
|
||||
// returning both the set received txs that were present within the given txs, and
|
||||
// the set of txs that were missing from the set of received txs
|
||||
func compareReceivedTxs(recvTxs []common.Hash, txs []*types.Transaction) (present []*types.Transaction, missing []*types.Transaction) {
|
||||
// create a map of the hashes received from node
|
||||
recvHashes := make(map[common.Hash]common.Hash)
|
||||
for _, hash := range recvTxs {
|
||||
recvHashes[hash] = hash
|
||||
}
|
||||
|
||||
// collect present txs and missing txs separately
|
||||
present = make([]*types.Transaction, 0)
|
||||
missing = make([]*types.Transaction, 0)
|
||||
for _, tx := range txs {
|
||||
if _, exists := recvHashes[tx.Hash()]; exists {
|
||||
present = append(present, tx)
|
||||
} else {
|
||||
missing = append(missing, tx)
|
||||
}
|
||||
}
|
||||
return present, missing
|
||||
}
|
||||
|
||||
func unknownTx(s *Suite) *types.Transaction {
|
||||
tx := getNextTxFromChain(s)
|
||||
if tx == nil {
|
||||
return nil
|
||||
}
|
||||
var to common.Address
|
||||
if tx.To() != nil {
|
||||
to = *tx.To()
|
||||
}
|
||||
txNew := types.NewTransaction(tx.Nonce()+1, to, tx.Value(), tx.Gas(), tx.GasPrice(), tx.Data())
|
||||
return signWithFaucet(t, txNew)
|
||||
return signWithFaucet(s.chain.chainConfig, txNew)
|
||||
}
|
||||
|
||||
func getNextTxFromChain(t *utesting.T, s *Suite) *types.Transaction {
|
||||
func getNextTxFromChain(s *Suite) *types.Transaction {
|
||||
// Get a new transaction
|
||||
var tx *types.Transaction
|
||||
for _, blocks := range s.fullChain.blocks[s.chain.Len():] {
|
||||
txs := blocks.Transactions()
|
||||
if txs.Len() != 0 {
|
||||
tx = txs[0]
|
||||
break
|
||||
return txs[0]
|
||||
}
|
||||
}
|
||||
if tx == nil {
|
||||
t.Fatal("could not find transaction")
|
||||
}
|
||||
return tx
|
||||
return nil
|
||||
}
|
||||
|
||||
func getOldTxFromChain(t *utesting.T, s *Suite) *types.Transaction {
|
||||
var tx *types.Transaction
|
||||
func generateTxs(s *Suite, numTxs int) (map[common.Hash]common.Hash, []*types.Transaction, error) {
|
||||
txHashMap := make(map[common.Hash]common.Hash, numTxs)
|
||||
txs := make([]*types.Transaction, numTxs)
|
||||
|
||||
nextTx := getNextTxFromChain(s)
|
||||
if nextTx == nil {
|
||||
return nil, nil, fmt.Errorf("failed to get the next transaction")
|
||||
}
|
||||
gas := nextTx.Gas()
|
||||
|
||||
nonce = nonce + 1
|
||||
// generate txs
|
||||
for i := 0; i < numTxs; i++ {
|
||||
tx := generateTx(s.chain.chainConfig, nonce, gas)
|
||||
if tx == nil {
|
||||
return nil, nil, fmt.Errorf("failed to get the next transaction")
|
||||
}
|
||||
txHashMap[tx.Hash()] = tx.Hash()
|
||||
txs[i] = tx
|
||||
nonce = nonce + 1
|
||||
}
|
||||
return txHashMap, txs, nil
|
||||
}
|
||||
|
||||
func generateTx(chainConfig *params.ChainConfig, nonce uint64, gas uint64) *types.Transaction {
|
||||
var to common.Address
|
||||
tx := types.NewTransaction(nonce, to, big.NewInt(1), gas, big.NewInt(1), []byte{})
|
||||
return signWithFaucet(chainConfig, tx)
|
||||
}
|
||||
|
||||
func getOldTxFromChain(s *Suite) *types.Transaction {
|
||||
for _, blocks := range s.fullChain.blocks[:s.chain.Len()-1] {
|
||||
txs := blocks.Transactions()
|
||||
if txs.Len() != 0 {
|
||||
tx = txs[0]
|
||||
break
|
||||
return txs[0]
|
||||
}
|
||||
}
|
||||
if tx == nil {
|
||||
t.Fatal("could not find transaction")
|
||||
}
|
||||
return tx
|
||||
return nil
|
||||
}
|
||||
|
||||
func invalidNonceTx(t *utesting.T, s *Suite) *types.Transaction {
|
||||
tx := getNextTxFromChain(t, s)
|
||||
func invalidNonceTx(s *Suite) *types.Transaction {
|
||||
tx := getNextTxFromChain(s)
|
||||
if tx == nil {
|
||||
return nil
|
||||
}
|
||||
var to common.Address
|
||||
if tx.To() != nil {
|
||||
to = *tx.To()
|
||||
}
|
||||
txNew := types.NewTransaction(tx.Nonce()-2, to, tx.Value(), tx.Gas(), tx.GasPrice(), tx.Data())
|
||||
return signWithFaucet(t, txNew)
|
||||
return signWithFaucet(s.chain.chainConfig, txNew)
|
||||
}
|
||||
|
||||
func hugeAmount(t *utesting.T, s *Suite) *types.Transaction {
|
||||
tx := getNextTxFromChain(t, s)
|
||||
func hugeAmount(s *Suite) *types.Transaction {
|
||||
tx := getNextTxFromChain(s)
|
||||
if tx == nil {
|
||||
return nil
|
||||
}
|
||||
amount := largeNumber(2)
|
||||
var to common.Address
|
||||
if tx.To() != nil {
|
||||
to = *tx.To()
|
||||
}
|
||||
txNew := types.NewTransaction(tx.Nonce(), to, amount, tx.Gas(), tx.GasPrice(), tx.Data())
|
||||
return signWithFaucet(t, txNew)
|
||||
return signWithFaucet(s.chain.chainConfig, txNew)
|
||||
}
|
||||
|
||||
func hugeGasPrice(t *utesting.T, s *Suite) *types.Transaction {
|
||||
tx := getNextTxFromChain(t, s)
|
||||
func hugeGasPrice(s *Suite) *types.Transaction {
|
||||
tx := getNextTxFromChain(s)
|
||||
if tx == nil {
|
||||
return nil
|
||||
}
|
||||
gasPrice := largeNumber(2)
|
||||
var to common.Address
|
||||
if tx.To() != nil {
|
||||
to = *tx.To()
|
||||
}
|
||||
txNew := types.NewTransaction(tx.Nonce(), to, tx.Value(), tx.Gas(), gasPrice, tx.Data())
|
||||
return signWithFaucet(t, txNew)
|
||||
return signWithFaucet(s.chain.chainConfig, txNew)
|
||||
}
|
||||
|
||||
func hugeData(t *utesting.T, s *Suite) *types.Transaction {
|
||||
tx := getNextTxFromChain(t, s)
|
||||
func hugeData(s *Suite) *types.Transaction {
|
||||
tx := getNextTxFromChain(s)
|
||||
if tx == nil {
|
||||
return nil
|
||||
}
|
||||
var to common.Address
|
||||
if tx.To() != nil {
|
||||
to = *tx.To()
|
||||
}
|
||||
txNew := types.NewTransaction(tx.Nonce(), to, tx.Value(), tx.Gas(), tx.GasPrice(), largeBuffer(2))
|
||||
return signWithFaucet(t, txNew)
|
||||
return signWithFaucet(s.chain.chainConfig, txNew)
|
||||
}
|
||||
|
||||
func signWithFaucet(t *utesting.T, tx *types.Transaction) *types.Transaction {
|
||||
signer := types.HomesteadSigner{}
|
||||
func signWithFaucet(chainConfig *params.ChainConfig, tx *types.Transaction) *types.Transaction {
|
||||
signer := types.LatestSigner(chainConfig)
|
||||
signedTx, err := types.SignTx(tx, signer, faucetKey)
|
||||
if err != nil {
|
||||
t.Fatalf("could not sign tx: %v\n", err)
|
||||
return nil
|
||||
}
|
||||
return signedTx
|
||||
}
|
||||
|
@@ -19,16 +19,8 @@ package ethtest
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"reflect"
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/forkid"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/internal/utesting"
|
||||
"github.com/ethereum/go-ethereum/eth/protocols/eth"
|
||||
"github.com/ethereum/go-ethereum/p2p"
|
||||
"github.com/ethereum/go-ethereum/p2p/rlpx"
|
||||
"github.com/ethereum/go-ethereum/rlp"
|
||||
@@ -81,109 +73,66 @@ type Pong struct{}
|
||||
func (p Pong) Code() int { return 0x03 }
|
||||
|
||||
// Status is the network packet for the status message for eth/64 and later.
|
||||
type Status struct {
|
||||
ProtocolVersion uint32
|
||||
NetworkID uint64
|
||||
TD *big.Int
|
||||
Head common.Hash
|
||||
Genesis common.Hash
|
||||
ForkID forkid.ID
|
||||
}
|
||||
type Status eth.StatusPacket
|
||||
|
||||
func (s Status) Code() int { return 16 }
|
||||
|
||||
// NewBlockHashes is the network packet for the block announcements.
|
||||
type NewBlockHashes []struct {
|
||||
Hash common.Hash // Hash of one particular block being announced
|
||||
Number uint64 // Number of one particular block being announced
|
||||
}
|
||||
type NewBlockHashes eth.NewBlockHashesPacket
|
||||
|
||||
func (nbh NewBlockHashes) Code() int { return 17 }
|
||||
|
||||
type Transactions []*types.Transaction
|
||||
type Transactions eth.TransactionsPacket
|
||||
|
||||
func (t Transactions) Code() int { return 18 }
|
||||
|
||||
// GetBlockHeaders represents a block header query.
|
||||
type GetBlockHeaders struct {
|
||||
Origin hashOrNumber // Block from which to retrieve headers
|
||||
Amount uint64 // Maximum number of headers to retrieve
|
||||
Skip uint64 // Blocks to skip between consecutive headers
|
||||
Reverse bool // Query direction (false = rising towards latest, true = falling towards genesis)
|
||||
}
|
||||
type GetBlockHeaders eth.GetBlockHeadersPacket
|
||||
|
||||
func (g GetBlockHeaders) Code() int { return 19 }
|
||||
|
||||
type BlockHeaders []*types.Header
|
||||
type BlockHeaders eth.BlockHeadersPacket
|
||||
|
||||
func (bh BlockHeaders) Code() int { return 20 }
|
||||
|
||||
// GetBlockBodies represents a GetBlockBodies request
|
||||
type GetBlockBodies []common.Hash
|
||||
type GetBlockBodies eth.GetBlockBodiesPacket
|
||||
|
||||
func (gbb GetBlockBodies) Code() int { return 21 }
|
||||
|
||||
// BlockBodies is the network packet for block content distribution.
|
||||
type BlockBodies []*types.Body
|
||||
type BlockBodies eth.BlockBodiesPacket
|
||||
|
||||
func (bb BlockBodies) Code() int { return 22 }
|
||||
|
||||
// NewBlock is the network packet for the block propagation message.
|
||||
type NewBlock struct {
|
||||
Block *types.Block
|
||||
TD *big.Int
|
||||
}
|
||||
type NewBlock eth.NewBlockPacket
|
||||
|
||||
func (nb NewBlock) Code() int { return 23 }
|
||||
|
||||
// NewPooledTransactionHashes is the network packet for the tx hash propagation message.
|
||||
type NewPooledTransactionHashes [][32]byte
|
||||
type NewPooledTransactionHashes eth.NewPooledTransactionHashesPacket
|
||||
|
||||
func (nb NewPooledTransactionHashes) Code() int { return 24 }
|
||||
|
||||
// HashOrNumber is a combined field for specifying an origin block.
|
||||
type hashOrNumber struct {
|
||||
Hash common.Hash // Block hash from which to retrieve headers (excludes Number)
|
||||
Number uint64 // Block hash from which to retrieve headers (excludes Hash)
|
||||
}
|
||||
type GetPooledTransactions eth.GetPooledTransactionsPacket
|
||||
|
||||
// EncodeRLP is a specialized encoder for hashOrNumber to encode only one of the
|
||||
// two contained union fields.
|
||||
func (hn *hashOrNumber) EncodeRLP(w io.Writer) error {
|
||||
if hn.Hash == (common.Hash{}) {
|
||||
return rlp.Encode(w, hn.Number)
|
||||
}
|
||||
if hn.Number != 0 {
|
||||
return fmt.Errorf("both origin hash (%x) and number (%d) provided", hn.Hash, hn.Number)
|
||||
}
|
||||
return rlp.Encode(w, hn.Hash)
|
||||
}
|
||||
func (gpt GetPooledTransactions) Code() int { return 25 }
|
||||
|
||||
// DecodeRLP is a specialized decoder for hashOrNumber to decode the contents
|
||||
// into either a block hash or a block number.
|
||||
func (hn *hashOrNumber) DecodeRLP(s *rlp.Stream) error {
|
||||
_, size, _ := s.Kind()
|
||||
origin, err := s.Raw()
|
||||
if err == nil {
|
||||
switch {
|
||||
case size == 32:
|
||||
err = rlp.DecodeBytes(origin, &hn.Hash)
|
||||
case size <= 8:
|
||||
err = rlp.DecodeBytes(origin, &hn.Number)
|
||||
default:
|
||||
err = fmt.Errorf("invalid input size %d for origin", size)
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
type PooledTransactions eth.PooledTransactionsPacket
|
||||
|
||||
func (pt PooledTransactions) Code() int { return 26 }
|
||||
|
||||
// Conn represents an individual connection with a peer
|
||||
type Conn struct {
|
||||
*rlpx.Conn
|
||||
ourKey *ecdsa.PrivateKey
|
||||
ethProtocolVersion uint
|
||||
ourKey *ecdsa.PrivateKey
|
||||
negotiatedProtoVersion uint
|
||||
ourHighestProtoVersion uint
|
||||
caps []p2p.Cap
|
||||
}
|
||||
|
||||
// Read reads an eth packet from the connection.
|
||||
func (c *Conn) Read() Message {
|
||||
code, rawData, _, err := c.Conn.Read()
|
||||
if err != nil {
|
||||
@@ -218,45 +167,104 @@ func (c *Conn) Read() Message {
|
||||
msg = new(Transactions)
|
||||
case (NewPooledTransactionHashes{}).Code():
|
||||
msg = new(NewPooledTransactionHashes)
|
||||
case (GetPooledTransactions{}.Code()):
|
||||
msg = new(GetPooledTransactions)
|
||||
case (PooledTransactions{}.Code()):
|
||||
msg = new(PooledTransactions)
|
||||
default:
|
||||
return errorf("invalid message code: %d", code)
|
||||
}
|
||||
|
||||
// if message is devp2p, decode here
|
||||
if err := rlp.DecodeBytes(rawData, msg); err != nil {
|
||||
return errorf("could not rlp decode message: %v", err)
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
// ReadAndServe serves GetBlockHeaders requests while waiting
|
||||
// on another message from the node.
|
||||
func (c *Conn) ReadAndServe(chain *Chain, timeout time.Duration) Message {
|
||||
start := time.Now()
|
||||
for time.Since(start) < timeout {
|
||||
timeout := time.Now().Add(10 * time.Second)
|
||||
c.SetReadDeadline(timeout)
|
||||
switch msg := c.Read().(type) {
|
||||
case *Ping:
|
||||
c.Write(&Pong{})
|
||||
case *GetBlockHeaders:
|
||||
req := *msg
|
||||
headers, err := chain.GetHeaders(req)
|
||||
if err != nil {
|
||||
return errorf("could not get headers for inbound header request: %v", err)
|
||||
}
|
||||
|
||||
if err := c.Write(headers); err != nil {
|
||||
return errorf("could not write to connection: %v", err)
|
||||
}
|
||||
default:
|
||||
return msg
|
||||
}
|
||||
// Read66 reads an eth66 packet from the connection.
|
||||
func (c *Conn) Read66() (uint64, Message) {
|
||||
code, rawData, _, err := c.Conn.Read()
|
||||
if err != nil {
|
||||
return 0, errorf("could not read from connection: %v", err)
|
||||
}
|
||||
return errorf("no message received within %v", timeout)
|
||||
|
||||
var msg Message
|
||||
switch int(code) {
|
||||
case (Hello{}).Code():
|
||||
msg = new(Hello)
|
||||
case (Ping{}).Code():
|
||||
msg = new(Ping)
|
||||
case (Pong{}).Code():
|
||||
msg = new(Pong)
|
||||
case (Disconnect{}).Code():
|
||||
msg = new(Disconnect)
|
||||
case (Status{}).Code():
|
||||
msg = new(Status)
|
||||
case (GetBlockHeaders{}).Code():
|
||||
ethMsg := new(eth.GetBlockHeadersPacket66)
|
||||
if err := rlp.DecodeBytes(rawData, ethMsg); err != nil {
|
||||
return 0, errorf("could not rlp decode message: %v", err)
|
||||
}
|
||||
return ethMsg.RequestId, GetBlockHeaders(*ethMsg.GetBlockHeadersPacket)
|
||||
case (BlockHeaders{}).Code():
|
||||
ethMsg := new(eth.BlockHeadersPacket66)
|
||||
if err := rlp.DecodeBytes(rawData, ethMsg); err != nil {
|
||||
return 0, errorf("could not rlp decode message: %v", err)
|
||||
}
|
||||
return ethMsg.RequestId, BlockHeaders(ethMsg.BlockHeadersPacket)
|
||||
case (GetBlockBodies{}).Code():
|
||||
ethMsg := new(eth.GetBlockBodiesPacket66)
|
||||
if err := rlp.DecodeBytes(rawData, ethMsg); err != nil {
|
||||
return 0, errorf("could not rlp decode message: %v", err)
|
||||
}
|
||||
return ethMsg.RequestId, GetBlockBodies(ethMsg.GetBlockBodiesPacket)
|
||||
case (BlockBodies{}).Code():
|
||||
ethMsg := new(eth.BlockBodiesPacket66)
|
||||
if err := rlp.DecodeBytes(rawData, ethMsg); err != nil {
|
||||
return 0, errorf("could not rlp decode message: %v", err)
|
||||
}
|
||||
return ethMsg.RequestId, BlockBodies(ethMsg.BlockBodiesPacket)
|
||||
case (NewBlock{}).Code():
|
||||
msg = new(NewBlock)
|
||||
case (NewBlockHashes{}).Code():
|
||||
msg = new(NewBlockHashes)
|
||||
case (Transactions{}).Code():
|
||||
msg = new(Transactions)
|
||||
case (NewPooledTransactionHashes{}).Code():
|
||||
msg = new(NewPooledTransactionHashes)
|
||||
case (GetPooledTransactions{}.Code()):
|
||||
ethMsg := new(eth.GetPooledTransactionsPacket66)
|
||||
if err := rlp.DecodeBytes(rawData, ethMsg); err != nil {
|
||||
return 0, errorf("could not rlp decode message: %v", err)
|
||||
}
|
||||
return ethMsg.RequestId, GetPooledTransactions(ethMsg.GetPooledTransactionsPacket)
|
||||
case (PooledTransactions{}.Code()):
|
||||
ethMsg := new(eth.PooledTransactionsPacket66)
|
||||
if err := rlp.DecodeBytes(rawData, ethMsg); err != nil {
|
||||
return 0, errorf("could not rlp decode message: %v", err)
|
||||
}
|
||||
return ethMsg.RequestId, PooledTransactions(ethMsg.PooledTransactionsPacket)
|
||||
default:
|
||||
msg = errorf("invalid message code: %d", code)
|
||||
}
|
||||
|
||||
if msg != nil {
|
||||
if err := rlp.DecodeBytes(rawData, msg); err != nil {
|
||||
return 0, errorf("could not rlp decode message: %v", err)
|
||||
}
|
||||
return 0, msg
|
||||
}
|
||||
return 0, errorf("invalid message: %s", string(rawData))
|
||||
}
|
||||
|
||||
// Write writes a eth packet to the connection.
|
||||
func (c *Conn) Write(msg Message) error {
|
||||
payload, err := rlp.EncodeToBytes(msg)
|
||||
// check if message is eth protocol message
|
||||
var (
|
||||
payload []byte
|
||||
err error
|
||||
)
|
||||
payload, err = rlp.EncodeToBytes(msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -264,132 +272,12 @@ func (c *Conn) Write(msg Message) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// handshake checks to make sure a `HELLO` is received.
|
||||
func (c *Conn) handshake(t *utesting.T) Message {
|
||||
defer c.SetDeadline(time.Time{})
|
||||
c.SetDeadline(time.Now().Add(10 * time.Second))
|
||||
|
||||
// write hello to client
|
||||
pub0 := crypto.FromECDSAPub(&c.ourKey.PublicKey)[1:]
|
||||
ourHandshake := &Hello{
|
||||
Version: 5,
|
||||
Caps: []p2p.Cap{
|
||||
{Name: "eth", Version: 64},
|
||||
{Name: "eth", Version: 65},
|
||||
},
|
||||
ID: pub0,
|
||||
}
|
||||
if err := c.Write(ourHandshake); err != nil {
|
||||
t.Fatalf("could not write to connection: %v", err)
|
||||
}
|
||||
// read hello from client
|
||||
switch msg := c.Read().(type) {
|
||||
case *Hello:
|
||||
// set snappy if version is at least 5
|
||||
if msg.Version >= 5 {
|
||||
c.SetSnappy(true)
|
||||
}
|
||||
c.negotiateEthProtocol(msg.Caps)
|
||||
if c.ethProtocolVersion == 0 {
|
||||
t.Fatalf("unexpected eth protocol version")
|
||||
}
|
||||
return msg
|
||||
default:
|
||||
t.Fatalf("bad handshake: %#v", msg)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// negotiateEthProtocol sets the Conn's eth protocol version
|
||||
// to highest advertised capability from peer
|
||||
func (c *Conn) negotiateEthProtocol(caps []p2p.Cap) {
|
||||
var highestEthVersion uint
|
||||
for _, capability := range caps {
|
||||
if capability.Name != "eth" {
|
||||
continue
|
||||
}
|
||||
if capability.Version > highestEthVersion && capability.Version <= 65 {
|
||||
highestEthVersion = capability.Version
|
||||
}
|
||||
}
|
||||
c.ethProtocolVersion = highestEthVersion
|
||||
}
|
||||
|
||||
// statusExchange performs a `Status` message exchange with the given
|
||||
// node.
|
||||
func (c *Conn) statusExchange(t *utesting.T, chain *Chain, status *Status) Message {
|
||||
defer c.SetDeadline(time.Time{})
|
||||
c.SetDeadline(time.Now().Add(20 * time.Second))
|
||||
|
||||
// read status message from client
|
||||
var message Message
|
||||
loop:
|
||||
for {
|
||||
switch msg := c.Read().(type) {
|
||||
case *Status:
|
||||
if msg.Head != chain.blocks[chain.Len()-1].Hash() {
|
||||
t.Fatalf("wrong head block in status: %s", msg.Head.String())
|
||||
}
|
||||
if msg.TD.Cmp(chain.TD(chain.Len())) != 0 {
|
||||
t.Fatalf("wrong TD in status: %v", msg.TD)
|
||||
}
|
||||
if !reflect.DeepEqual(msg.ForkID, chain.ForkID()) {
|
||||
t.Fatalf("wrong fork ID in status: %v", msg.ForkID)
|
||||
}
|
||||
message = msg
|
||||
break loop
|
||||
case *Disconnect:
|
||||
t.Fatalf("disconnect received: %v", msg.Reason)
|
||||
case *Ping:
|
||||
c.Write(&Pong{}) // TODO (renaynay): in the future, this should be an error
|
||||
// (PINGs should not be a response upon fresh connection)
|
||||
default:
|
||||
t.Fatalf("bad status message: %s", pretty.Sdump(msg))
|
||||
}
|
||||
}
|
||||
// make sure eth protocol version is set for negotiation
|
||||
if c.ethProtocolVersion == 0 {
|
||||
t.Fatalf("eth protocol version must be set in Conn")
|
||||
}
|
||||
if status == nil {
|
||||
// write status message to client
|
||||
status = &Status{
|
||||
ProtocolVersion: uint32(c.ethProtocolVersion),
|
||||
NetworkID: chain.chainConfig.ChainID.Uint64(),
|
||||
TD: chain.TD(chain.Len()),
|
||||
Head: chain.blocks[chain.Len()-1].Hash(),
|
||||
Genesis: chain.blocks[0].Hash(),
|
||||
ForkID: chain.ForkID(),
|
||||
}
|
||||
}
|
||||
|
||||
if err := c.Write(*status); err != nil {
|
||||
t.Fatalf("could not write to connection: %v", err)
|
||||
}
|
||||
|
||||
return message
|
||||
}
|
||||
|
||||
// waitForBlock waits for confirmation from the client that it has
|
||||
// imported the given block.
|
||||
func (c *Conn) waitForBlock(block *types.Block) error {
|
||||
defer c.SetReadDeadline(time.Time{})
|
||||
|
||||
timeout := time.Now().Add(20 * time.Second)
|
||||
c.SetReadDeadline(timeout)
|
||||
for {
|
||||
req := &GetBlockHeaders{Origin: hashOrNumber{Hash: block.Hash()}, Amount: 1}
|
||||
if err := c.Write(req); err != nil {
|
||||
return err
|
||||
}
|
||||
switch msg := c.Read().(type) {
|
||||
case *BlockHeaders:
|
||||
if len(*msg) > 0 {
|
||||
return nil
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
default:
|
||||
return fmt.Errorf("invalid message: %s", pretty.Sdump(msg))
|
||||
}
|
||||
// Write66 writes an eth66 packet to the connection.
|
||||
func (c *Conn) Write66(req eth.Packet, code int) error {
|
||||
payload, err := rlp.EncodeToBytes(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = c.Conn.Write(uint64(code), payload)
|
||||
return err
|
||||
}
|
||||
|
@@ -21,7 +21,6 @@ import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"net"
|
||||
"reflect"
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
@@ -80,25 +79,57 @@ func BasicPing(t *utesting.T) {
|
||||
To: te.remoteEndpoint(),
|
||||
Expiration: futureExpiration(),
|
||||
})
|
||||
|
||||
reply, _, _ := te.read(te.l1)
|
||||
if err := te.checkPong(reply, pingHash); err != nil {
|
||||
if err := te.checkPingPong(pingHash); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// checkPong verifies that reply is a valid PONG matching the given ping hash.
|
||||
// checkPingPong verifies that the remote side sends both a PONG with the
|
||||
// correct hash, and a PING.
|
||||
// The two packets do not have to be in any particular order.
|
||||
func (te *testenv) checkPingPong(pingHash []byte) error {
|
||||
var (
|
||||
pings int
|
||||
pongs int
|
||||
)
|
||||
for i := 0; i < 2; i++ {
|
||||
reply, _, err := te.read(te.l1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch reply.Kind() {
|
||||
case v4wire.PongPacket:
|
||||
if err := te.checkPong(reply, pingHash); err != nil {
|
||||
return err
|
||||
}
|
||||
pongs++
|
||||
case v4wire.PingPacket:
|
||||
pings++
|
||||
default:
|
||||
return fmt.Errorf("expected PING or PONG, got %v %v", reply.Name(), reply)
|
||||
}
|
||||
}
|
||||
if pongs == 1 && pings == 1 {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("expected 1 PING (got %d) and 1 PONG (got %d)", pings, pongs)
|
||||
}
|
||||
|
||||
// checkPong verifies that reply is a valid PONG matching the given ping hash,
|
||||
// and a PING. The two packets do not have to be in any particular order.
|
||||
func (te *testenv) checkPong(reply v4wire.Packet, pingHash []byte) error {
|
||||
if reply == nil || reply.Kind() != v4wire.PongPacket {
|
||||
return fmt.Errorf("expected PONG reply, got %v", reply)
|
||||
if reply == nil {
|
||||
return fmt.Errorf("expected PONG reply, got nil")
|
||||
}
|
||||
if reply.Kind() != v4wire.PongPacket {
|
||||
return fmt.Errorf("expected PONG reply, got %v %v", reply.Name(), reply)
|
||||
}
|
||||
pong := reply.(*v4wire.Pong)
|
||||
if !bytes.Equal(pong.ReplyTok, pingHash) {
|
||||
return fmt.Errorf("PONG reply token mismatch: got %x, want %x", pong.ReplyTok, pingHash)
|
||||
}
|
||||
wantEndpoint := te.localEndpoint(te.l1)
|
||||
if !reflect.DeepEqual(pong.To, wantEndpoint) {
|
||||
return fmt.Errorf("PONG 'to' endpoint mismatch: got %+v, want %+v", pong.To, wantEndpoint)
|
||||
if want := te.localEndpoint(te.l1); !want.IP.Equal(pong.To.IP) || want.UDP != pong.To.UDP {
|
||||
return fmt.Errorf("PONG 'to' endpoint mismatch: got %+v, want %+v", pong.To, want)
|
||||
}
|
||||
if v4wire.Expired(pong.Expiration) {
|
||||
return fmt.Errorf("PONG is expired (%v)", pong.Expiration)
|
||||
@@ -118,9 +149,7 @@ func PingWrongTo(t *utesting.T) {
|
||||
To: wrongEndpoint,
|
||||
Expiration: futureExpiration(),
|
||||
})
|
||||
|
||||
reply, _, _ := te.read(te.l1)
|
||||
if err := te.checkPong(reply, pingHash); err != nil {
|
||||
if err := te.checkPingPong(pingHash); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -138,8 +167,7 @@ func PingWrongFrom(t *utesting.T) {
|
||||
Expiration: futureExpiration(),
|
||||
})
|
||||
|
||||
reply, _, _ := te.read(te.l1)
|
||||
if err := te.checkPong(reply, pingHash); err != nil {
|
||||
if err := te.checkPingPong(pingHash); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -160,8 +188,7 @@ func PingExtraData(t *utesting.T) {
|
||||
JunkData2: []byte{9, 8, 7, 6, 5, 4, 3, 2, 1},
|
||||
})
|
||||
|
||||
reply, _, _ := te.read(te.l1)
|
||||
if err := te.checkPong(reply, pingHash); err != nil {
|
||||
if err := te.checkPingPong(pingHash); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -182,8 +209,7 @@ func PingExtraDataWrongFrom(t *utesting.T) {
|
||||
JunkData2: []byte{9, 8, 7, 6, 5, 4, 3, 2, 1},
|
||||
}
|
||||
pingHash := te.send(te.l1, &req)
|
||||
reply, _, _ := te.read(te.l1)
|
||||
if err := te.checkPong(reply, pingHash); err != nil {
|
||||
if err := te.checkPingPong(pingHash); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -239,9 +265,9 @@ func BondThenPingWithWrongFrom(t *utesting.T) {
|
||||
To: te.remoteEndpoint(),
|
||||
Expiration: futureExpiration(),
|
||||
})
|
||||
|
||||
reply, _, _ := te.read(te.l1)
|
||||
if err := te.checkPong(reply, pingHash); err != nil {
|
||||
if reply, _, err := te.read(te.l1); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if err := te.checkPong(reply, pingHash); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
@@ -71,6 +71,7 @@ func writeNodesJSON(file string, nodes nodeSet) {
|
||||
}
|
||||
}
|
||||
|
||||
// nodes returns the node records contained in the set.
|
||||
func (ns nodeSet) nodes() []*enode.Node {
|
||||
result := make([]*enode.Node, 0, len(ns))
|
||||
for _, n := range ns {
|
||||
@@ -83,12 +84,37 @@ func (ns nodeSet) nodes() []*enode.Node {
|
||||
return result
|
||||
}
|
||||
|
||||
// add ensures the given nodes are present in the set.
|
||||
func (ns nodeSet) add(nodes ...*enode.Node) {
|
||||
for _, n := range nodes {
|
||||
ns[n.ID()] = nodeJSON{Seq: n.Seq(), N: n}
|
||||
v := ns[n.ID()]
|
||||
v.N = n
|
||||
v.Seq = n.Seq()
|
||||
ns[n.ID()] = v
|
||||
}
|
||||
}
|
||||
|
||||
// topN returns the top n nodes by score as a new set.
|
||||
func (ns nodeSet) topN(n int) nodeSet {
|
||||
if n >= len(ns) {
|
||||
return ns
|
||||
}
|
||||
|
||||
byscore := make([]nodeJSON, 0, len(ns))
|
||||
for _, v := range ns {
|
||||
byscore = append(byscore, v)
|
||||
}
|
||||
sort.Slice(byscore, func(i, j int) bool {
|
||||
return byscore[i].Score >= byscore[j].Score
|
||||
})
|
||||
result := make(nodeSet, n)
|
||||
for _, v := range byscore[:n] {
|
||||
result[v.N.ID()] = v
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// verify performs integrity checks on the node set.
|
||||
func (ns nodeSet) verify() error {
|
||||
for id, n := range ns {
|
||||
if n.N.ID() != id {
|
||||
|
@@ -17,8 +17,12 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/core/forkid"
|
||||
@@ -60,25 +64,64 @@ func nodesetInfo(ctx *cli.Context) error {
|
||||
|
||||
ns := loadNodesJSON(ctx.Args().First())
|
||||
fmt.Printf("Set contains %d nodes.\n", len(ns))
|
||||
showAttributeCounts(ns)
|
||||
return nil
|
||||
}
|
||||
|
||||
// showAttributeCounts prints the distribution of ENR attributes in a node set.
|
||||
func showAttributeCounts(ns nodeSet) {
|
||||
attrcount := make(map[string]int)
|
||||
var attrlist []interface{}
|
||||
for _, n := range ns {
|
||||
r := n.N.Record()
|
||||
attrlist = r.AppendElements(attrlist[:0])[1:]
|
||||
for i := 0; i < len(attrlist); i += 2 {
|
||||
key := attrlist[i].(string)
|
||||
attrcount[key]++
|
||||
}
|
||||
}
|
||||
|
||||
var keys []string
|
||||
var maxlength int
|
||||
for key := range attrcount {
|
||||
keys = append(keys, key)
|
||||
if len(key) > maxlength {
|
||||
maxlength = len(key)
|
||||
}
|
||||
}
|
||||
sort.Strings(keys)
|
||||
fmt.Println("ENR attribute counts:")
|
||||
for _, key := range keys {
|
||||
fmt.Printf("%s%s: %d\n", strings.Repeat(" ", maxlength-len(key)+1), key, attrcount[key])
|
||||
}
|
||||
}
|
||||
|
||||
func nodesetFilter(ctx *cli.Context) error {
|
||||
if ctx.NArg() < 1 {
|
||||
return fmt.Errorf("need nodes file as argument")
|
||||
}
|
||||
ns := loadNodesJSON(ctx.Args().First())
|
||||
// Parse -limit.
|
||||
limit, err := parseFilterLimit(ctx.Args().Tail())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Parse the filters.
|
||||
filter, err := andFilter(ctx.Args().Tail())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Load nodes and apply filters.
|
||||
ns := loadNodesJSON(ctx.Args().First())
|
||||
result := make(nodeSet)
|
||||
for id, n := range ns {
|
||||
if filter(n) {
|
||||
result[id] = n
|
||||
}
|
||||
}
|
||||
if limit >= 0 {
|
||||
result = result.topN(limit)
|
||||
}
|
||||
writeNodesJSON("-", result)
|
||||
return nil
|
||||
}
|
||||
@@ -91,6 +134,7 @@ type nodeFilterC struct {
|
||||
}
|
||||
|
||||
var filterFlags = map[string]nodeFilterC{
|
||||
"-limit": {1, trueFilter}, // needed to skip over -limit
|
||||
"-ip": {1, ipFilter},
|
||||
"-min-age": {1, minAgeFilter},
|
||||
"-eth-network": {1, ethFilter},
|
||||
@@ -98,6 +142,7 @@ var filterFlags = map[string]nodeFilterC{
|
||||
"-snap": {0, snapFilter},
|
||||
}
|
||||
|
||||
// parseFilters parses nodeFilters from args.
|
||||
func parseFilters(args []string) ([]nodeFilter, error) {
|
||||
var filters []nodeFilter
|
||||
for len(args) > 0 {
|
||||
@@ -118,6 +163,26 @@ func parseFilters(args []string) ([]nodeFilter, error) {
|
||||
return filters, nil
|
||||
}
|
||||
|
||||
// parseFilterLimit parses the -limit option in args. It returns -1 if there is no limit.
|
||||
func parseFilterLimit(args []string) (int, error) {
|
||||
limit := -1
|
||||
for i, arg := range args {
|
||||
if arg == "-limit" {
|
||||
if i == len(args)-1 {
|
||||
return -1, errors.New("-limit requires an argument")
|
||||
}
|
||||
n, err := strconv.Atoi(args[i+1])
|
||||
if err != nil {
|
||||
return -1, fmt.Errorf("invalid -limit %q", args[i+1])
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
}
|
||||
return limit, nil
|
||||
}
|
||||
|
||||
// andFilter parses node filters in args and and returns a single filter that requires all
|
||||
// of them to match.
|
||||
func andFilter(args []string) (nodeFilter, error) {
|
||||
checks, err := parseFilters(args)
|
||||
if err != nil {
|
||||
@@ -134,6 +199,10 @@ func andFilter(args []string) (nodeFilter, error) {
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func trueFilter(args []string) (nodeFilter, error) {
|
||||
return func(n nodeJSON) bool { return true }, nil
|
||||
}
|
||||
|
||||
func ipFilter(args []string) (nodeFilter, error) {
|
||||
_, cidr, err := net.ParseCIDR(args[0])
|
||||
if err != nil {
|
||||
@@ -173,7 +242,7 @@ func ethFilter(args []string) (nodeFilter, error) {
|
||||
f := func(n nodeJSON) bool {
|
||||
var eth struct {
|
||||
ForkID forkid.ID
|
||||
_ []rlp.RawValue `rlp:"tail"`
|
||||
Tail []rlp.RawValue `rlp:"tail"`
|
||||
}
|
||||
if n.N.Load(enr.WithEntry("eth", ð)) != nil {
|
||||
return false
|
||||
@@ -186,7 +255,7 @@ func ethFilter(args []string) (nodeFilter, error) {
|
||||
func lesFilter(args []string) (nodeFilter, error) {
|
||||
f := func(n nodeJSON) bool {
|
||||
var les struct {
|
||||
_ []rlp.RawValue `rlp:"tail"`
|
||||
Tail []rlp.RawValue `rlp:"tail"`
|
||||
}
|
||||
return n.N.Load(enr.WithEntry("les", &les)) == nil
|
||||
}
|
||||
@@ -196,7 +265,7 @@ func lesFilter(args []string) (nodeFilter, error) {
|
||||
func snapFilter(args []string) (nodeFilter, error) {
|
||||
f := func(n nodeJSON) bool {
|
||||
var snap struct {
|
||||
_ []rlp.RawValue `rlp:"tail"`
|
||||
Tail []rlp.RawValue `rlp:"tail"`
|
||||
}
|
||||
return n.N.Load(enr.WithEntry("snap", &snap)) == nil
|
||||
}
|
||||
|
@@ -22,6 +22,7 @@ import (
|
||||
|
||||
"github.com/ethereum/go-ethereum/cmd/devp2p/internal/ethtest"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/internal/utesting"
|
||||
"github.com/ethereum/go-ethereum/p2p"
|
||||
"github.com/ethereum/go-ethereum/p2p/rlpx"
|
||||
"github.com/ethereum/go-ethereum/rlp"
|
||||
@@ -94,6 +95,14 @@ func rlpxEthTest(ctx *cli.Context) error {
|
||||
if ctx.NArg() < 3 {
|
||||
exit("missing path to chain.rlp as command-line argument")
|
||||
}
|
||||
suite := ethtest.NewSuite(getNodeArg(ctx), ctx.Args()[1], ctx.Args()[2])
|
||||
return runTests(ctx, suite.AllTests())
|
||||
suite, err := ethtest.NewSuite(getNodeArg(ctx), ctx.Args()[1], ctx.Args()[2])
|
||||
if err != nil {
|
||||
exit(err)
|
||||
}
|
||||
// check if given node supports eth66, and if so, run eth66 protocol tests as well
|
||||
is66Failed, _ := utesting.Run(utesting.Test{Name: "Is_66", Fn: suite.Is_66})
|
||||
if is66Failed {
|
||||
return runTests(ctx, suite.EthTests())
|
||||
}
|
||||
return runTests(ctx, suite.AllEthTests())
|
||||
}
|
||||
|
@@ -26,7 +26,7 @@ import (
|
||||
"github.com/ethereum/go-ethereum/accounts/keystore"
|
||||
"github.com/ethereum/go-ethereum/cmd/utils"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/pborman/uuid"
|
||||
"github.com/google/uuid"
|
||||
"gopkg.in/urfave/cli.v1"
|
||||
)
|
||||
|
||||
@@ -86,9 +86,12 @@ If you want to encrypt an existing private key, it can be specified by setting
|
||||
}
|
||||
|
||||
// Create the keyfile object with a random UUID.
|
||||
id := uuid.NewRandom()
|
||||
UUID, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
utils.Fatalf("Failed to generate random uuid: %v", err)
|
||||
}
|
||||
key := &keystore.Key{
|
||||
Id: id,
|
||||
Id: UUID,
|
||||
Address: crypto.PubkeyToAddress(privateKey.PublicKey),
|
||||
PrivateKey: privateKey,
|
||||
}
|
||||
|
@@ -4,15 +4,15 @@ The `evm t8n` tool is a stateless state transition utility. It is a utility
|
||||
which can
|
||||
|
||||
1. Take a prestate, including
|
||||
- Accounts,
|
||||
- Block context information,
|
||||
- Previous blockshashes (*optional)
|
||||
- Accounts,
|
||||
- Block context information,
|
||||
- Previous blockshashes (*optional)
|
||||
2. Apply a set of transactions,
|
||||
3. Apply a mining-reward (*optional),
|
||||
4. And generate a post-state, including
|
||||
- State root, transaction root, receipt root,
|
||||
- Information about rejected transactions,
|
||||
- Optionally: a full or partial post-state dump
|
||||
- State root, transaction root, receipt root,
|
||||
- Information about rejected transactions,
|
||||
- Optionally: a full or partial post-state dump
|
||||
|
||||
## Specification
|
||||
|
||||
@@ -30,13 +30,15 @@ Command line params that has to be supported are
|
||||
--trace.nomemory Disable full memory dump in traces
|
||||
--trace.nostack Disable stack output in traces
|
||||
--trace.noreturndata Disable return data output in traces
|
||||
--output.basedir value Specifies where output files are placed. Will be created if it does not exist. (default: ".")
|
||||
--output.basedir value Specifies where output files are placed. Will be created if it does not exist.
|
||||
--output.alloc alloc Determines where to put the alloc of the post-state.
|
||||
`stdout` - into the stdout output
|
||||
`stderr` - into the stderr output
|
||||
--output.result result Determines where to put the result (stateroot, txroot etc) of the post-state.
|
||||
`stdout` - into the stdout output
|
||||
`stderr` - into the stderr output
|
||||
--output.body value If set, the RLP of the transactions (block body) will be written to this file.
|
||||
--input.txs stdin stdin or file name of where to find the transactions to apply. If the file prefix is '.rlp', then the data is interpreted as an RLP list of signed transactions.The '.rlp' format is identical to the output.body format. (default: "txs.json")
|
||||
--state.fork value Name of ruleset to use.
|
||||
--state.chainid value ChainID to use (default: 1)
|
||||
--state.reward value Mining reward. Set to -1 to disable (default: 0)
|
||||
@@ -110,7 +112,10 @@ Two resulting files:
|
||||
}
|
||||
],
|
||||
"rejected": [
|
||||
1
|
||||
{
|
||||
"index": 1,
|
||||
"error": "nonce too low: address 0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192, tx: 0 state: 1"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -156,7 +161,10 @@ Output:
|
||||
}
|
||||
],
|
||||
"rejected": [
|
||||
1
|
||||
{
|
||||
"index": 1,
|
||||
"error": "nonce too low: address 0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192, tx: 0 state: 1"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -168,9 +176,9 @@ Mining rewards and ommer rewards might need to be added. This is how those are a
|
||||
|
||||
- `block_reward` is the block mining reward for the miner (`0xaa`), of a block at height `N`.
|
||||
- For each ommer (mined by `0xbb`), with blocknumber `N-delta`
|
||||
- (where `delta` is the difference between the current block and the ommer)
|
||||
- The account `0xbb` (ommer miner) is awarded `(8-delta)/ 8 * block_reward`
|
||||
- The account `0xaa` (block miner) is awarded `block_reward / 32`
|
||||
- (where `delta` is the difference between the current block and the ommer)
|
||||
- The account `0xbb` (ommer miner) is awarded `(8-delta)/ 8 * block_reward`
|
||||
- The account `0xaa` (block miner) is awarded `block_reward / 32`
|
||||
|
||||
To make `state_t8n` apply these, the following inputs are required:
|
||||
|
||||
@@ -220,7 +228,7 @@ Output:
|
||||
### Future EIPS
|
||||
|
||||
It is also possible to experiment with future eips that are not yet defined in a hard fork.
|
||||
Example, putting EIP-1344 into Frontier:
|
||||
Example, putting EIP-1344 into Frontier:
|
||||
```
|
||||
./evm t8n --state.fork=Frontier+1344 --input.pre=./testdata/1/pre.json --input.txs=./testdata/1/txs.json --input.env=/testdata/1/env.json
|
||||
```
|
||||
@@ -229,42 +237,102 @@ Example, putting EIP-1344 into Frontier:
|
||||
|
||||
The `BLOCKHASH` opcode requires blockhashes to be provided by the caller, inside the `env`.
|
||||
If a required blockhash is not provided, the exit code should be `4`:
|
||||
Example where blockhashes are provided:
|
||||
Example where blockhashes are provided:
|
||||
```
|
||||
./evm t8n --input.alloc=./testdata/3/alloc.json --input.txs=./testdata/3/txs.json --input.env=./testdata/3/env.json --trace
|
||||
./evm --verbosity=1 t8n --input.alloc=./testdata/3/alloc.json --input.txs=./testdata/3/txs.json --input.env=./testdata/3/env.json --trace
|
||||
INFO [07-27|11:53:40.960] Trie dumping started root=b7341d..857ea1
|
||||
INFO [07-27|11:53:40.960] Trie dumping complete accounts=3 elapsed="103.298µs"
|
||||
INFO [07-27|11:53:40.960] Wrote file file=alloc.json
|
||||
INFO [07-27|11:53:40.960] Wrote file file=result.json
|
||||
|
||||
```
|
||||
|
||||
```
|
||||
cat trace-0-0x72fadbef39cd251a437eea619cfeda752271a5faaaa2147df012e112159ffb81.jsonl | grep BLOCKHASH -C2
|
||||
```
|
||||
```
|
||||
{"pc":0,"op":96,"gas":"0x5f58ef8","gasCost":"0x3","memory":"0x","memSize":0,"stack":[],"returnStack":[],"returnData":null,"depth":1,"refund":0,"opName":"PUSH1","error":""}
|
||||
{"pc":2,"op":64,"gas":"0x5f58ef5","gasCost":"0x14","memory":"0x","memSize":0,"stack":["0x1"],"returnStack":[],"returnData":null,"depth":1,"refund":0,"opName":"BLOCKHASH","error":""}
|
||||
{"pc":3,"op":0,"gas":"0x5f58ee1","gasCost":"0x0","memory":"0x","memSize":0,"stack":["0xdac58aa524e50956d0c0bae7f3f8bb9d35381365d07804dd5b48a5a297c06af4"],"returnStack":[],"returnData":null,"depth":1,"refund":0,"opName":"STOP","error":""}
|
||||
{"output":"","gasUsed":"0x17","time":112885}
|
||||
{"pc":0,"op":96,"gas":"0x5f58ef8","gasCost":"0x3","memory":"0x","memSize":0,"stack":[],"returnData":"0x","depth":1,"refund":0,"opName":"PUSH1","error":""}
|
||||
{"pc":2,"op":64,"gas":"0x5f58ef5","gasCost":"0x14","memory":"0x","memSize":0,"stack":["0x1"],"returnData":"0x","depth":1,"refund":0,"opName":"BLOCKHASH","error":""}
|
||||
{"pc":3,"op":0,"gas":"0x5f58ee1","gasCost":"0x0","memory":"0x","memSize":0,"stack":["0xdac58aa524e50956d0c0bae7f3f8bb9d35381365d07804dd5b48a5a297c06af4"],"returnData":"0x","depth":1,"refund":0,"opName":"STOP","error":""}
|
||||
{"output":"","gasUsed":"0x17","time":156276}
|
||||
```
|
||||
|
||||
In this example, the caller has not provided the required blockhash:
|
||||
```
|
||||
./evm t8n --input.alloc=./testdata/4/alloc.json --input.txs=./testdata/4/txs.json --input.env=./testdata/4/env.json --trace
|
||||
```
|
||||
```
|
||||
ERROR(4): getHash(3) invoked, blockhash for that block not provided
|
||||
```
|
||||
Error code: 4
|
||||
|
||||
### Chaining
|
||||
|
||||
Another thing that can be done, is to chain invocations:
|
||||
```
|
||||
./evm t8n --input.alloc=./testdata/1/alloc.json --input.txs=./testdata/1/txs.json --input.env=./testdata/1/env.json --output.alloc=stdout | ./evm t8n --input.alloc=stdin --input.env=./testdata/1/env.json --input.txs=./testdata/1/txs.json
|
||||
INFO [08-03|15:25:15.168] rejected tx index=1 hash="0557ba…18d673" from=0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192 error="nonce too low"
|
||||
INFO [08-03|15:25:15.169] rejected tx index=0 hash="0557ba…18d673" from=0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192 error="nonce too low"
|
||||
INFO [08-03|15:25:15.169] rejected tx index=1 hash="0557ba…18d673" from=0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192 error="nonce too low"
|
||||
INFO [07-27|11:53:41.049] rejected tx index=1 hash=0557ba..18d673 from=0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192 error="nonce too low: address 0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192, tx: 0 state: 1"
|
||||
INFO [07-27|11:53:41.050] Trie dumping started root=84208a..ae4e13
|
||||
INFO [07-27|11:53:41.050] Trie dumping complete accounts=3 elapsed="59.412µs"
|
||||
INFO [07-27|11:53:41.050] Wrote file file=result.json
|
||||
INFO [07-27|11:53:41.051] rejected tx index=0 hash=0557ba..18d673 from=0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192 error="nonce too low: address 0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192, tx: 0 state: 1"
|
||||
INFO [07-27|11:53:41.051] rejected tx index=1 hash=0557ba..18d673 from=0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192 error="nonce too low: address 0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192, tx: 0 state: 1"
|
||||
INFO [07-27|11:53:41.052] Trie dumping started root=84208a..ae4e13
|
||||
INFO [07-27|11:53:41.052] Trie dumping complete accounts=3 elapsed="45.734µs"
|
||||
INFO [07-27|11:53:41.052] Wrote file file=alloc.json
|
||||
INFO [07-27|11:53:41.052] Wrote file file=result.json
|
||||
|
||||
```
|
||||
What happened here, is that we first applied two identical transactions, so the second one was rejected.
|
||||
What happened here, is that we first applied two identical transactions, so the second one was rejected.
|
||||
Then, taking the poststate alloc as the input for the next state, we tried again to include
|
||||
the same two transactions: this time, both failed due to too low nonce.
|
||||
|
||||
In order to meaningfully chain invocations, one would need to provide meaningful new `env`, otherwise the
|
||||
actual blocknumber (exposed to the EVM) would not increase.
|
||||
|
||||
### Transactions in RLP form
|
||||
|
||||
It is possible to provide already-signed transactions as input to, using an `input.txs` which ends with the `rlp` suffix.
|
||||
The input format for RLP-form transactions is _identical_ to the _output_ format for block bodies. Therefore, it's fully possible
|
||||
to use the evm to go from `json` input to `rlp` input.
|
||||
|
||||
The following command takes **json** the transactions in `./testdata/13/txs.json` and signs them. After execution, they are output to `signed_txs.rlp`.:
|
||||
```
|
||||
./evm t8n --state.fork=London --input.alloc=./testdata/13/alloc.json --input.txs=./testdata/13/txs.json --input.env=./testdata/13/env.json --output.result=alloc_jsontx.json --output.body=signed_txs.rlp
|
||||
INFO [07-27|11:53:41.124] Trie dumping started root=e4b924..6aef61
|
||||
INFO [07-27|11:53:41.124] Trie dumping complete accounts=3 elapsed="94.284µs"
|
||||
INFO [07-27|11:53:41.125] Wrote file file=alloc.json
|
||||
INFO [07-27|11:53:41.125] Wrote file file=alloc_jsontx.json
|
||||
INFO [07-27|11:53:41.125] Wrote file file=signed_txs.rlp
|
||||
|
||||
```
|
||||
|
||||
The `output.body` is the rlp-list of transactions, encoded in hex and placed in a string a'la `json` encoding rules:
|
||||
```
|
||||
cat signed_txs.rlp
|
||||
"0xf8d2b86702f864010180820fa08284d09411111111111111111111111111111111111111118080c001a0b7dfab36232379bb3d1497a4f91c1966b1f932eae3ade107bf5d723b9cb474e0a06261c359a10f2132f126d250485b90cf20f30340801244a08ef6142ab33d1904b86702f864010280820fa08284d09411111111111111111111111111111111111111118080c080a0d4ec563b6568cd42d998fc4134b36933c6568d01533b5adf08769270243c6c7fa072bf7c21eac6bbeae5143371eef26d5e279637f3bd73482b55979d76d935b1e9"
|
||||
```
|
||||
|
||||
We can use `rlpdump` to check what the contents are:
|
||||
```
|
||||
rlpdump -hex $(cat signed_txs.rlp | jq -r )
|
||||
[
|
||||
02f864010180820fa08284d09411111111111111111111111111111111111111118080c001a0b7dfab36232379bb3d1497a4f91c1966b1f932eae3ade107bf5d723b9cb474e0a06261c359a10f2132f126d250485b90cf20f30340801244a08ef6142ab33d1904,
|
||||
02f864010280820fa08284d09411111111111111111111111111111111111111118080c080a0d4ec563b6568cd42d998fc4134b36933c6568d01533b5adf08769270243c6c7fa072bf7c21eac6bbeae5143371eef26d5e279637f3bd73482b55979d76d935b1e9,
|
||||
]
|
||||
```
|
||||
Now, we can now use those (or any other already signed transactions), as input, like so:
|
||||
```
|
||||
./evm t8n --state.fork=London --input.alloc=./testdata/13/alloc.json --input.txs=./signed_txs.rlp --input.env=./testdata/13/env.json --output.result=alloc_rlptx.json
|
||||
INFO [07-27|11:53:41.253] Trie dumping started root=e4b924..6aef61
|
||||
INFO [07-27|11:53:41.253] Trie dumping complete accounts=3 elapsed="128.445µs"
|
||||
INFO [07-27|11:53:41.253] Wrote file file=alloc.json
|
||||
INFO [07-27|11:53:41.255] Wrote file file=alloc_rlptx.json
|
||||
|
||||
```
|
||||
|
||||
You might have noticed that the results from these two invocations were stored in two separate files.
|
||||
And we can now finally check that they match.
|
||||
```
|
||||
cat alloc_jsontx.json | jq .stateRoot && cat alloc_rlptx.json | jq .stateRoot
|
||||
"0xe4b924a6adb5959fccf769d5b7bb2f6359e26d1e76a2443c5a91a36d826aef61"
|
||||
"0xe4b924a6adb5959fccf769d5b7bb2f6359e26d1e76a2443c5a91a36d826aef61"
|
||||
```
|
||||
|
@@ -52,7 +52,7 @@ type ExecutionResult struct {
|
||||
LogsHash common.Hash `json:"logsHash"`
|
||||
Bloom types.Bloom `json:"logsBloom" gencodec:"required"`
|
||||
Receipts types.Receipts `json:"receipts"`
|
||||
Rejected []int `json:"rejected,omitempty"`
|
||||
Rejected []*rejectedTx `json:"rejected,omitempty"`
|
||||
}
|
||||
|
||||
type ommer struct {
|
||||
@@ -69,6 +69,7 @@ type stEnv struct {
|
||||
Timestamp uint64 `json:"currentTimestamp" gencodec:"required"`
|
||||
BlockHashes map[math.HexOrDecimal64]common.Hash `json:"blockHashes,omitempty"`
|
||||
Ommers []ommer `json:"ommers,omitempty"`
|
||||
BaseFee *big.Int `json:"currentBaseFee,omitempty"`
|
||||
}
|
||||
|
||||
type stEnvMarshaling struct {
|
||||
@@ -77,6 +78,12 @@ type stEnvMarshaling struct {
|
||||
GasLimit math.HexOrDecimal64
|
||||
Number math.HexOrDecimal64
|
||||
Timestamp math.HexOrDecimal64
|
||||
BaseFee *math.HexOrDecimal256
|
||||
}
|
||||
|
||||
type rejectedTx struct {
|
||||
Index int `json:"index"`
|
||||
Err string `json:"error"`
|
||||
}
|
||||
|
||||
// Apply applies a set of transactions to a pre-state
|
||||
@@ -103,7 +110,7 @@ func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
|
||||
signer = types.MakeSigner(chainConfig, new(big.Int).SetUint64(pre.Env.Number))
|
||||
gaspool = new(core.GasPool)
|
||||
blockHash = common.Hash{0x13, 0x37}
|
||||
rejectedTxs []int
|
||||
rejectedTxs []*rejectedTx
|
||||
includedTxs types.Transactions
|
||||
gasUsed = uint64(0)
|
||||
receipts = make(types.Receipts, 0)
|
||||
@@ -120,6 +127,10 @@ func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
|
||||
GasLimit: pre.Env.GasLimit,
|
||||
GetHash: getHash,
|
||||
}
|
||||
// If currentBaseFee is defined, add it to the vmContext.
|
||||
if pre.Env.BaseFee != nil {
|
||||
vmContext.BaseFee = new(big.Int).Set(pre.Env.BaseFee)
|
||||
}
|
||||
// If DAO is supported/enabled, we need to handle it here. In geth 'proper', it's
|
||||
// done in StateProcessor.Process(block, ...), right before transactions are applied.
|
||||
if chainConfig.DAOForkSupport &&
|
||||
@@ -129,10 +140,10 @@ func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
|
||||
}
|
||||
|
||||
for i, tx := range txs {
|
||||
msg, err := tx.AsMessage(signer)
|
||||
msg, err := tx.AsMessage(signer, pre.Env.BaseFee)
|
||||
if err != nil {
|
||||
log.Info("rejected tx", "index", i, "hash", tx.Hash(), "error", err)
|
||||
rejectedTxs = append(rejectedTxs, i)
|
||||
log.Warn("rejected tx", "index", i, "hash", tx.Hash(), "error", err)
|
||||
rejectedTxs = append(rejectedTxs, &rejectedTx{i, err.Error()})
|
||||
continue
|
||||
}
|
||||
tracer, err := getTracerFn(txIndex, tx.Hash())
|
||||
@@ -141,27 +152,17 @@ func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
|
||||
}
|
||||
vmConfig.Tracer = tracer
|
||||
vmConfig.Debug = (tracer != nil)
|
||||
statedb.Prepare(tx.Hash(), blockHash, txIndex)
|
||||
statedb.Prepare(tx.Hash(), txIndex)
|
||||
txContext := core.NewEVMTxContext(msg)
|
||||
|
||||
evm := vm.NewEVM(vmContext, txContext, statedb, chainConfig, vmConfig)
|
||||
if chainConfig.IsYoloV2(vmContext.BlockNumber) {
|
||||
statedb.AddAddressToAccessList(msg.From())
|
||||
if dst := msg.To(); dst != nil {
|
||||
statedb.AddAddressToAccessList(*dst)
|
||||
// If it's a create-tx, the destination will be added inside evm.create
|
||||
}
|
||||
for _, addr := range evm.ActivePrecompiles() {
|
||||
statedb.AddAddressToAccessList(addr)
|
||||
}
|
||||
}
|
||||
snapshot := statedb.Snapshot()
|
||||
evm := vm.NewEVM(vmContext, txContext, statedb, chainConfig, vmConfig)
|
||||
|
||||
// (ret []byte, usedGas uint64, failed bool, err error)
|
||||
msgResult, err := core.ApplyMessage(evm, msg, gaspool)
|
||||
if err != nil {
|
||||
statedb.RevertToSnapshot(snapshot)
|
||||
log.Info("rejected tx", "index", i, "hash", tx.Hash(), "from", msg.From(), "error", err)
|
||||
rejectedTxs = append(rejectedTxs, i)
|
||||
rejectedTxs = append(rejectedTxs, &rejectedTx{i, err.Error()})
|
||||
continue
|
||||
}
|
||||
includedTxs = append(includedTxs, tx)
|
||||
@@ -169,7 +170,8 @@ func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
|
||||
return nil, nil, NewError(ErrorMissingBlockhash, hashError)
|
||||
}
|
||||
gasUsed += msgResult.UsedGas
|
||||
// Create a new receipt for the transaction, storing the intermediate root and gas used by the tx
|
||||
|
||||
// Receipt:
|
||||
{
|
||||
var root []byte
|
||||
if chainConfig.IsByzantium(vmContext.BlockNumber) {
|
||||
@@ -178,22 +180,32 @@ func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
|
||||
root = statedb.IntermediateRoot(chainConfig.IsEIP158(vmContext.BlockNumber)).Bytes()
|
||||
}
|
||||
|
||||
receipt := types.NewReceipt(root, msgResult.Failed(), gasUsed)
|
||||
// Create a new receipt for the transaction, storing the intermediate root and
|
||||
// gas used by the tx.
|
||||
receipt := &types.Receipt{Type: tx.Type(), PostState: root, CumulativeGasUsed: gasUsed}
|
||||
if msgResult.Failed() {
|
||||
receipt.Status = types.ReceiptStatusFailed
|
||||
} else {
|
||||
receipt.Status = types.ReceiptStatusSuccessful
|
||||
}
|
||||
receipt.TxHash = tx.Hash()
|
||||
receipt.GasUsed = msgResult.UsedGas
|
||||
// if the transaction created a contract, store the creation address in the receipt.
|
||||
|
||||
// If the transaction created a contract, store the creation address in the receipt.
|
||||
if msg.To() == nil {
|
||||
receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
|
||||
}
|
||||
// Set the receipt logs and create a bloom for filtering
|
||||
receipt.Logs = statedb.GetLogs(tx.Hash())
|
||||
|
||||
// Set the receipt logs and create the bloom filter.
|
||||
receipt.Logs = statedb.GetLogs(tx.Hash(), blockHash)
|
||||
receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
|
||||
// These three are non-consensus fields
|
||||
// These three are non-consensus fields:
|
||||
//receipt.BlockHash
|
||||
//receipt.BlockNumber =
|
||||
//receipt.BlockNumber
|
||||
receipt.TransactionIndex = uint(txIndex)
|
||||
receipts = append(receipts, receipt)
|
||||
}
|
||||
|
||||
txIndex++
|
||||
}
|
||||
statedb.IntermediateRoot(chainConfig.IsEIP158(vmContext.BlockNumber))
|
||||
@@ -229,8 +241,8 @@ func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
|
||||
}
|
||||
execRs := &ExecutionResult{
|
||||
StateRoot: root,
|
||||
TxRoot: types.DeriveSha(includedTxs, new(trie.Trie)),
|
||||
ReceiptRoot: types.DeriveSha(receipts, new(trie.Trie)),
|
||||
TxRoot: types.DeriveSha(includedTxs, trie.NewStackTrie(nil)),
|
||||
ReceiptRoot: types.DeriveSha(receipts, trie.NewStackTrie(nil)),
|
||||
Bloom: types.CreateBloom(receipts),
|
||||
LogsHash: rlpHash(statedb.Logs()),
|
||||
Receipts: receipts,
|
||||
|
@@ -47,6 +47,11 @@ var (
|
||||
Usage: "Specifies where output files are placed. Will be created if it does not exist.",
|
||||
Value: "",
|
||||
}
|
||||
OutputBodyFlag = cli.StringFlag{
|
||||
Name: "output.body",
|
||||
Usage: "If set, the RLP of the transactions (block body) will be written to this file.",
|
||||
Value: "",
|
||||
}
|
||||
OutputAllocFlag = cli.StringFlag{
|
||||
Name: "output.alloc",
|
||||
Usage: "Determines where to put the `alloc` of the post-state.\n" +
|
||||
@@ -74,8 +79,10 @@ var (
|
||||
Value: "env.json",
|
||||
}
|
||||
InputTxsFlag = cli.StringFlag{
|
||||
Name: "input.txs",
|
||||
Usage: "`stdin` or file name of where to find the transactions to apply.",
|
||||
Name: "input.txs",
|
||||
Usage: "`stdin` or file name of where to find the transactions to apply. " +
|
||||
"If the file prefix is '.rlp', then the data is interpreted as an RLP list of signed transactions." +
|
||||
"The '.rlp' format is identical to the output.body format.",
|
||||
Value: "txs.json",
|
||||
}
|
||||
RewardFlag = cli.Int64Flag{
|
||||
|
@@ -23,6 +23,7 @@ func (s stEnv) MarshalJSON() ([]byte, error) {
|
||||
Timestamp math.HexOrDecimal64 `json:"currentTimestamp" gencodec:"required"`
|
||||
BlockHashes map[math.HexOrDecimal64]common.Hash `json:"blockHashes,omitempty"`
|
||||
Ommers []ommer `json:"ommers,omitempty"`
|
||||
BaseFee *math.HexOrDecimal256 `json:"currentBaseFee,omitempty"`
|
||||
}
|
||||
var enc stEnv
|
||||
enc.Coinbase = common.UnprefixedAddress(s.Coinbase)
|
||||
@@ -32,6 +33,7 @@ func (s stEnv) MarshalJSON() ([]byte, error) {
|
||||
enc.Timestamp = math.HexOrDecimal64(s.Timestamp)
|
||||
enc.BlockHashes = s.BlockHashes
|
||||
enc.Ommers = s.Ommers
|
||||
enc.BaseFee = (*math.HexOrDecimal256)(s.BaseFee)
|
||||
return json.Marshal(&enc)
|
||||
}
|
||||
|
||||
@@ -45,6 +47,7 @@ func (s *stEnv) UnmarshalJSON(input []byte) error {
|
||||
Timestamp *math.HexOrDecimal64 `json:"currentTimestamp" gencodec:"required"`
|
||||
BlockHashes map[math.HexOrDecimal64]common.Hash `json:"blockHashes,omitempty"`
|
||||
Ommers []ommer `json:"ommers,omitempty"`
|
||||
BaseFee *math.HexOrDecimal256 `json:"currentBaseFee,omitempty"`
|
||||
}
|
||||
var dec stEnv
|
||||
if err := json.Unmarshal(input, &dec); err != nil {
|
||||
@@ -76,5 +79,8 @@ func (s *stEnv) UnmarshalJSON(input []byte) error {
|
||||
if dec.Ommers != nil {
|
||||
s.Ommers = dec.Ommers
|
||||
}
|
||||
if dec.BaseFee != nil {
|
||||
s.BaseFee = (*big.Int)(dec.BaseFee)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
@@ -17,20 +17,26 @@
|
||||
package t8ntool
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"math/big"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||
"github.com/ethereum/go-ethereum/core"
|
||||
"github.com/ethereum/go-ethereum/core/state"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/core/vm"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/log"
|
||||
"github.com/ethereum/go-ethereum/params"
|
||||
"github.com/ethereum/go-ethereum/rlp"
|
||||
"github.com/ethereum/go-ethereum/tests"
|
||||
"gopkg.in/urfave/cli.v1"
|
||||
)
|
||||
@@ -64,9 +70,10 @@ func (n *NumberedError) Code() int {
|
||||
}
|
||||
|
||||
type input struct {
|
||||
Alloc core.GenesisAlloc `json:"alloc,omitempty"`
|
||||
Env *stEnv `json:"env,omitempty"`
|
||||
Txs types.Transactions `json:"txs,omitempty"`
|
||||
Alloc core.GenesisAlloc `json:"alloc,omitempty"`
|
||||
Env *stEnv `json:"env,omitempty"`
|
||||
Txs []*txWithKey `json:"txs,omitempty"`
|
||||
TxRlp string `json:"txsRlp,omitempty"`
|
||||
}
|
||||
|
||||
func Main(ctx *cli.Context) error {
|
||||
@@ -135,10 +142,12 @@ func Main(ctx *cli.Context) error {
|
||||
txStr = ctx.String(InputTxsFlag.Name)
|
||||
inputData = &input{}
|
||||
)
|
||||
|
||||
// Figure out the prestate alloc
|
||||
if allocStr == stdinSelector || envStr == stdinSelector || txStr == stdinSelector {
|
||||
decoder := json.NewDecoder(os.Stdin)
|
||||
decoder.Decode(inputData)
|
||||
if err := decoder.Decode(inputData); err != nil {
|
||||
return NewError(ErrorJson, fmt.Errorf("failed unmarshaling stdin: %v", err))
|
||||
}
|
||||
}
|
||||
if allocStr != stdinSelector {
|
||||
inFile, err := os.Open(allocStr)
|
||||
@@ -148,10 +157,12 @@ func Main(ctx *cli.Context) error {
|
||||
defer inFile.Close()
|
||||
decoder := json.NewDecoder(inFile)
|
||||
if err := decoder.Decode(&inputData.Alloc); err != nil {
|
||||
return NewError(ErrorJson, fmt.Errorf("Failed unmarshaling alloc-file: %v", err))
|
||||
return NewError(ErrorJson, fmt.Errorf("failed unmarshaling alloc-file: %v", err))
|
||||
}
|
||||
}
|
||||
prestate.Pre = inputData.Alloc
|
||||
|
||||
// Set the block environment
|
||||
if envStr != stdinSelector {
|
||||
inFile, err := os.Open(envStr)
|
||||
if err != nil {
|
||||
@@ -161,30 +172,12 @@ func Main(ctx *cli.Context) error {
|
||||
decoder := json.NewDecoder(inFile)
|
||||
var env stEnv
|
||||
if err := decoder.Decode(&env); err != nil {
|
||||
return NewError(ErrorJson, fmt.Errorf("Failed unmarshaling env-file: %v", err))
|
||||
return NewError(ErrorJson, fmt.Errorf("failed unmarshaling env-file: %v", err))
|
||||
}
|
||||
inputData.Env = &env
|
||||
}
|
||||
|
||||
if txStr != stdinSelector {
|
||||
inFile, err := os.Open(txStr)
|
||||
if err != nil {
|
||||
return NewError(ErrorIO, fmt.Errorf("failed reading txs file: %v", err))
|
||||
}
|
||||
defer inFile.Close()
|
||||
decoder := json.NewDecoder(inFile)
|
||||
var txs types.Transactions
|
||||
if err := decoder.Decode(&txs); err != nil {
|
||||
return NewError(ErrorJson, fmt.Errorf("Failed unmarshaling txs-file: %v", err))
|
||||
}
|
||||
inputData.Txs = txs
|
||||
}
|
||||
|
||||
prestate.Pre = inputData.Alloc
|
||||
prestate.Env = *inputData.Env
|
||||
txs = inputData.Txs
|
||||
|
||||
// Iterate over all the tests, run them and aggregate the results
|
||||
vmConfig := vm.Config{
|
||||
Tracer: tracer,
|
||||
Debug: (tracer != nil),
|
||||
@@ -192,7 +185,7 @@ func Main(ctx *cli.Context) error {
|
||||
// Construct the chainconfig
|
||||
var chainConfig *params.ChainConfig
|
||||
if cConf, extraEips, err := tests.GetChainConfig(ctx.String(ForknameFlag.Name)); err != nil {
|
||||
return NewError(ErrorVMConfig, fmt.Errorf("Failed constructing chain configuration: %v", err))
|
||||
return NewError(ErrorVMConfig, fmt.Errorf("failed constructing chain configuration: %v", err))
|
||||
} else {
|
||||
chainConfig = cConf
|
||||
vmConfig.ExtraEips = extraEips
|
||||
@@ -200,17 +193,140 @@ func Main(ctx *cli.Context) error {
|
||||
// Set the chain id
|
||||
chainConfig.ChainID = big.NewInt(ctx.Int64(ChainIDFlag.Name))
|
||||
|
||||
var txsWithKeys []*txWithKey
|
||||
if txStr != stdinSelector {
|
||||
inFile, err := os.Open(txStr)
|
||||
if err != nil {
|
||||
return NewError(ErrorIO, fmt.Errorf("failed reading txs file: %v", err))
|
||||
}
|
||||
defer inFile.Close()
|
||||
decoder := json.NewDecoder(inFile)
|
||||
if strings.HasSuffix(txStr, ".rlp") {
|
||||
var body hexutil.Bytes
|
||||
if err := decoder.Decode(&body); err != nil {
|
||||
return err
|
||||
}
|
||||
var txs types.Transactions
|
||||
if err := rlp.DecodeBytes(body, &txs); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, tx := range txs {
|
||||
txsWithKeys = append(txsWithKeys, &txWithKey{
|
||||
key: nil,
|
||||
tx: tx,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
if err := decoder.Decode(&txsWithKeys); err != nil {
|
||||
return NewError(ErrorJson, fmt.Errorf("failed unmarshaling txs-file: %v", err))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if len(inputData.TxRlp) > 0 {
|
||||
// Decode the body of already signed transactions
|
||||
body := common.FromHex(inputData.TxRlp)
|
||||
var txs types.Transactions
|
||||
if err := rlp.DecodeBytes(body, &txs); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, tx := range txs {
|
||||
txsWithKeys = append(txsWithKeys, &txWithKey{
|
||||
key: nil,
|
||||
tx: tx,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// JSON encoded transactions
|
||||
txsWithKeys = inputData.Txs
|
||||
}
|
||||
}
|
||||
// We may have to sign the transactions.
|
||||
signer := types.MakeSigner(chainConfig, big.NewInt(int64(prestate.Env.Number)))
|
||||
|
||||
if txs, err = signUnsignedTransactions(txsWithKeys, signer); err != nil {
|
||||
return NewError(ErrorJson, fmt.Errorf("failed signing transactions: %v", err))
|
||||
}
|
||||
// Sanity check, to not `panic` in state_transition
|
||||
if chainConfig.IsLondon(big.NewInt(int64(prestate.Env.Number))) {
|
||||
if prestate.Env.BaseFee == nil {
|
||||
return NewError(ErrorVMConfig, errors.New("EIP-1559 config but missing 'currentBaseFee' in env section"))
|
||||
}
|
||||
}
|
||||
// Run the test and aggregate the result
|
||||
state, result, err := prestate.Apply(vmConfig, chainConfig, txs, ctx.Int64(RewardFlag.Name), getTracer)
|
||||
s, result, err := prestate.Apply(vmConfig, chainConfig, txs, ctx.Int64(RewardFlag.Name), getTracer)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
body, _ := rlp.EncodeToBytes(txs)
|
||||
// Dump the excution result
|
||||
//postAlloc := state.DumpGenesisFormat(false, false, false)
|
||||
collector := make(Alloc)
|
||||
state.DumpToCollector(collector, false, false, false, nil, -1)
|
||||
return dispatchOutput(ctx, baseDir, result, collector)
|
||||
s.DumpToCollector(collector, nil)
|
||||
return dispatchOutput(ctx, baseDir, result, collector, body)
|
||||
}
|
||||
|
||||
// txWithKey is a helper-struct, to allow us to use the types.Transaction along with
|
||||
// a `secretKey`-field, for input
|
||||
type txWithKey struct {
|
||||
key *ecdsa.PrivateKey
|
||||
tx *types.Transaction
|
||||
}
|
||||
|
||||
func (t *txWithKey) UnmarshalJSON(input []byte) error {
|
||||
// Read the secretKey, if present
|
||||
type sKey struct {
|
||||
Key *common.Hash `json:"secretKey"`
|
||||
}
|
||||
var key sKey
|
||||
if err := json.Unmarshal(input, &key); err != nil {
|
||||
return err
|
||||
}
|
||||
if key.Key != nil {
|
||||
k := key.Key.Hex()[2:]
|
||||
if ecdsaKey, err := crypto.HexToECDSA(k); err != nil {
|
||||
return err
|
||||
} else {
|
||||
t.key = ecdsaKey
|
||||
}
|
||||
}
|
||||
// Now, read the transaction itself
|
||||
var tx types.Transaction
|
||||
if err := json.Unmarshal(input, &tx); err != nil {
|
||||
return err
|
||||
}
|
||||
t.tx = &tx
|
||||
return nil
|
||||
}
|
||||
|
||||
// signUnsignedTransactions converts the input txs to canonical transactions.
|
||||
//
|
||||
// The transactions can have two forms, either
|
||||
// 1. unsigned or
|
||||
// 2. signed
|
||||
// For (1), r, s, v, need so be zero, and the `secretKey` needs to be set.
|
||||
// If so, we sign it here and now, with the given `secretKey`
|
||||
// If the condition above is not met, then it's considered a signed transaction.
|
||||
//
|
||||
// To manage this, we read the transactions twice, first trying to read the secretKeys,
|
||||
// and secondly to read them with the standard tx json format
|
||||
func signUnsignedTransactions(txs []*txWithKey, signer types.Signer) (types.Transactions, error) {
|
||||
var signedTxs []*types.Transaction
|
||||
for i, txWithKey := range txs {
|
||||
tx := txWithKey.tx
|
||||
key := txWithKey.key
|
||||
v, r, s := tx.RawSignatureValues()
|
||||
if key != nil && v.BitLen()+r.BitLen()+s.BitLen() == 0 {
|
||||
// This transaction needs to be signed
|
||||
signed, err := types.SignTx(tx, signer, key)
|
||||
if err != nil {
|
||||
return nil, NewError(ErrorJson, fmt.Errorf("tx %d: failed to sign tx: %v", i, err))
|
||||
}
|
||||
signedTxs = append(signedTxs, signed)
|
||||
} else {
|
||||
// Already signed
|
||||
signedTxs = append(signedTxs, tx)
|
||||
}
|
||||
}
|
||||
return signedTxs, nil
|
||||
}
|
||||
|
||||
type Alloc map[common.Address]core.GenesisAccount
|
||||
@@ -227,7 +343,7 @@ func (g Alloc) OnAccount(addr common.Address, dumpAccount state.DumpAccount) {
|
||||
}
|
||||
}
|
||||
genesisAccount := core.GenesisAccount{
|
||||
Code: common.FromHex(dumpAccount.Code),
|
||||
Code: dumpAccount.Code,
|
||||
Storage: storage,
|
||||
Balance: balance,
|
||||
Nonce: dumpAccount.Nonce,
|
||||
@@ -241,15 +357,17 @@ func saveFile(baseDir, filename string, data interface{}) error {
|
||||
if err != nil {
|
||||
return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err))
|
||||
}
|
||||
if err = ioutil.WriteFile(path.Join(baseDir, filename), b, 0644); err != nil {
|
||||
location := path.Join(baseDir, filename)
|
||||
if err = ioutil.WriteFile(location, b, 0644); err != nil {
|
||||
return NewError(ErrorIO, fmt.Errorf("failed writing output: %v", err))
|
||||
}
|
||||
log.Info("Wrote file", "file", location)
|
||||
return nil
|
||||
}
|
||||
|
||||
// dispatchOutput writes the output data to either stderr or stdout, or to the specified
|
||||
// files
|
||||
func dispatchOutput(ctx *cli.Context, baseDir string, result *ExecutionResult, alloc Alloc) error {
|
||||
func dispatchOutput(ctx *cli.Context, baseDir string, result *ExecutionResult, alloc Alloc, body hexutil.Bytes) error {
|
||||
stdOutObject := make(map[string]interface{})
|
||||
stdErrObject := make(map[string]interface{})
|
||||
dispatch := func(baseDir, fName, name string, obj interface{}) error {
|
||||
@@ -258,6 +376,8 @@ func dispatchOutput(ctx *cli.Context, baseDir string, result *ExecutionResult, a
|
||||
stdOutObject[name] = obj
|
||||
case "stderr":
|
||||
stdErrObject[name] = obj
|
||||
case "":
|
||||
// don't save
|
||||
default: // save to file
|
||||
if err := saveFile(baseDir, fName, obj); err != nil {
|
||||
return err
|
||||
@@ -271,12 +391,16 @@ func dispatchOutput(ctx *cli.Context, baseDir string, result *ExecutionResult, a
|
||||
if err := dispatch(baseDir, ctx.String(OutputResultFlag.Name), "result", result); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := dispatch(baseDir, ctx.String(OutputBodyFlag.Name), "body", body); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(stdOutObject) > 0 {
|
||||
b, err := json.MarshalIndent(stdOutObject, "", " ")
|
||||
if err != nil {
|
||||
return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err))
|
||||
}
|
||||
os.Stdout.Write(b)
|
||||
os.Stdout.Write([]byte("\n"))
|
||||
}
|
||||
if len(stdErrObject) > 0 {
|
||||
b, err := json.MarshalIndent(stdErrObject, "", " ")
|
||||
@@ -284,6 +408,7 @@ func dispatchOutput(ctx *cli.Context, baseDir string, result *ExecutionResult, a
|
||||
return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err))
|
||||
}
|
||||
os.Stderr.Write(b)
|
||||
os.Stderr.Write([]byte("\n"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
@@ -129,11 +129,6 @@ var (
|
||||
Name: "noreturndata",
|
||||
Usage: "disable return data output",
|
||||
}
|
||||
EVMInterpreterFlag = cli.StringFlag{
|
||||
Name: "vm.evm",
|
||||
Usage: "External EVM configuration (default = built-in interpreter)",
|
||||
Value: "",
|
||||
}
|
||||
)
|
||||
|
||||
var stateTransitionCommand = cli.Command{
|
||||
@@ -149,6 +144,7 @@ var stateTransitionCommand = cli.Command{
|
||||
t8ntool.OutputBasedir,
|
||||
t8ntool.OutputAllocFlag,
|
||||
t8ntool.OutputResultFlag,
|
||||
t8ntool.OutputBodyFlag,
|
||||
t8ntool.InputAllocFlag,
|
||||
t8ntool.InputEnvFlag,
|
||||
t8ntool.InputTxsFlag,
|
||||
@@ -184,7 +180,6 @@ func init() {
|
||||
DisableStackFlag,
|
||||
DisableStorageFlag,
|
||||
DisableReturnDataFlag,
|
||||
EVMInterpreterFlag,
|
||||
}
|
||||
app.Commands = []cli.Command{
|
||||
compileCommand,
|
||||
|
@@ -1,23 +0,0 @@
|
||||
{
|
||||
"root": "f4157bb27bcb1d1a63001434a249a80948f2e9fe1f53d551244c1dae826b5b23",
|
||||
"accounts": {
|
||||
"0x8a8eafb1cf62bfbeb1741769dae1a9dd47996192": {
|
||||
"balance": "4276951709",
|
||||
"nonce": 1,
|
||||
"root": "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
|
||||
"codeHash": "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"
|
||||
},
|
||||
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": {
|
||||
"balance": "6916764286133345652",
|
||||
"nonce": 172,
|
||||
"root": "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
|
||||
"codeHash": "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"
|
||||
},
|
||||
"0xc94f5374fce5edbc8e2a8697c15331677e6ebf0b": {
|
||||
"balance": "42500",
|
||||
"nonce": 0,
|
||||
"root": "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
|
||||
"codeHash": "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"
|
||||
}
|
||||
}
|
||||
}
|
@@ -211,9 +211,8 @@ func runCmd(ctx *cli.Context) error {
|
||||
Coinbase: genesisConfig.Coinbase,
|
||||
BlockNumber: new(big.Int).SetUint64(genesisConfig.Number),
|
||||
EVMConfig: vm.Config{
|
||||
Tracer: tracer,
|
||||
Debug: ctx.GlobalBool(DebugFlag.Name) || ctx.GlobalBool(MachineFlag.Name),
|
||||
EVMInterpreter: ctx.GlobalString(EVMInterpreterFlag.Name),
|
||||
Tracer: tracer,
|
||||
Debug: ctx.GlobalBool(DebugFlag.Name) || ctx.GlobalBool(MachineFlag.Name),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -270,7 +269,7 @@ func runCmd(ctx *cli.Context) error {
|
||||
if ctx.GlobalBool(DumpFlag.Name) {
|
||||
statedb.Commit(true)
|
||||
statedb.IntermediateRoot(true)
|
||||
fmt.Println(string(statedb.Dump(false, false, true)))
|
||||
fmt.Println(string(statedb.Dump(nil)))
|
||||
}
|
||||
|
||||
if memProfilePath := ctx.GlobalString(MemProfileFlag.Name); memProfilePath != "" {
|
||||
|
@@ -98,16 +98,16 @@ func stateTestCmd(ctx *cli.Context) error {
|
||||
for _, st := range test.Subtests() {
|
||||
// Run the test and aggregate the result
|
||||
result := &StatetestResult{Name: key, Fork: st.Fork, Pass: true}
|
||||
_, state, err := test.Run(st, cfg, false)
|
||||
_, s, err := test.Run(st, cfg, false)
|
||||
// print state root for evmlab tracing
|
||||
if ctx.GlobalBool(MachineFlag.Name) && state != nil {
|
||||
fmt.Fprintf(os.Stderr, "{\"stateRoot\": \"%x\"}\n", state.IntermediateRoot(false))
|
||||
if ctx.GlobalBool(MachineFlag.Name) && s != nil {
|
||||
fmt.Fprintf(os.Stderr, "{\"stateRoot\": \"%x\"}\n", s.IntermediateRoot(false))
|
||||
}
|
||||
if err != nil {
|
||||
// Test failed, mark as so and dump any state to aid debugging
|
||||
result.Pass, result.Error = false, err.Error()
|
||||
if ctx.GlobalBool(DumpFlag.Name) && state != nil {
|
||||
dump := state.RawDump(false, false, true)
|
||||
if ctx.GlobalBool(DumpFlag.Name) && s != nil {
|
||||
dump := s.RawDump(nil)
|
||||
result.State = &dump
|
||||
}
|
||||
}
|
||||
|
23
cmd/evm/testdata/10/alloc.json
vendored
Normal file
23
cmd/evm/testdata/10/alloc.json
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"0x1111111111111111111111111111111111111111" : {
|
||||
"balance" : "0x010000000000",
|
||||
"code" : "0xfe",
|
||||
"nonce" : "0x01",
|
||||
"storage" : {
|
||||
}
|
||||
},
|
||||
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
|
||||
"balance" : "0x010000000000",
|
||||
"code" : "0x",
|
||||
"nonce" : "0x01",
|
||||
"storage" : {
|
||||
}
|
||||
},
|
||||
"0xd02d72e067e77158444ef2020ff2d325f929b363" : {
|
||||
"balance" : "0x01000000000000",
|
||||
"code" : "0x",
|
||||
"nonce" : "0x01",
|
||||
"storage" : {
|
||||
}
|
||||
}
|
||||
}
|
12
cmd/evm/testdata/10/env.json
vendored
Normal file
12
cmd/evm/testdata/10/env.json
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"currentCoinbase" : "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
"currentDifficulty" : "0x020000",
|
||||
"currentNumber" : "0x01",
|
||||
"currentTimestamp" : "0x079e",
|
||||
"previousHash" : "0xcb23ee65a163121f640673b41788ee94633941405f95009999b502eedfbbfd4f",
|
||||
"currentGasLimit" : "0x40000000",
|
||||
"currentBaseFee" : "0x036b",
|
||||
"blockHashes" : {
|
||||
"0" : "0xcb23ee65a163121f640673b41788ee94633941405f95009999b502eedfbbfd4f"
|
||||
}
|
||||
}
|
79
cmd/evm/testdata/10/readme.md
vendored
Normal file
79
cmd/evm/testdata/10/readme.md
vendored
Normal file
@@ -0,0 +1,79 @@
|
||||
## EIP-1559 testing
|
||||
|
||||
This test contains testcases for EIP-1559, which were reported by Ori as misbehaving.
|
||||
|
||||
```
|
||||
[user@work evm]$ dir=./testdata/10 && ./evm t8n --state.fork=London --input.alloc=$dir/alloc.json --input.txs=$dir/txs.json --input.env=$dir/env.json --output.alloc=stdout --output.result=stdout 2>&1
|
||||
INFO [05-09|22:11:59.436] rejected tx index=3 hash=db07bf..ede1e8 from=0xd02d72E067e77158444ef2020Ff2d325f929B363 error="gas limit reached"
|
||||
```
|
||||
Output:
|
||||
```json
|
||||
{
|
||||
"alloc": {
|
||||
"0x1111111111111111111111111111111111111111": {
|
||||
"code": "0xfe",
|
||||
"balance": "0x10000000000",
|
||||
"nonce": "0x1"
|
||||
},
|
||||
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": {
|
||||
"balance": "0x10000000000",
|
||||
"nonce": "0x1"
|
||||
},
|
||||
"0xd02d72e067e77158444ef2020ff2d325f929b363": {
|
||||
"balance": "0xff5beffffc95",
|
||||
"nonce": "0x4"
|
||||
}
|
||||
},
|
||||
"result": {
|
||||
"stateRoot": "0xf91a7ec08e4bfea88719aab34deabb000c86902360532b52afa9599d41f2bb8b",
|
||||
"txRoot": "0xda925f2306a52fa24c15d5cd212d736ee016415fd8dd0c45fd368de7917d64bb",
|
||||
"receiptRoot": "0x439a25f7fc424c10fb1f89800e4aa1df74156b137239d9ac3eaa7c911c353cd5",
|
||||
"logsHash": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
|
||||
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
|
||||
"receipts": [
|
||||
{
|
||||
"type": "0x2",
|
||||
"root": "0x",
|
||||
"status": "0x0",
|
||||
"cumulativeGasUsed": "0x10000001",
|
||||
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
|
||||
"logs": null,
|
||||
"transactionHash": "0x88980f6efcc5358d9c359663e7b9414722d430497637340ea056b076bc206701",
|
||||
"contractAddress": "0x0000000000000000000000000000000000000000",
|
||||
"gasUsed": "0x10000001",
|
||||
"blockHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"transactionIndex": "0x0"
|
||||
},
|
||||
{
|
||||
"type": "0x2",
|
||||
"root": "0x",
|
||||
"status": "0x0",
|
||||
"cumulativeGasUsed": "0x20000001",
|
||||
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
|
||||
"logs": null,
|
||||
"transactionHash": "0xd7bf3886f4e2aef74d525ae072c680f3846f550254401b67cbfda4a233757582",
|
||||
"contractAddress": "0x0000000000000000000000000000000000000000",
|
||||
"gasUsed": "0x10000000",
|
||||
"blockHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"transactionIndex": "0x1"
|
||||
},
|
||||
{
|
||||
"type": "0x2",
|
||||
"root": "0x",
|
||||
"status": "0x0",
|
||||
"cumulativeGasUsed": "0x30000001",
|
||||
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
|
||||
"logs": null,
|
||||
"transactionHash": "0x50308296760f01f1eeec7500e9e73cad67469249b1f59e9a9f55e6625a4923db",
|
||||
"contractAddress": "0x0000000000000000000000000000000000000000",
|
||||
"gasUsed": "0x10000000",
|
||||
"blockHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"transactionIndex": "0x2"
|
||||
}
|
||||
],
|
||||
"rejected": [
|
||||
3
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
70
cmd/evm/testdata/10/txs.json
vendored
Normal file
70
cmd/evm/testdata/10/txs.json
vendored
Normal file
@@ -0,0 +1,70 @@
|
||||
[
|
||||
{
|
||||
"input" : "0x",
|
||||
"gas" : "0x10000001",
|
||||
"nonce" : "0x1",
|
||||
"to" : "0x1111111111111111111111111111111111111111",
|
||||
"value" : "0x0",
|
||||
"v" : "0x0",
|
||||
"r" : "0x7a45f00bcde9036b026cdf1628b023cd8a31a95c62b5e4dbbee2fa7debe668fb",
|
||||
"s" : "0x3cc9d6f2cd00a045b0263f2d6dad7d60938d5d13d061af4969f95928aa934d4a",
|
||||
"secretKey" : "0x41f6e321b31e72173f8ff2e292359e1862f24fba42fe6f97efaf641980eff298",
|
||||
"chainId" : "0x1",
|
||||
"type" : "0x2",
|
||||
"maxFeePerGas" : "0xfa0",
|
||||
"maxPriorityFeePerGas" : "0x0",
|
||||
"accessList" : [
|
||||
]
|
||||
},
|
||||
{
|
||||
"input" : "0x",
|
||||
"gas" : "0x10000000",
|
||||
"nonce" : "0x2",
|
||||
"to" : "0x1111111111111111111111111111111111111111",
|
||||
"value" : "0x0",
|
||||
"v" : "0x0",
|
||||
"r" : "0x4c564b94b0281a8210eeec2dd1fe2e16ff1c1903a8c3a1078d735d7f8208b2af",
|
||||
"s" : "0x56432b2593e6de95db1cb997b7385217aca03f1615327e231734446b39f266d",
|
||||
"secretKey" : "0x41f6e321b31e72173f8ff2e292359e1862f24fba42fe6f97efaf641980eff298",
|
||||
"chainId" : "0x1",
|
||||
"type" : "0x2",
|
||||
"maxFeePerGas" : "0xfa0",
|
||||
"maxPriorityFeePerGas" : "0x0",
|
||||
"accessList" : [
|
||||
]
|
||||
},
|
||||
{
|
||||
"input" : "0x",
|
||||
"gas" : "0x10000000",
|
||||
"nonce" : "0x3",
|
||||
"to" : "0x1111111111111111111111111111111111111111",
|
||||
"value" : "0x0",
|
||||
"v" : "0x0",
|
||||
"r" : "0x2ed2ef52f924f59d4a21e1f2a50d3b1109303ce5e32334a7ece9b46f4fbc2a57",
|
||||
"s" : "0x2980257129cbd3da987226f323d50ba3975a834d165e0681f991b75615605c44",
|
||||
"secretKey" : "0x41f6e321b31e72173f8ff2e292359e1862f24fba42fe6f97efaf641980eff298",
|
||||
"chainId" : "0x1",
|
||||
"type" : "0x2",
|
||||
"maxFeePerGas" : "0xfa0",
|
||||
"maxPriorityFeePerGas" : "0x0",
|
||||
"accessList" : [
|
||||
]
|
||||
},
|
||||
{
|
||||
"input" : "0x",
|
||||
"gas" : "0x10000000",
|
||||
"nonce" : "0x4",
|
||||
"to" : "0x1111111111111111111111111111111111111111",
|
||||
"value" : "0x0",
|
||||
"v" : "0x0",
|
||||
"r" : "0x5df7d7f8f8e15b36fc9f189cacb625040fad10398d08fc90812595922a2c49b2",
|
||||
"s" : "0x565fc1803f77a84d754ffe3c5363ab54a8d93a06ea1bb9d4c73c73a282b35917",
|
||||
"secretKey" : "0x41f6e321b31e72173f8ff2e292359e1862f24fba42fe6f97efaf641980eff298",
|
||||
"chainId" : "0x1",
|
||||
"type" : "0x2",
|
||||
"maxFeePerGas" : "0xfa0",
|
||||
"maxPriorityFeePerGas" : "0x0",
|
||||
"accessList" : [
|
||||
]
|
||||
}
|
||||
]
|
25
cmd/evm/testdata/11/alloc.json
vendored
Normal file
25
cmd/evm/testdata/11/alloc.json
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : {
|
||||
"balance" : "0x0de0b6b3a7640000",
|
||||
"code" : "0x61ffff5060046000f3",
|
||||
"nonce" : "0x01",
|
||||
"storage" : {
|
||||
}
|
||||
},
|
||||
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
|
||||
"balance" : "0x0de0b6b3a7640000",
|
||||
"code" : "0x",
|
||||
"nonce" : "0x00",
|
||||
"storage" : {
|
||||
"0x00" : "0x00"
|
||||
}
|
||||
},
|
||||
"0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
|
||||
"balance" : "0x00",
|
||||
"code" : "0x6001600055",
|
||||
"nonce" : "0x00",
|
||||
"storage" : {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
12
cmd/evm/testdata/11/env.json
vendored
Normal file
12
cmd/evm/testdata/11/env.json
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"currentCoinbase" : "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
"currentDifficulty" : "0x020000",
|
||||
"currentNumber" : "0x01",
|
||||
"currentTimestamp" : "0x03e8",
|
||||
"previousHash" : "0xfda4419b3660e99f37e536dae1ab081c180136bb38c837a93e93d9aab58553b2",
|
||||
"currentGasLimit" : "0x0f4240",
|
||||
"blockHashes" : {
|
||||
"0" : "0xfda4419b3660e99f37e536dae1ab081c180136bb38c837a93e93d9aab58553b2"
|
||||
}
|
||||
}
|
||||
|
13
cmd/evm/testdata/11/readme.md
vendored
Normal file
13
cmd/evm/testdata/11/readme.md
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
## Test missing basefee
|
||||
|
||||
In this test, the `currentBaseFee` is missing from the env portion.
|
||||
On a live blockchain, the basefee is present in the header, and verified as part of header validation.
|
||||
|
||||
In `evm t8n`, we don't have blocks, so it needs to be added in the `env`instead.
|
||||
|
||||
When it's missing, an error is expected.
|
||||
|
||||
```
|
||||
dir=./testdata/11 && ./evm t8n --state.fork=London --input.alloc=$dir/alloc.json --input.txs=$dir/txs.json --input.env=$dir/env.json --output.alloc=stdout --output.result=stdout 2>&1>/dev/null
|
||||
ERROR(3): EIP-1559 config but missing 'currentBaseFee' in env section
|
||||
```
|
14
cmd/evm/testdata/11/txs.json
vendored
Normal file
14
cmd/evm/testdata/11/txs.json
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
[
|
||||
{
|
||||
"input" : "0x38600060013960015160005560006000f3",
|
||||
"gas" : "0x61a80",
|
||||
"gasPrice" : "0x1",
|
||||
"nonce" : "0x0",
|
||||
"value" : "0x186a0",
|
||||
"v" : "0x1c",
|
||||
"r" : "0x2e1391fd903387f1cc2b51df083805fb4bbb0d4710a2cdf4a044d191ff7be63e",
|
||||
"s" : "0x7f10a933c42ab74927db02b1db009e923d9d2ab24ac24d63c399f2fe5d9c9b22",
|
||||
"secretKey" : "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8"
|
||||
}
|
||||
]
|
||||
|
11
cmd/evm/testdata/12/alloc.json
vendored
Normal file
11
cmd/evm/testdata/12/alloc.json
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
|
||||
"balance" : "84000000",
|
||||
"code" : "0x",
|
||||
"nonce" : "0x00",
|
||||
"storage" : {
|
||||
"0x00" : "0x00"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
10
cmd/evm/testdata/12/env.json
vendored
Normal file
10
cmd/evm/testdata/12/env.json
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"currentCoinbase" : "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
"currentDifficulty" : "0x020000",
|
||||
"currentNumber" : "0x01",
|
||||
"currentTimestamp" : "0x03e8",
|
||||
"previousHash" : "0xfda4419b3660e99f37e536dae1ab081c180136bb38c837a93e93d9aab58553b2",
|
||||
"currentGasLimit" : "0x0f4240",
|
||||
"currentBaseFee" : "0x20"
|
||||
}
|
||||
|
40
cmd/evm/testdata/12/readme.md
vendored
Normal file
40
cmd/evm/testdata/12/readme.md
vendored
Normal file
@@ -0,0 +1,40 @@
|
||||
## Test 1559 balance + gasCap
|
||||
|
||||
This test contains an EIP-1559 consensus issue which happened on Ropsten, where
|
||||
`geth` did not properly account for the value transfer while doing the check on `max_fee_per_gas * gas_limit`.
|
||||
|
||||
Before the issue was fixed, this invocation allowed the transaction to pass into a block:
|
||||
```
|
||||
dir=./testdata/12 && ./evm t8n --state.fork=London --input.alloc=$dir/alloc.json --input.txs=$dir/txs.json --input.env=$dir/env.json --output.alloc=stdout --output.result=stdout
|
||||
```
|
||||
|
||||
With the fix applied, the result is:
|
||||
```
|
||||
dir=./testdata/12 && ./evm t8n --state.fork=London --input.alloc=$dir/alloc.json --input.txs=$dir/txs.json --input.env=$dir/env.json --output.alloc=stdout --output.result=stdout
|
||||
INFO [07-21|19:03:50.276] rejected tx index=0 hash=ccc996..d83435 from=0xa94f5374Fce5edBC8E2a8697C15331677e6EbF0B error="insufficient funds for gas * price + value: address 0xa94f5374Fce5edBC8E2a8697C15331677e6EbF0B have 84000000 want 84000032"
|
||||
INFO [07-21|19:03:50.276] Trie dumping started root=e05f81..6597a5
|
||||
INFO [07-21|19:03:50.276] Trie dumping complete accounts=1 elapsed="39.549µs"
|
||||
{
|
||||
"alloc": {
|
||||
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": {
|
||||
"balance": "0x501bd00"
|
||||
}
|
||||
},
|
||||
"result": {
|
||||
"stateRoot": "0xe05f81f8244a76503ceec6f88abfcd03047a612a1001217f37d30984536597a5",
|
||||
"txRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
|
||||
"receiptRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
|
||||
"logsHash": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
|
||||
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
|
||||
"receipts": [],
|
||||
"rejected": [
|
||||
{
|
||||
"index": 0,
|
||||
"error": "insufficient funds for gas * price + value: address 0xa94f5374Fce5edBC8E2a8697C15331677e6EbF0B have 84000000 want 84000032"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The transaction is rejected.
|
20
cmd/evm/testdata/12/txs.json
vendored
Normal file
20
cmd/evm/testdata/12/txs.json
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
[
|
||||
{
|
||||
"input" : "0x",
|
||||
"gas" : "0x5208",
|
||||
"nonce" : "0x0",
|
||||
"to" : "0x1111111111111111111111111111111111111111",
|
||||
"value" : "0x20",
|
||||
"v" : "0x0",
|
||||
"r" : "0x0",
|
||||
"s" : "0x0",
|
||||
"secretKey" : "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8",
|
||||
"chainId" : "0x1",
|
||||
"type" : "0x2",
|
||||
"maxFeePerGas" : "0xfa0",
|
||||
"maxPriorityFeePerGas" : "0x20",
|
||||
"accessList" : [
|
||||
]
|
||||
}
|
||||
]
|
||||
|
23
cmd/evm/testdata/13/alloc.json
vendored
Normal file
23
cmd/evm/testdata/13/alloc.json
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"0x1111111111111111111111111111111111111111" : {
|
||||
"balance" : "0x010000000000",
|
||||
"code" : "0xfe",
|
||||
"nonce" : "0x01",
|
||||
"storage" : {
|
||||
}
|
||||
},
|
||||
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
|
||||
"balance" : "0x010000000000",
|
||||
"code" : "0x",
|
||||
"nonce" : "0x01",
|
||||
"storage" : {
|
||||
}
|
||||
},
|
||||
"0xd02d72e067e77158444ef2020ff2d325f929b363" : {
|
||||
"balance" : "0x01000000000000",
|
||||
"code" : "0x",
|
||||
"nonce" : "0x01",
|
||||
"storage" : {
|
||||
}
|
||||
}
|
||||
}
|
12
cmd/evm/testdata/13/env.json
vendored
Normal file
12
cmd/evm/testdata/13/env.json
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"currentCoinbase" : "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
"currentDifficulty" : "0x020000",
|
||||
"currentNumber" : "0x01",
|
||||
"currentTimestamp" : "0x079e",
|
||||
"previousHash" : "0xcb23ee65a163121f640673b41788ee94633941405f95009999b502eedfbbfd4f",
|
||||
"currentGasLimit" : "0x40000000",
|
||||
"currentBaseFee" : "0x036b",
|
||||
"blockHashes" : {
|
||||
"0" : "0xcb23ee65a163121f640673b41788ee94633941405f95009999b502eedfbbfd4f"
|
||||
}
|
||||
}
|
4
cmd/evm/testdata/13/readme.md
vendored
Normal file
4
cmd/evm/testdata/13/readme.md
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
## Input transactions in RLP form
|
||||
|
||||
This testdata folder is used to examplify how transaction input can be provided in rlp form.
|
||||
Please see the README in `evm` folder for how this is performed.
|
34
cmd/evm/testdata/13/txs.json
vendored
Normal file
34
cmd/evm/testdata/13/txs.json
vendored
Normal file
@@ -0,0 +1,34 @@
|
||||
[
|
||||
{
|
||||
"input" : "0x",
|
||||
"gas" : "0x84d0",
|
||||
"nonce" : "0x1",
|
||||
"to" : "0x1111111111111111111111111111111111111111",
|
||||
"value" : "0x0",
|
||||
"v" : "0x0",
|
||||
"r" : "0x0",
|
||||
"s" : "0x0",
|
||||
"secretKey" : "0x41f6e321b31e72173f8ff2e292359e1862f24fba42fe6f97efaf641980eff298",
|
||||
"chainId" : "0x1",
|
||||
"type" : "0x2",
|
||||
"maxFeePerGas" : "0xfa0",
|
||||
"maxPriorityFeePerGas" : "0x0",
|
||||
"accessList" : []
|
||||
},
|
||||
{
|
||||
"input" : "0x",
|
||||
"gas" : "0x84d0",
|
||||
"nonce" : "0x2",
|
||||
"to" : "0x1111111111111111111111111111111111111111",
|
||||
"value" : "0x0",
|
||||
"v" : "0x0",
|
||||
"r" : "0x0",
|
||||
"s" : "0x0",
|
||||
"secretKey" : "0x41f6e321b31e72173f8ff2e292359e1862f24fba42fe6f97efaf641980eff298",
|
||||
"chainId" : "0x1",
|
||||
"type" : "0x2",
|
||||
"maxFeePerGas" : "0xfa0",
|
||||
"maxPriorityFeePerGas" : "0x0",
|
||||
"accessList" : []
|
||||
}
|
||||
]
|
11
cmd/evm/testdata/8/alloc.json
vendored
Normal file
11
cmd/evm/testdata/8/alloc.json
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"0x000000000000000000000000000000000000aaaa": {
|
||||
"balance": "0x03",
|
||||
"code": "0x5854505854",
|
||||
"nonce": "0x1"
|
||||
},
|
||||
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": {
|
||||
"balance": "0x100000",
|
||||
"nonce": "0x00"
|
||||
}
|
||||
}
|
7
cmd/evm/testdata/8/env.json
vendored
Normal file
7
cmd/evm/testdata/8/env.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"currentCoinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
"currentDifficulty": "0x20000",
|
||||
"currentGasLimit": "0x1000000000",
|
||||
"currentNumber": "0x1000000",
|
||||
"currentTimestamp": "0x04"
|
||||
}
|
63
cmd/evm/testdata/8/readme.md
vendored
Normal file
63
cmd/evm/testdata/8/readme.md
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
## EIP-2930 testing
|
||||
|
||||
This test contains testcases for EIP-2930, which uses transactions with access lists.
|
||||
|
||||
### Prestate
|
||||
|
||||
The alloc portion contains one contract (`0x000000000000000000000000000000000000aaaa`), containing the
|
||||
following code: `0x5854505854`: `PC ;SLOAD; POP; PC; SLOAD`.
|
||||
|
||||
Essentialy, this contract does `SLOAD(0)` and `SLOAD(3)`.
|
||||
|
||||
The alloc also contains some funds on `0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b`.
|
||||
|
||||
## Transactions
|
||||
|
||||
There are three transactions, each invokes the contract above.
|
||||
|
||||
1. ACL-transaction, which contains some non-used slots
|
||||
2. Regular transaction
|
||||
3. ACL-transaction, which contains the slots `1` and `3` in `0x000000000000000000000000000000000000aaaa`
|
||||
|
||||
## Execution
|
||||
|
||||
Running it yields:
|
||||
```
|
||||
dir=./testdata/8 && ./evm t8n --state.fork=Berlin --input.alloc=$dir/alloc.json --input.txs=$dir/txs.json --input.env=$dir/env.json --trace && cat trace-* | grep SLOAD
|
||||
{"pc":1,"op":84,"gas":"0x484be","gasCost":"0x834","memory":"0x","memSize":0,"stack":["0x0"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"SLOAD","error":""}
|
||||
{"pc":4,"op":84,"gas":"0x47c86","gasCost":"0x834","memory":"0x","memSize":0,"stack":["0x3"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"SLOAD","error":""}
|
||||
{"pc":1,"op":84,"gas":"0x49cf6","gasCost":"0x834","memory":"0x","memSize":0,"stack":["0x0"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"SLOAD","error":""}
|
||||
{"pc":4,"op":84,"gas":"0x494be","gasCost":"0x834","memory":"0x","memSize":0,"stack":["0x3"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"SLOAD","error":""}
|
||||
{"pc":1,"op":84,"gas":"0x484be","gasCost":"0x64","memory":"0x","memSize":0,"stack":["0x0"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"SLOAD","error":""}
|
||||
{"pc":4,"op":84,"gas":"0x48456","gasCost":"0x64","memory":"0x","memSize":0,"stack":["0x3"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"SLOAD","error":""}
|
||||
|
||||
```
|
||||
|
||||
Simlarly, we can provide the input transactions via `stdin` instead of as file:
|
||||
|
||||
```
|
||||
dir=./testdata/8 \
|
||||
&& cat $dir/txs.json | jq "{txs: .}" \
|
||||
| ./evm t8n --state.fork=Berlin \
|
||||
--input.alloc=$dir/alloc.json \
|
||||
--input.txs=stdin \
|
||||
--input.env=$dir/env.json \
|
||||
--trace \
|
||||
&& cat trace-* | grep SLOAD
|
||||
|
||||
{"pc":1,"op":84,"gas":"0x484be","gasCost":"0x834","memory":"0x","memSize":0,"stack":["0x0"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"SLOAD","error":""}
|
||||
{"pc":4,"op":84,"gas":"0x47c86","gasCost":"0x834","memory":"0x","memSize":0,"stack":["0x3"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"SLOAD","error":""}
|
||||
{"pc":1,"op":84,"gas":"0x49cf6","gasCost":"0x834","memory":"0x","memSize":0,"stack":["0x0"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"SLOAD","error":""}
|
||||
{"pc":4,"op":84,"gas":"0x494be","gasCost":"0x834","memory":"0x","memSize":0,"stack":["0x3"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"SLOAD","error":""}
|
||||
{"pc":1,"op":84,"gas":"0x484be","gasCost":"0x64","memory":"0x","memSize":0,"stack":["0x0"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"SLOAD","error":""}
|
||||
{"pc":4,"op":84,"gas":"0x48456","gasCost":"0x64","memory":"0x","memSize":0,"stack":["0x3"],"returnStack":[],"returnData":"0x","depth":1,"refund":0,"opName":"SLOAD","error":""}
|
||||
```
|
||||
|
||||
If we try to execute it on older rules:
|
||||
```
|
||||
dir=./testdata/8 && ./evm t8n --state.fork=Istanbul --input.alloc=$dir/alloc.json --input.txs=$dir/txs.json --input.env=$dir/env.json
|
||||
INFO [01-21|23:21:51.265] rejected tx index=0 hash=d2818d..6ab3da error="tx type not supported"
|
||||
INFO [01-21|23:21:51.265] rejected tx index=1 hash=26ea00..81c01b from=0xa94f5374Fce5edBC8E2a8697C15331677e6EbF0B error="nonce too high: address 0xa94f5374Fce5edBC8E2a8697C15331677e6EbF0B, tx: 1 state: 0"
|
||||
INFO [01-21|23:21:51.265] rejected tx index=2 hash=698d01..369cee error="tx type not supported"
|
||||
```
|
||||
Number `1` and `3` are not applicable, and therefore number `2` has wrong nonce.
|
58
cmd/evm/testdata/8/txs.json
vendored
Normal file
58
cmd/evm/testdata/8/txs.json
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
[
|
||||
{
|
||||
"gas": "0x4ef00",
|
||||
"gasPrice": "0x1",
|
||||
"chainId": "0x1",
|
||||
"input": "0x",
|
||||
"nonce": "0x0",
|
||||
"to": "0x000000000000000000000000000000000000aaaa",
|
||||
"value": "0x1",
|
||||
"type" : "0x1",
|
||||
"accessList": [
|
||||
{"address": "0x0000000000000000000000000000000000000000",
|
||||
"storageKeys": [
|
||||
"0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"0x0000000000000000000000000000000000000000000000000000000000000000"
|
||||
]
|
||||
}
|
||||
],
|
||||
"v": "0x0",
|
||||
"r": "0x0",
|
||||
"s": "0x0",
|
||||
"secretKey": "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8"
|
||||
},
|
||||
{
|
||||
"gas": "0x4ef00",
|
||||
"gasPrice": "0x1",
|
||||
"input": "0x",
|
||||
"nonce": "0x1",
|
||||
"to": "0x000000000000000000000000000000000000aaaa",
|
||||
"value": "0x2",
|
||||
"v": "0x0",
|
||||
"r": "0x0",
|
||||
"s": "0x0",
|
||||
"secretKey": "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8"
|
||||
},
|
||||
{
|
||||
"gas": "0x4ef00",
|
||||
"gasPrice": "0x1",
|
||||
"chainId": "0x1",
|
||||
"input": "0x",
|
||||
"nonce": "0x2",
|
||||
"to": "0x000000000000000000000000000000000000aaaa",
|
||||
"value": "0x1",
|
||||
"type" : "0x1",
|
||||
"accessList": [
|
||||
{"address": "0x000000000000000000000000000000000000aaaa",
|
||||
"storageKeys": [
|
||||
"0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"0x0000000000000000000000000000000000000000000000000000000000000003"
|
||||
]
|
||||
}
|
||||
],
|
||||
"v": "0x0",
|
||||
"r": "0x0",
|
||||
"s": "0x0",
|
||||
"secretKey": "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8"
|
||||
}
|
||||
]
|
11
cmd/evm/testdata/9/alloc.json
vendored
Normal file
11
cmd/evm/testdata/9/alloc.json
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"0x000000000000000000000000000000000000aaaa": {
|
||||
"balance": "0x03",
|
||||
"code": "0x58585454",
|
||||
"nonce": "0x1"
|
||||
},
|
||||
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": {
|
||||
"balance": "0x100000000000000",
|
||||
"nonce": "0x00"
|
||||
}
|
||||
}
|
8
cmd/evm/testdata/9/env.json
vendored
Normal file
8
cmd/evm/testdata/9/env.json
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"currentCoinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
"currentDifficulty": "0x20000",
|
||||
"currentGasTarget": "0x1000000000",
|
||||
"currentBaseFee": "0x3B9ACA00",
|
||||
"currentNumber": "0x1000000",
|
||||
"currentTimestamp": "0x04"
|
||||
}
|
75
cmd/evm/testdata/9/readme.md
vendored
Normal file
75
cmd/evm/testdata/9/readme.md
vendored
Normal file
@@ -0,0 +1,75 @@
|
||||
## EIP-1559 testing
|
||||
|
||||
This test contains testcases for EIP-1559, which uses an new transaction type and has a new block parameter.
|
||||
|
||||
### Prestate
|
||||
|
||||
The alloc portion contains one contract (`0x000000000000000000000000000000000000aaaa`), containing the
|
||||
following code: `0x58585454`: `PC; PC; SLOAD; SLOAD`.
|
||||
|
||||
Essentialy, this contract does `SLOAD(0)` and `SLOAD(1)`.
|
||||
|
||||
The alloc also contains some funds on `0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b`.
|
||||
|
||||
## Transactions
|
||||
|
||||
There are two transactions, each invokes the contract above.
|
||||
|
||||
1. EIP-1559 ACL-transaction, which contains the `0x0` slot for `0xaaaa`
|
||||
2. Legacy transaction
|
||||
|
||||
## Execution
|
||||
|
||||
Running it yields:
|
||||
```
|
||||
$ dir=./testdata/9 && ./evm t8n --state.fork=London --input.alloc=$dir/alloc.json --input.txs=$dir/txs.json --input.env=$dir/env.json --trace && cat trace-* | grep SLOAD
|
||||
{"pc":2,"op":84,"gas":"0x48c28","gasCost":"0x834","memory":"0x","memSize":0,"stack":["0x0","0x1"],"returnStack":null,"returnD
|
||||
ata":"0x","depth":1,"refund":0,"opName":"SLOAD","error":""}
|
||||
{"pc":3,"op":84,"gas":"0x483f4","gasCost":"0x64","memory":"0x","memSize":0,"stack":["0x0","0x0"],"returnStack":null,"returnDa
|
||||
ta":"0x","depth":1,"refund":0,"opName":"SLOAD","error":""}
|
||||
{"pc":2,"op":84,"gas":"0x49cf4","gasCost":"0x834","memory":"0x","memSize":0,"stack":["0x0","0x1"],"returnStack":null,"returnD
|
||||
ata":"0x","depth":1,"refund":0,"opName":"SLOAD","error":""}
|
||||
{"pc":3,"op":84,"gas":"0x494c0","gasCost":"0x834","memory":"0x","memSize":0,"stack":["0x0","0x0"],"returnStack":null,"returnD
|
||||
ata":"0x","depth":1,"refund":0,"opName":"SLOAD","error":""}
|
||||
```
|
||||
|
||||
We can also get the post-alloc:
|
||||
```
|
||||
$ dir=./testdata/9 && ./evm t8n --state.fork=London --input.alloc=$dir/alloc.json --input.txs=$dir/txs.json --input.env=$dir/env.json --output.alloc=stdout
|
||||
{
|
||||
"alloc": {
|
||||
"0x000000000000000000000000000000000000aaaa": {
|
||||
"code": "0x58585454",
|
||||
"balance": "0x3",
|
||||
"nonce": "0x1"
|
||||
},
|
||||
"0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba": {
|
||||
"balance": "0xbfc02677a000"
|
||||
},
|
||||
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": {
|
||||
"balance": "0xff104fcfea7800",
|
||||
"nonce": "0x2"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If we try to execute it on older rules:
|
||||
```
|
||||
dir=./testdata/9 && ./evm t8n --state.fork=Berlin --input.alloc=$dir/alloc.json --input.txs=$dir/txs.json --input.env=$dir/env.json --output.alloc=stdout
|
||||
ERROR(10): Failed signing transactions: ERROR(10): Tx 0: failed to sign tx: transaction type not supported
|
||||
```
|
||||
|
||||
It fails, due to the `evm t8n` cannot sign them in with the given signer. We can bypass that, however,
|
||||
by feeding it presigned transactions, located in `txs_signed.json`.
|
||||
|
||||
```
|
||||
dir=./testdata/9 && ./evm t8n --state.fork=Berlin --input.alloc=$dir/alloc.json --input.txs=$dir/txs_signed.json --input.env=$dir/env.json
|
||||
INFO [05-07|12:28:42.072] rejected tx index=0 hash=b4821e..536819 error="transaction type not supported"
|
||||
INFO [05-07|12:28:42.072] rejected tx index=1 hash=a9c6c6..fa4036 from=0xa94f5374Fce5edBC8E2a8697C15331677e6EbF0B error="nonce too high: address 0xa94f5374Fce5edBC8E2a8697C15331677e6EbF0B, tx: 1 state: 0"
|
||||
INFO [05-07|12:28:42.073] Wrote file file=alloc.json
|
||||
INFO [05-07|12:28:42.073] Wrote file file=result.json
|
||||
```
|
||||
|
||||
Number `0` is not applicable, and therefore number `1` has wrong nonce, and both are rejected.
|
||||
|
37
cmd/evm/testdata/9/txs.json
vendored
Normal file
37
cmd/evm/testdata/9/txs.json
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
[
|
||||
{
|
||||
"gas": "0x4ef00",
|
||||
"maxPriorityFeePerGas": "0x2",
|
||||
"maxFeePerGas": "0x12A05F200",
|
||||
"chainId": "0x1",
|
||||
"input": "0x",
|
||||
"nonce": "0x0",
|
||||
"to": "0x000000000000000000000000000000000000aaaa",
|
||||
"value": "0x0",
|
||||
"type" : "0x2",
|
||||
"accessList": [
|
||||
{"address": "0x000000000000000000000000000000000000aaaa",
|
||||
"storageKeys": [
|
||||
"0x0000000000000000000000000000000000000000000000000000000000000000"
|
||||
]
|
||||
}
|
||||
],
|
||||
"v": "0x0",
|
||||
"r": "0x0",
|
||||
"s": "0x0",
|
||||
"secretKey": "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8"
|
||||
},
|
||||
{
|
||||
"gas": "0x4ef00",
|
||||
"gasPrice": "0x12A05F200",
|
||||
"chainId": "0x1",
|
||||
"input": "0x",
|
||||
"nonce": "0x1",
|
||||
"to": "0x000000000000000000000000000000000000aaaa",
|
||||
"value": "0x0",
|
||||
"v": "0x0",
|
||||
"r": "0x0",
|
||||
"s": "0x0",
|
||||
"secretKey": "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8"
|
||||
}
|
||||
]
|
@@ -11,6 +11,8 @@ function showjson(){
|
||||
function demo(){
|
||||
echo "$ticks"
|
||||
echo "$1"
|
||||
$1
|
||||
echo ""
|
||||
echo "$ticks"
|
||||
echo ""
|
||||
}
|
||||
@@ -152,9 +154,7 @@ echo ""
|
||||
echo "The \`BLOCKHASH\` opcode requires blockhashes to be provided by the caller, inside the \`env\`."
|
||||
echo "If a required blockhash is not provided, the exit code should be \`4\`:"
|
||||
echo "Example where blockhashes are provided: "
|
||||
cmd="./evm t8n --input.alloc=./testdata/3/alloc.json --input.txs=./testdata/3/txs.json --input.env=./testdata/3/env.json --trace"
|
||||
tick && echo $cmd && tick
|
||||
$cmd 2>&1 >/dev/null
|
||||
demo "./evm --verbosity=1 t8n --input.alloc=./testdata/3/alloc.json --input.txs=./testdata/3/txs.json --input.env=./testdata/3/env.json --trace"
|
||||
cmd="cat trace-0-0x72fadbef39cd251a437eea619cfeda752271a5faaaa2147df012e112159ffb81.jsonl | grep BLOCKHASH -C2"
|
||||
tick && echo $cmd && tick
|
||||
echo "$ticks"
|
||||
@@ -164,13 +164,11 @@ echo ""
|
||||
|
||||
echo "In this example, the caller has not provided the required blockhash:"
|
||||
cmd="./evm t8n --input.alloc=./testdata/4/alloc.json --input.txs=./testdata/4/txs.json --input.env=./testdata/4/env.json --trace"
|
||||
tick && echo $cmd && tick
|
||||
tick
|
||||
$cmd
|
||||
tick && echo $cmd && $cmd
|
||||
errc=$?
|
||||
tick
|
||||
echo "Error code: $errc"
|
||||
|
||||
echo ""
|
||||
|
||||
echo "### Chaining"
|
||||
echo ""
|
||||
@@ -189,3 +187,28 @@ echo ""
|
||||
echo "In order to meaningfully chain invocations, one would need to provide meaningful new \`env\`, otherwise the"
|
||||
echo "actual blocknumber (exposed to the EVM) would not increase."
|
||||
echo ""
|
||||
|
||||
echo "### Transactions in RLP form"
|
||||
echo ""
|
||||
echo "It is possible to provide already-signed transactions as input to, using an \`input.txs\` which ends with the \`rlp\` suffix."
|
||||
echo "The input format for RLP-form transactions is _identical_ to the _output_ format for block bodies. Therefore, it's fully possible"
|
||||
echo "to use the evm to go from \`json\` input to \`rlp\` input."
|
||||
echo ""
|
||||
echo "The following command takes **json** the transactions in \`./testdata/13/txs.json\` and signs them. After execution, they are output to \`signed_txs.rlp\`.:"
|
||||
demo "./evm t8n --state.fork=London --input.alloc=./testdata/13/alloc.json --input.txs=./testdata/13/txs.json --input.env=./testdata/13/env.json --output.result=alloc_jsontx.json --output.body=signed_txs.rlp"
|
||||
echo "The \`output.body\` is the rlp-list of transactions, encoded in hex and placed in a string a'la \`json\` encoding rules:"
|
||||
demo "cat signed_txs.rlp"
|
||||
echo "We can use \`rlpdump\` to check what the contents are: "
|
||||
echo "$ticks"
|
||||
echo "rlpdump -hex \$(cat signed_txs.rlp | jq -r )"
|
||||
rlpdump -hex $(cat signed_txs.rlp | jq -r )
|
||||
echo "$ticks"
|
||||
echo "Now, we can now use those (or any other already signed transactions), as input, like so: "
|
||||
demo "./evm t8n --state.fork=London --input.alloc=./testdata/13/alloc.json --input.txs=./signed_txs.rlp --input.env=./testdata/13/env.json --output.result=alloc_rlptx.json"
|
||||
|
||||
echo "You might have noticed that the results from these two invocations were stored in two separate files. "
|
||||
echo "And we can now finally check that they match."
|
||||
echo "$ticks"
|
||||
echo "cat alloc_jsontx.json | jq .stateRoot && cat alloc_rlptx.json | jq .stateRoot"
|
||||
cat alloc_jsontx.json | jq .stateRoot && cat alloc_rlptx.json | jq .stateRoot
|
||||
echo "$ticks"
|
||||
|
50
cmd/faucet/README.md
Normal file
50
cmd/faucet/README.md
Normal file
@@ -0,0 +1,50 @@
|
||||
# Faucet
|
||||
|
||||
The `faucet` is a simplistic web application with the goal of distributing small amounts of Ether in private and test networks.
|
||||
|
||||
Users need to post their Ethereum addresses to fund in a Twitter status update or public Facebook post and share the link to the faucet. The faucet will in turn deduplicate user requests and send the Ether. After a funding round, the faucet prevents the same user requesting again for a pre-configured amount of time, proportional to the amount of Ether requested.
|
||||
|
||||
## Operation
|
||||
|
||||
The `faucet` is a single binary app (everything included) with all configurations set via command line flags and a few files.
|
||||
|
||||
First thing's first, the `faucet` needs to connect to an Ethereum network, for which it needs the necessary genesis and network infos. Each of the following flags must be set:
|
||||
|
||||
- `--genesis` is a path to a file containin the network `genesis.json`
|
||||
- `--network` is the devp2p network id used during connection
|
||||
- `--bootnodes` is a list of `enode://` ids to join the network through
|
||||
|
||||
The `faucet` will use the `les` protocol to join the configured Ethereum network and will store its data in `$HOME/.faucet` (currently not configurable).
|
||||
|
||||
## Funding
|
||||
|
||||
To be able to distribute funds, the `faucet` needs access to an already funded Ethereum account. This can be configured via:
|
||||
|
||||
- `--account.json` is a path to the Ethereum account's JSON key file
|
||||
- `--account.pass` is a path to a text file with the decryption passphrase
|
||||
|
||||
The faucet is able to distribute various amounts of Ether in exchange for various timeouts. These can be configured via:
|
||||
|
||||
- `--faucet.amount` is the number of Ethers to send by default
|
||||
- `--faucet.minutes` is the time to wait before allowing a rerequest
|
||||
- `--faucet.tiers` is the funding tiers to support (x3 time, x2.5 funds)
|
||||
|
||||
## Sybil protection
|
||||
|
||||
To prevent the same user from exhausting funds in a loop, the `faucet` ties requests to social networks and captcha resolvers.
|
||||
|
||||
Captcha protection uses Google's invisible ReCaptcha, thus the `faucet` needs to run on a live domain. The domain needs to be registered in Google's systems to retrieve the captcha API token and secrets. After doing so, captcha protection may be enabled via:
|
||||
|
||||
- `--captcha.token` is the API token for ReCaptcha
|
||||
- `--captcha.secret` is the API secret for ReCaptcha
|
||||
|
||||
Sybil protection via Twitter requires an API key as of 15th December, 2020. To obtain it, a Twitter user must be upgraded to developer status and a new Twitter App deployed with it. The app's `Bearer` token is required by the faucet to retrieve tweet data:
|
||||
|
||||
- `--twitter.token` is the Bearer token for `v2` API access
|
||||
- `--twitter.token.v1` is the Bearer token for `v1` API access
|
||||
|
||||
Sybil protection via Facebook uses the website to directly download post data thus does not currently require an API configuration.
|
||||
|
||||
## Miscellaneous
|
||||
|
||||
Beside the above - mostly essential - CLI flags, there are a number that can be used to fine tune the `faucet`'s operation. Please see `faucet --help` for a full list.
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user