├── .gitignore
├── CONTRIBUTORS.md
├── Dockerfile
├── LICENSE
├── Makefile
├── README.md
├── argpool
├── argpool.go
├── bytes32pool.go
├── int16pool.go
├── int32pool.go
├── int64pool.go
├── int8pool.go
├── pool.go
├── stringpool.go
└── timestamppool.go
├── benchmarks
└── IndividuallyCappedCrowdsale
│ ├── contracts
│ ├── CapperRole.sol
│ ├── Crowdsale.sol
│ ├── ERC20.sol
│ ├── IERC20.sol
│ ├── IndividuallyCappedCrowdsale.sol
│ ├── Migrations.sol
│ ├── Roles.sol
│ ├── SafeERC20.sol
│ ├── SafeMath.sol
│ ├── SimpleToken.sol
│ └── StandardToken.sol
│ ├── migrations
│ ├── 1_initial_migration.js
│ └── 2_deploy_contracts.js
│ ├── test
│ ├── .placeholder
│ └── Crowdsale.test.js
│ └── truffle.js
├── build
├── env.sh
├── extract.js
├── extract.sh
├── ganache.py
└── patch
├── config
├── accounts.json
└── config.json
├── fuzzer
└── fuzzer.go
└── utils
├── accounts.go
├── args.go
├── backend.go
├── contracts.go
├── generator.go
├── heuristics.go
├── processor.go
├── snapshots.go
├── statistics.go
├── transactions.go
├── types.go
└── utils.go
/.gitignore:
--------------------------------------------------------------------------------
1 | build/bin
2 | build/gen
3 | vendor
4 | benchmarks/*/build
5 | *.prof
6 |
7 |
--------------------------------------------------------------------------------
/CONTRIBUTORS.md:
--------------------------------------------------------------------------------
1 | # Developers' credit:
2 |
3 | - Nodar Ambroladze
4 | - Dr. Hubert Ritzdorf
5 | - Petar Ivanov
6 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM ubuntu:18.04
2 |
3 | RUN apt-get update \
4 | && apt-get install -y software-properties-common \
5 | && add-apt-repository -y ppa:ethereum/ethereum \
6 | && apt-get update
7 |
8 | # install golang 1.10
9 | RUN apt-get install -y golang-1.10-go
10 | # export GOPATH
11 | RUN printf "export GOPATH=/go\n" >> ~/.bashrc \
12 | && printf "export PATH=$PATH:/usr/lib/go-1.10/bin\n" >> ~/.bashrc \
13 | && printf "echo Welcome to the FUZZER\n" >> ~/.bashrc \
14 | && printf "echo Important commands are in bash history.\n" >> ~/.bashrc
15 |
16 | # use bash instead of /bin/sh
17 | RUN ["/bin/bash", "-c", "source ~/.bashrc"]
18 |
19 | RUN apt-get update && apt-get install -y git vim
20 |
21 | RUN echo './build/extract.sh -p /shared/ \n./build/bin/fuzzer --metadata /shared/fuzz_config/metadata_*.json --limit 4000 -o 8 --loglevel=4' > /root/.bash_history
22 |
23 |
24 | # install nodejs, Truffle and Ganache
25 | RUN apt-get install -y curl \
26 | && curl -sL https://deb.nodesource.com/setup_11.x | bash -
27 |
28 | RUN apt-get install -y nodejs \
29 | && npm -g config set user root \
30 | && npm install -g ganache-cli \
31 | && npm install -g truffle
32 |
33 | # clone go-ethereum, reset to revision: 27e3f968194e2723279b60f71c79d4da9fc7577f
34 | # and apply patch
35 | COPY ./build/patch /tmp/patch
36 | RUN mkdir -p /go/src/github.com/ethereum && cd /go/src/github.com/ethereum \
37 | && git clone https://github.com/ethereum/go-ethereum.git \
38 | && cd /go/src/github.com/ethereum/go-ethereum \
39 | && git reset --hard 27e3f968194e2723279b60f71c79d4da9fc7577f \
40 | && cd /go/src/github.com/ethereum/go-ethereum && git apply /tmp/patch
41 |
42 | WORKDIR /go/src/fuzzer
43 |
44 | COPY . /go/src/fuzzer/
45 |
46 | RUN ["/bin/bash", "-ci", "make fmt; make fuzz > /dev/null"]
47 |
48 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: all
2 |
3 | export GOBIN = $(shell pwd)/build/bin
4 |
5 | fuzz:
6 | build/env.sh go install fuzzer/*.go
7 |
8 | # extract transactions from truffle deployment code
9 | tx:
10 | @build/extract.sh ${version} ${path} ${solc}
11 |
12 | fmt:
13 | go fmt utils/*
14 | go fmt fuzzer/*
15 | go fmt argpool/*
16 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ChainFuzz: fast transaction fuzzer for Ethereum smart contracts
2 |
3 | ## Requirements
4 |
5 | - ChainFuzz requires a truffle project with correct migration files to fuzz a project.
6 |
7 | ## Checking custom properties
8 |
9 | Functions starting with `fuzz_always_true` will be evaluated for property violations.
10 |
11 | If such a function returns a value different than `1` or `True`, then ChainFuzz reports it as a custom property violation and stops.
12 |
13 | ## Fuzzing Truffle projects using ChainFuzz
14 |
15 | The easiest way to use ChainFuzz is using [docker](https://www.docker.com/).
16 |
17 | ### Build docker image
18 |
19 | To build a docker image, run the following command from the root folder of this repository:
20 |
21 | ```docker build -t chainfuzz .```
22 |
23 | ### Run docker image
24 |
25 | Go to the folder of the truffle project that you would like to test. For testing purposes, you can use `IndividuallyCappedCrowdsale` project:
26 |
27 | ```cd benchmarks/IndividuallyCappedCrowdsale```
28 |
29 | Then, run the following command:
30 |
31 | ```docker run -v $PWD:/shared -it chainfuzz```
32 |
33 | This command starts the docker image in interactive mode and mounts the folder of the truffle project (returned by `$(PWD)`) under `/shared` inside the docker container.
34 |
35 | ### Set up the fuzzer inside docker
36 |
37 | The command above places you inside a new docker container that can run ChainFuzz. Before fuzzing the project, we need to run the following command to deploy the truffle project on ganache and collect fuzzing metadata (described below):
38 |
39 | ```./build/extract.sh -p /shared/```
40 |
41 | ### ChainFuzz configuration
42 |
43 | ChainFuzz is configured with contracts and functions to be called when fuzzing, as well as which addresses to be used for sending transactions. This configuration is generated automatically by ChainFuzz using the command above, and can be modified by editing the following files (located in folder `fuzz_config`):
44 |
45 | - `config.json`: configure which functions should be used / ignored when fuzzing. Example configuration file:
46 | ```
47 | {
48 | "ContractName": {
49 | "ignore": ["method", "method1"],
50 | "timestamps": [1503756000, 1803756000]
51 | },
52 | "SomeToken": {
53 | "ignore": ["name", "symbol", "decimals", "pause", "unpause", "renounceOwnership", "transferOwnership"]
54 | },
55 | "Migrations": {
56 | "ignore_all": true
57 | }
58 | }
59 | ```
60 | You can define the functions of any contract to be ignored while fuzzing by mentioning the function name in the `ignore` property. Property `ignore_all` results in ignoring all functions of a given contract. The `timestamps` property takes different timestamps which will be used by the fuzzer to mock the `block.timestamp` and `now` instructions.
61 | - `accounts.json`: Ethereum accounts (addresses with ether balance) that can be used to send the generated transactions
62 |
63 |
64 | ### Run ChainFuzz
65 |
66 | To fuzz the project, you need to run ChainFuzz and provide the metadata file generated with the steps above:
67 |
68 | ```./build/bin/fuzzer --metadata /shared/fuzz_config/metadata_*.json --limit 4000```
69 |
70 | Additional options:
71 | - `-o 8` generates additional statistics about the called functions and their failure rates
72 | - `--loglevel=4` provides additional insides into inputs and outputs of the functions
73 |
74 | ### Results
75 |
76 | ChainFuzz checks and reports the following properties:
77 |
78 | - Custom property violations (defined as a function whose name starts with `fuzz_always_true` returning something other than 1)
79 | - Violated assertions (these are inserted either implicitly by the solidity compiler or explicitly in the code)
80 | - Arithmetic under-/overflows
81 |
82 | For any discovered violation, ChainFuzz generates a JSON file that contains the sequence of transactions that violates the property.
83 |
84 | # Contributors
85 |
86 | - Nodar Ambroladze
87 | - [Dr. Hubert Ritzdorf](https://github.com/ritzdorf)
88 | - Petar Ivanov
89 |
90 | # License
91 |
92 | Licensed under [GNU AFFERO GENERAL PUBLIC LICENSE Version 3](https://www.gnu.org/licenses/agpl-3.0.en.html)
93 |
94 | Copyright (C) 2019 [ChainSecurity AG](https://chainsecurity.com)
95 |
--------------------------------------------------------------------------------
/argpool/argpool.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package argpool
23 |
24 | import (
25 | "fmt"
26 | "math/big"
27 | "time"
28 |
29 | "github.com/ethereum/go-ethereum/common"
30 | "github.com/ethereum/go-ethereum/log"
31 | )
32 |
33 | var argPool *ArgPool
34 |
35 | type ArgPool struct {
36 | Int8Pool *int8pool
37 | Int16Pool *int16pool
38 | Int32Pool *int32pool
39 | Int64Pool *int64pool
40 | Bytes32Pool *bytes32pool
41 |
42 | AddressPool *pool
43 | BigIntPool *pool
44 | StringPool *stringpool
45 | TimestampPool *timestamppool
46 | }
47 |
48 | func (argPool *ArgPool) AddInt64(item int64) {
49 | if !argPool.Int64Pool.Contains(item) {
50 | log.Trace(fmt.Sprintf("adding int64: %+v", item))
51 | argPool.Int64Pool.Add(item)
52 | }
53 | }
54 |
55 | func (argPool *ArgPool) AddInt32(item int32) {
56 | if !argPool.Int32Pool.Contains(item) {
57 | log.Trace(fmt.Sprintf("adding int32: %+v", item))
58 | argPool.Int32Pool.Add(item)
59 | }
60 | }
61 |
62 | func (argPool *ArgPool) AddInt16(item int16) {
63 | if !argPool.Int16Pool.Contains(item) {
64 | log.Trace(fmt.Sprintf("adding int16: %+v", item))
65 | argPool.Int16Pool.Add(item)
66 | }
67 | }
68 |
69 | func (argPool *ArgPool) AddInt8(item int8) {
70 | if !argPool.Int8Pool.Contains(item) {
71 | log.Trace(fmt.Sprintf("adding int8: %+v", item))
72 | argPool.Int8Pool.Add(item)
73 | }
74 | }
75 |
76 | func (argPool *ArgPool) AddBytes32(item [32]byte) {
77 | if !argPool.Bytes32Pool.Contains(item) {
78 | log.Trace(fmt.Sprintf("adding bytes32: %+v", item))
79 | argPool.Bytes32Pool.Add(item)
80 | }
81 | }
82 |
83 | func (argPool *ArgPool) AddAddress(item common.Address) {
84 | if !argPool.AddressPool.Contains(item) {
85 | log.Trace(fmt.Sprintf("adding address: %+v", item))
86 | argPool.AddressPool.Add(item)
87 | }
88 | }
89 |
90 | func (argPool *ArgPool) AddBigInt(item *big.Int) {
91 | if !argPool.BigIntPool.Contains(item) {
92 | log.Trace(fmt.Sprintf("adding bigInt: %+v", item))
93 | argPool.BigIntPool.Add(item)
94 | }
95 | }
96 |
97 | func (argPool *ArgPool) AddString(item string) {
98 | if !argPool.StringPool.Contains(item) {
99 | log.Trace(fmt.Sprintf("adding string: %+v", item))
100 | argPool.StringPool.Add(item)
101 | }
102 | }
103 |
104 | func (argPool *ArgPool) AddTimestamp(item uint64) {
105 | if !argPool.TimestampPool.Contains(item) {
106 | log.Trace(fmt.Sprintf("adding timestamp: %+v", item))
107 | argPool.TimestampPool.Add(item)
108 | argPool.TimestampPool.Sort()
109 | }
110 | }
111 |
112 | func (pool *ArgPool) NextInt64() int64 {
113 | return pool.Int64Pool.Next()
114 | }
115 |
116 | func (pool *ArgPool) NextInt32() int32 {
117 | return pool.Int32Pool.Next()
118 | }
119 |
120 | func (pool *ArgPool) NextInt16() int16 {
121 | return pool.Int16Pool.Next()
122 | }
123 |
124 | func (pool *ArgPool) NextInt8() int8 {
125 | return pool.Int8Pool.Next()
126 | }
127 |
128 | func (pool *ArgPool) NextBytes32() [32]byte {
129 | return pool.Bytes32Pool.Next()
130 | }
131 |
132 | func (pool *ArgPool) NextAddress() common.Address {
133 | return pool.AddressPool.Next().(common.Address)
134 | }
135 |
136 | func (pool *ArgPool) NextBigInt() *big.Int {
137 | return pool.BigIntPool.Next().(*big.Int)
138 | }
139 |
140 | func (pool *ArgPool) NextString() string {
141 | return pool.StringPool.Next()
142 | }
143 |
144 | func (pool *ArgPool) NextTimestamp() (*big.Int, bool) {
145 | if pool.TimestampPool.Size() == 0 {
146 | return big.NewInt(time.Now().Unix()), false
147 | }
148 | return pool.TimestampPool.Next(), pool.TimestampPool.AllPassed()
149 | }
150 |
151 | func (pool *ArgPool) CurrentTimestamp() *big.Int {
152 | if pool.TimestampPool.Size() == 0 {
153 | return big.NewInt(time.Now().Unix())
154 | }
155 | return pool.TimestampPool.GetCurrent()
156 | }
157 |
158 | func (pool *ArgPool) GetSizes() map[string]int {
159 | return map[string]int{
160 | "int8": pool.Int8Pool.Size(),
161 | "int16": pool.Int16Pool.Size(),
162 | "int32": pool.Int32Pool.Size(),
163 | "int64": pool.Int64Pool.Size(),
164 | "string": pool.StringPool.Size(),
165 | "address": pool.AddressPool.Size(),
166 | "bigInt": pool.BigIntPool.Size(),
167 | "timestamp": pool.TimestampPool.Size(),
168 | }
169 | }
170 |
171 | // Singleton, returns same pool for same id
172 | func GetArgPool() *ArgPool {
173 | if argPool == nil {
174 | argPool = &ArgPool{
175 | Int8Pool: GetInt8Pool(),
176 | Int16Pool: GetInt16Pool(),
177 | Int32Pool: GetInt32Pool(),
178 | Int64Pool: GetInt64Pool(),
179 | Bytes32Pool: GetBytes32Pool(),
180 | AddressPool: GetPool("Address"),
181 | BigIntPool: GetPool("BigInt"),
182 | StringPool: GetStringPool(),
183 | TimestampPool: GetTimestampPool(),
184 | }
185 | }
186 | return argPool
187 | }
188 |
189 | func ResetArgPool() {
190 | argPool = nil
191 | }
192 |
--------------------------------------------------------------------------------
/argpool/bytes32pool.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package argpool
23 |
24 | // simple FIFO queue
25 | type bytes32pool struct {
26 | // Next() iterates circularly so we keep index of current element
27 | idx int
28 | // circular list of elements
29 | storage [][32]byte
30 | // map for checking whether pool already contains value, for deduplication
31 | storageMap map[[32]byte]bool
32 | }
33 |
34 | func (p *bytes32pool) Add(item [32]byte) {
35 | p.storage = append(p.storage, item)
36 | p.storageMap[item] = true
37 | }
38 |
39 | func (p *bytes32pool) Next() [32]byte {
40 | if len(p.storage) == 0 {
41 | return [32]byte{}
42 | }
43 | item := p.storage[p.idx]
44 | p.idx = (p.idx + 1) % len(p.storage)
45 | return item
46 | }
47 |
48 | func (p *bytes32pool) Contains(val [32]byte) bool {
49 | _, ok := p.storageMap[val]
50 | return ok
51 | }
52 |
53 | func (p *bytes32pool) Size() int {
54 | return len(p.storage)
55 | }
56 |
57 | func GetBytes32Pool() *bytes32pool {
58 | return &bytes32pool{
59 | idx: 0,
60 | storage: make([][32]byte, 0),
61 | storageMap: make(map[[32]byte]bool),
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/argpool/int16pool.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package argpool
23 |
24 | // simple FIFO queue
25 | type int16pool struct {
26 | // Next() iterates circularly so we keep index of current element
27 | idx int
28 | // circular list of elements
29 | storage []int16
30 | // map for checking whether pool already contains value, for deduplication
31 | storageMap map[int16]bool
32 | }
33 |
34 | func (p *int16pool) Add(item int16) {
35 | p.storage = append(p.storage, item)
36 | p.storageMap[item] = true
37 | }
38 |
39 | func (p *int16pool) Next() int16 {
40 | if len(p.storage) == 0 {
41 | return 0
42 | }
43 | item := p.storage[p.idx]
44 | p.idx = (p.idx + 1) % len(p.storage)
45 | return item
46 | }
47 |
48 | func (p *int16pool) Contains(val int16) bool {
49 | _, ok := p.storageMap[val]
50 | return ok
51 | }
52 |
53 | func (p *int16pool) Size() int {
54 | return len(p.storage)
55 | }
56 |
57 | func GetInt16Pool() *int16pool {
58 | return &int16pool{
59 | idx: 0,
60 | storage: make([]int16, 0),
61 | storageMap: make(map[int16]bool),
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/argpool/int32pool.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package argpool
23 |
24 | // simple FIFO queue
25 | type int32pool struct {
26 | // Next() iterates circularly so we keep index of current element
27 | idx int
28 | // circular list of elements
29 | storage []int32
30 | // map for checking whether pool already contains value, for deduplication
31 | storageMap map[int32]bool
32 | }
33 |
34 | func (p *int32pool) Add(item int32) {
35 | p.storage = append(p.storage, item)
36 | p.storageMap[item] = true
37 | }
38 |
39 | func (p *int32pool) Next() int32 {
40 | if len(p.storage) == 0 {
41 | return 0
42 | }
43 | item := p.storage[p.idx]
44 | p.idx = (p.idx + 1) % len(p.storage)
45 | return item
46 | }
47 |
48 | func (p *int32pool) Contains(val int32) bool {
49 | _, ok := p.storageMap[val]
50 | return ok
51 | }
52 |
53 | func (p *int32pool) Size() int {
54 | return len(p.storage)
55 | }
56 |
57 | func GetInt32Pool() *int32pool {
58 | return &int32pool{
59 | idx: 0,
60 | storage: make([]int32, 0),
61 | storageMap: make(map[int32]bool),
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/argpool/int64pool.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package argpool
23 |
24 | // simple FIFO queue
25 | type int64pool struct {
26 | // Next() iterates circularly so we keep index of current element
27 | idx int
28 | // circular list of elements
29 | storage []int64
30 | // map for checking whether pool already contains value, for deduplication
31 | storageMap map[int64]bool
32 | }
33 |
34 | func (p *int64pool) Add(item int64) {
35 | p.storage = append(p.storage, item)
36 | p.storageMap[item] = true
37 | }
38 |
39 | func (p *int64pool) Next() int64 {
40 | if len(p.storage) == 0 {
41 | return 0
42 | }
43 | item := p.storage[p.idx]
44 | p.idx = (p.idx + 1) % len(p.storage)
45 | return item
46 | }
47 |
48 | func (p *int64pool) Contains(val int64) bool {
49 | _, ok := p.storageMap[val]
50 | return ok
51 | }
52 |
53 | func (p *int64pool) Size() int {
54 | return len(p.storage)
55 | }
56 |
57 | func GetInt64Pool() *int64pool {
58 | return &int64pool{
59 | idx: 0,
60 | storage: make([]int64, 0),
61 | storageMap: make(map[int64]bool),
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/argpool/int8pool.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package argpool
23 |
24 | // simple FIFO queue
25 | type int8pool struct {
26 | // Next() iterates circularly so we keep index of current element
27 | idx int
28 | // circular list of elements
29 | storage []int8
30 | // map for checking whether pool already contains value, for deduplication
31 | storageMap map[int8]bool
32 | }
33 |
34 | func (p *int8pool) Add(item int8) {
35 | p.storage = append(p.storage, item)
36 | p.storageMap[item] = true
37 | }
38 |
39 | func (p *int8pool) Next() int8 {
40 | if len(p.storage) == 0 {
41 | return 0
42 | }
43 | item := p.storage[p.idx]
44 | p.idx = (p.idx + 1) % len(p.storage)
45 | return item
46 | }
47 |
48 | func (p *int8pool) Contains(val int8) bool {
49 | _, ok := p.storageMap[val]
50 | return ok
51 | }
52 |
53 | func (p *int8pool) Size() int {
54 | return len(p.storage)
55 | }
56 |
57 | func GetInt8Pool() *int8pool {
58 | return &int8pool{
59 | idx: 0,
60 | storage: make([]int8, 0),
61 | storageMap: make(map[int8]bool),
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/argpool/pool.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package argpool
23 |
24 | import (
25 | "fmt"
26 | )
27 |
28 | var pools map[string]*pool
29 |
30 | // simple FIFO queue
31 | type pool struct {
32 | // Next() iterates circularly so we keep index of current element
33 | idx int
34 | // circular list of elements
35 | storage []interface{}
36 | // map for checking whether pool already contains value, for deduplication
37 | storageMap map[string]bool
38 | }
39 |
40 | func (p *pool) Add(item interface{}) {
41 | p.storage = append(p.storage, item)
42 | p.storageMap[fmt.Sprintf("%v", item)] = true
43 | }
44 |
45 | func (p *pool) Next() interface{} {
46 | if len(p.storage) == 0 {
47 | return nil
48 | }
49 | item := p.storage[p.idx]
50 | p.idx = (p.idx + 1) % len(p.storage)
51 | return item
52 | }
53 |
54 | func (p *pool) Contains(val interface{}) bool {
55 | _, ok := p.storageMap[fmt.Sprintf("%v", val)]
56 | return ok
57 | }
58 |
59 | func (p *pool) Size() int {
60 | return len(p.storage)
61 | }
62 |
63 | func GetPool(id string) *pool {
64 | if pools[id] == nil {
65 | pools[id] = &pool{
66 | idx: 0,
67 | storage: make([]interface{}, 0),
68 | storageMap: make(map[string]bool),
69 | }
70 | }
71 | return pools[id]
72 | }
73 |
74 | func init() {
75 | pools = make(map[string]*pool)
76 | }
77 |
--------------------------------------------------------------------------------
/argpool/stringpool.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package argpool
23 |
24 | // simple FIFO queue
25 | type stringpool struct {
26 | // Next() iterates circularly so we keep index of current element
27 | idx int
28 | // circular list of elements
29 | storage []string
30 | // map for checking whether pool already contains value, for deduplication
31 | storageMap map[string]bool
32 | }
33 |
34 | func (p *stringpool) Add(item string) {
35 | p.storage = append(p.storage, item)
36 | p.storageMap[item] = true
37 | }
38 |
39 | func (p *stringpool) Next() string {
40 | if len(p.storage) == 0 {
41 | return ""
42 | }
43 | item := p.storage[p.idx]
44 | p.idx = (p.idx + 1) % len(p.storage)
45 | return item
46 | }
47 |
48 | func (p *stringpool) Contains(val string) bool {
49 | _, ok := p.storageMap[val]
50 | return ok
51 | }
52 |
53 | func (p *stringpool) Size() int {
54 | return len(p.storage)
55 | }
56 |
57 | func GetStringPool() *stringpool {
58 | return &stringpool{
59 | idx: 0,
60 | storage: make([]string, 0),
61 | storageMap: make(map[string]bool),
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/argpool/timestamppool.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package argpool
23 |
24 | import (
25 | "math/big"
26 | "sort"
27 | )
28 |
29 | // simple FIFO queue
30 | type timestamppool struct {
31 | // Next() iterates circularly so we keep index of current element
32 | idx int
33 | // circular list of elements
34 | storage []*big.Int
35 | // map for checking whether pool already contains value, for deduplication
36 | storageMap map[uint64]bool
37 | }
38 |
39 | func (p *timestamppool) Add(item uint64) {
40 | p.storage = append(p.storage, big.NewInt(int64(item)))
41 | p.storageMap[item] = true
42 | }
43 |
44 | func (p *timestamppool) Next() *big.Int {
45 | if len(p.storage) == 0 {
46 | return nil
47 | }
48 | p.idx = (p.idx + 1) % len(p.storage)
49 | return p.storage[p.idx]
50 | }
51 |
52 | func (p *timestamppool) GetCurrent() *big.Int {
53 | if len(p.storage) == 0 {
54 | return nil
55 | }
56 | return p.storage[p.idx]
57 | }
58 |
59 | func (p *timestamppool) AllPassed() bool {
60 | if len(p.storage) > 0 && (p.idx+1 == len(p.storage)) {
61 | return true
62 | }
63 | return false
64 | }
65 |
66 | func (p *timestamppool) Contains(val uint64) bool {
67 | _, ok := p.storageMap[val]
68 | return ok
69 | }
70 |
71 | // must only be used for timestamps
72 | func (p *timestamppool) Sort() {
73 | sort.Slice(p.storage, func(i, j int) bool {
74 | return p.storage[i].Uint64() < p.storage[j].Uint64()
75 | })
76 | }
77 |
78 | func (p *timestamppool) Size() int {
79 | return len(p.storage)
80 | }
81 |
82 | func GetTimestampPool() *timestamppool {
83 | return ×tamppool{
84 | idx: 0,
85 | storage: make([]*big.Int, 0),
86 | storageMap: make(map[uint64]bool),
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/benchmarks/IndividuallyCappedCrowdsale/contracts/CapperRole.sol:
--------------------------------------------------------------------------------
1 | // pragma solidity ^0.4.24;
2 |
3 | import "./Roles.sol";
4 |
5 |
6 | contract CapperRole {
7 | using Roles for Roles.Role;
8 |
9 | Roles.Role private cappers;
10 |
11 | constructor() public {
12 | cappers.add(msg.sender);
13 | }
14 |
15 | modifier onlyCapper() {
16 | require(isCapper(msg.sender));
17 | _;
18 | }
19 |
20 | function isCapper(address _account) public view returns (bool) {
21 | return cappers.has(_account);
22 | }
23 |
24 | function addCapper(address _account) public onlyCapper {
25 | cappers.add(_account);
26 | }
27 |
28 | function renounceCapper() public {
29 | cappers.remove(msg.sender);
30 | }
31 |
32 | function _removeCapper(address _account) internal {
33 | cappers.remove(_account);
34 | }
35 | }
--------------------------------------------------------------------------------
/benchmarks/IndividuallyCappedCrowdsale/contracts/Crowdsale.sol:
--------------------------------------------------------------------------------
1 | // pragma solidity ^0.4.24;
2 |
3 | import "./IERC20.sol";
4 | import "./SafeMath.sol";
5 | import "./SafeERC20.sol";
6 |
7 |
8 | /**
9 | * @title Crowdsale
10 | * @dev Crowdsale is a base contract for managing a token crowdsale,
11 | * allowing investors to purchase tokens with ether. This contract implements
12 | * such functionality in its most fundamental form and can be extended to provide additional
13 | * functionality and/or custom behavior.
14 | * The external interface represents the basic interface for purchasing tokens, and conform
15 | * the base architecture for crowdsales. They are *not* intended to be modified / overridden.
16 | * The internal interface conforms the extensible and modifiable surface of crowdsales. Override
17 | * the methods to add functionality. Consider using 'super' where appropriate to concatenate
18 | * behavior.
19 | */
20 | contract Crowdsale {
21 | using SafeMath for uint256;
22 | using SafeERC20 for IERC20;
23 |
24 | // The token being sold
25 | IERC20 private token_;
26 |
27 | // Address where funds are collected
28 | address private wallet_;
29 |
30 | // How many token units a buyer gets per wei.
31 | // The rate is the conversion between wei and the smallest and indivisible token unit.
32 | // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
33 | // 1 wei will give you 1 unit, or 0.001 TOK.
34 | uint256 private rate_;
35 |
36 | // Amount of wei raised
37 | uint256 private weiRaised_;
38 |
39 | /**
40 | * Event for token purchase logging
41 | * @param purchaser who paid for the tokens
42 | * @param beneficiary who got the tokens
43 | * @param value weis paid for purchase
44 | * @param amount amount of tokens purchased
45 | */
46 | event TokensPurchased(
47 | address indexed purchaser,
48 | address indexed beneficiary,
49 | uint256 value,
50 | uint256 amount
51 | );
52 |
53 | /**
54 | * @param _rate Number of token units a buyer gets per wei
55 | * @dev The rate is the conversion between wei and the smallest and indivisible
56 | * token unit. So, if you are using a rate of 1 with a ERC20Detailed token
57 | * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
58 | * @param _wallet Address where collected funds will be forwarded to
59 | * @param _token Address of the token being sold
60 | */
61 | constructor(uint256 _rate, address _wallet, IERC20 _token) public {
62 | require(_rate > 0);
63 | require(_wallet != address(0));
64 | require(_token != address(0));
65 |
66 | rate_ = _rate;
67 | wallet_ = _wallet;
68 | token_ = _token;
69 | }
70 |
71 | // -----------------------------------------
72 | // Crowdsale external interface
73 | // -----------------------------------------
74 |
75 | /**
76 | * @dev fallback function ***DO NOT OVERRIDE***
77 | */
78 | function () external payable {
79 | buyTokens(msg.sender);
80 | }
81 |
82 | /**
83 | * @return the token being sold.
84 | */
85 | function token() public view returns(IERC20) {
86 | return token_;
87 | }
88 |
89 | /**
90 | * @return the address where funds are collected.
91 | */
92 | function wallet() public view returns(address) {
93 | return wallet_;
94 | }
95 |
96 | /**
97 | * @return the number of token units a buyer gets per wei.
98 | */
99 | function rate() public view returns(uint256) {
100 | return rate_;
101 | }
102 |
103 | /**
104 | * @return the mount of wei raised.
105 | */
106 | function weiRaised() public view returns (uint256) {
107 | return weiRaised_;
108 | }
109 |
110 | /**
111 | * @dev low level token purchase ***DO NOT OVERRIDE***
112 | * @param _beneficiary Address performing the token purchase
113 | */
114 | function buyTokens(address _beneficiary) public payable {
115 |
116 | uint256 weiAmount = msg.value;
117 | _preValidatePurchase(_beneficiary, weiAmount);
118 |
119 | // calculate token amount to be created
120 | uint256 tokens = _getTokenAmount(weiAmount);
121 |
122 | // update state
123 | weiRaised_ = weiRaised_.add(weiAmount);
124 |
125 | _processPurchase(_beneficiary, tokens);
126 | emit TokensPurchased(
127 | msg.sender,
128 | _beneficiary,
129 | weiAmount,
130 | tokens
131 | );
132 |
133 | _updatePurchasingState(_beneficiary, weiAmount);
134 |
135 | _forwardFunds();
136 | _postValidatePurchase(_beneficiary, weiAmount);
137 | }
138 |
139 | // -----------------------------------------
140 | // Internal interface (extensible)
141 | // -----------------------------------------
142 |
143 | /**
144 | * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
145 | * Example from CappedCrowdsale.sol's _preValidatePurchase method:
146 | * super._preValidatePurchase(_beneficiary, _weiAmount);
147 | * require(weiRaised().add(_weiAmount) <= cap);
148 | * @param _beneficiary Address performing the token purchase
149 | * @param _weiAmount Value in wei involved in the purchase
150 | */
151 | function _preValidatePurchase(
152 | address _beneficiary,
153 | uint256 _weiAmount
154 | )
155 | internal
156 | {
157 | require(_beneficiary != address(0));
158 | require(_weiAmount != 0);
159 | }
160 |
161 | /**
162 | * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
163 | * @param _beneficiary Address performing the token purchase
164 | * @param _weiAmount Value in wei involved in the purchase
165 | */
166 | function _postValidatePurchase(
167 | address _beneficiary,
168 | uint256 _weiAmount
169 | )
170 | internal
171 | {
172 | // optional override
173 | }
174 |
175 | /**
176 | * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
177 | * @param _beneficiary Address performing the token purchase
178 | * @param _tokenAmount Number of tokens to be emitted
179 | */
180 | function _deliverTokens(
181 | address _beneficiary,
182 | uint256 _tokenAmount
183 | )
184 | internal
185 | {
186 | token_.safeTransfer(_beneficiary, _tokenAmount);
187 | }
188 |
189 | /**
190 | * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
191 | * @param _beneficiary Address receiving the tokens
192 | * @param _tokenAmount Number of tokens to be purchased
193 | */
194 | function _processPurchase(
195 | address _beneficiary,
196 | uint256 _tokenAmount
197 | )
198 | internal
199 | {
200 | _deliverTokens(_beneficiary, _tokenAmount);
201 | }
202 |
203 | /**
204 | * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
205 | * @param _beneficiary Address receiving the tokens
206 | * @param _weiAmount Value in wei involved in the purchase
207 | */
208 | function _updatePurchasingState(
209 | address _beneficiary,
210 | uint256 _weiAmount
211 | )
212 | internal
213 | {
214 | // optional override
215 | }
216 |
217 | /**
218 | * @dev Override to extend the way in which ether is converted to tokens.
219 | * @param _weiAmount Value in wei to be converted into tokens
220 | * @return Number of tokens that can be purchased with the specified _weiAmount
221 | */
222 | function _getTokenAmount(uint256 _weiAmount)
223 | internal view returns (uint256)
224 | {
225 | return _weiAmount.mul(rate_);
226 | }
227 |
228 | /**
229 | * @dev Determines how ETH is stored/forwarded on purchases.
230 | */
231 | function _forwardFunds() internal {
232 | wallet_.transfer(msg.value);
233 | }
234 | }
--------------------------------------------------------------------------------
/benchmarks/IndividuallyCappedCrowdsale/contracts/ERC20.sol:
--------------------------------------------------------------------------------
1 | // pragma solidity ^0.4.24;
2 |
3 | import "./IERC20.sol";
4 | import "./SafeMath.sol";
5 |
6 |
7 | /**
8 | * @title Standard ERC20 token
9 | *
10 | * @dev Implementation of the basic standard token.
11 | * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
12 | * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
13 | */
14 | contract ERC20 is IERC20 {
15 | using SafeMath for uint256;
16 |
17 | mapping (address => uint256) private balances_;
18 |
19 | mapping (address => mapping (address => uint256)) private allowed_;
20 |
21 | uint256 private totalSupply_;
22 |
23 | /**
24 | * @dev Total number of tokens in existence
25 | */
26 | function totalSupply() public view returns (uint256) {
27 | return totalSupply_;
28 | }
29 |
30 | /**
31 | * @dev Gets the balance of the specified address.
32 | * @param _owner The address to query the the balance of.
33 | * @return An uint256 representing the amount owned by the passed address.
34 | */
35 | function balanceOf(address _owner) public view returns (uint256) {
36 | return balances_[_owner];
37 | }
38 |
39 | /**
40 | * @dev Function to check the amount of tokens that an owner allowed to a spender.
41 | * @param _owner address The address which owns the funds.
42 | * @param _spender address The address which will spend the funds.
43 | * @return A uint256 specifying the amount of tokens still available for the spender.
44 | */
45 | function allowance(
46 | address _owner,
47 | address _spender
48 | )
49 | public
50 | view
51 | returns (uint256)
52 | {
53 | return allowed_[_owner][_spender];
54 | }
55 |
56 | /**
57 | * @dev Transfer token for a specified address
58 | * @param _to The address to transfer to.
59 | * @param _value The amount to be transferred.
60 | */
61 | function transfer(address _to, uint256 _value) public returns (bool) {
62 | require(_value <= balances_[msg.sender]);
63 | require(_to != address(0));
64 |
65 | balances_[msg.sender] = balances_[msg.sender].sub(_value);
66 | balances_[_to] = balances_[_to].add(_value);
67 | emit Transfer(msg.sender, _to, _value);
68 | return true;
69 | }
70 |
71 | /**
72 | * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
73 | * Beware that changing an allowance with this method brings the risk that someone may use both the old
74 | * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
75 | * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
76 | * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
77 | * @param _spender The address which will spend the funds.
78 | * @param _value The amount of tokens to be spent.
79 | */
80 | function approve(address _spender, uint256 _value) public returns (bool) {
81 | require(_spender != address(0));
82 |
83 | allowed_[msg.sender][_spender] = _value;
84 | emit Approval(msg.sender, _spender, _value);
85 | return true;
86 | }
87 |
88 | /**
89 | * @dev Transfer tokens from one address to another
90 | * @param _from address The address which you want to send tokens from
91 | * @param _to address The address which you want to transfer to
92 | * @param _value uint256 the amount of tokens to be transferred
93 | */
94 | function transferFrom(
95 | address _from,
96 | address _to,
97 | uint256 _value
98 | )
99 | public
100 | returns (bool)
101 | {
102 | require(_value <= balances_[_from]);
103 | require(_value <= allowed_[_from][msg.sender]);
104 | require(_to != address(0));
105 |
106 | balances_[_from] = balances_[_from].sub(_value);
107 | balances_[_to] = balances_[_to].add(_value);
108 | allowed_[_from][msg.sender] = allowed_[_from][msg.sender].sub(_value);
109 | emit Transfer(_from, _to, _value);
110 | return true;
111 | }
112 |
113 | /**
114 | * @dev Increase the amount of tokens that an owner allowed to a spender.
115 | * approve should be called when allowed_[_spender] == 0. To increment
116 | * allowed value is better to use this function to avoid 2 calls (and wait until
117 | * the first transaction is mined)
118 | * From MonolithDAO Token.sol
119 | * @param _spender The address which will spend the funds.
120 | * @param _addedValue The amount of tokens to increase the allowance by.
121 | */
122 | function increaseAllowance(
123 | address _spender,
124 | uint256 _addedValue
125 | )
126 | public
127 | returns (bool)
128 | {
129 | require(_spender != address(0));
130 |
131 | allowed_[msg.sender][_spender] = (
132 | allowed_[msg.sender][_spender].add(_addedValue));
133 | emit Approval(msg.sender, _spender, allowed_[msg.sender][_spender]);
134 | return true;
135 | }
136 |
137 | /**
138 | * @dev Decrease the amount of tokens that an owner allowed to a spender.
139 | * approve should be called when allowed_[_spender] == 0. To decrement
140 | * allowed value is better to use this function to avoid 2 calls (and wait until
141 | * the first transaction is mined)
142 | * From MonolithDAO Token.sol
143 | * @param _spender The address which will spend the funds.
144 | * @param _subtractedValue The amount of tokens to decrease the allowance by.
145 | */
146 | function decreaseAllowance(
147 | address _spender,
148 | uint256 _subtractedValue
149 | )
150 | public
151 | returns (bool)
152 | {
153 | require(_spender != address(0));
154 |
155 | allowed_[msg.sender][_spender] = (
156 | allowed_[msg.sender][_spender].sub(_subtractedValue));
157 | emit Approval(msg.sender, _spender, allowed_[msg.sender][_spender]);
158 | return true;
159 | }
160 |
161 | /**
162 | * @dev Internal function that mints an amount of the token and assigns it to
163 | * an account. This encapsulates the modification of balances such that the
164 | * proper events are emitted.
165 | * @param _account The account that will receive the created tokens.
166 | * @param _amount The amount that will be created.
167 | */
168 | function _mint(address _account, uint256 _amount) internal {
169 | require(_account != 0);
170 | totalSupply_ = totalSupply_.add(_amount);
171 | balances_[_account] = balances_[_account].add(_amount);
172 | emit Transfer(address(0), _account, _amount);
173 | }
174 |
175 | /**
176 | * @dev Internal function that burns an amount of the token of a given
177 | * account.
178 | * @param _account The account whose tokens will be burnt.
179 | * @param _amount The amount that will be burnt.
180 | */
181 | function _burn(address _account, uint256 _amount) internal {
182 | require(_account != 0);
183 | require(_amount <= balances_[_account]);
184 |
185 | totalSupply_ = totalSupply_.sub(_amount);
186 | balances_[_account] = balances_[_account].sub(_amount);
187 | emit Transfer(_account, address(0), _amount);
188 | }
189 |
190 | /**
191 | * @dev Internal function that burns an amount of the token of a given
192 | * account, deducting from the sender's allowance for said account. Uses the
193 | * internal _burn function.
194 | * @param _account The account whose tokens will be burnt.
195 | * @param _amount The amount that will be burnt.
196 | */
197 | function _burnFrom(address _account, uint256 _amount) internal {
198 | require(_amount <= allowed_[_account][msg.sender]);
199 |
200 | // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
201 | // this function needs to emit an event with the updated approval.
202 | allowed_[_account][msg.sender] = allowed_[_account][msg.sender].sub(
203 | _amount);
204 | _burn(_account, _amount);
205 | }
206 | }
--------------------------------------------------------------------------------
/benchmarks/IndividuallyCappedCrowdsale/contracts/IERC20.sol:
--------------------------------------------------------------------------------
1 | // pragma solidity ^0.4.24;
2 |
3 |
4 | /**
5 | * @title ERC20 interface
6 | * @dev see https://github.com/ethereum/EIPs/issues/20
7 | */
8 | interface IERC20 {
9 | function totalSupply() external view returns (uint256);
10 |
11 | function balanceOf(address _who) external view returns (uint256);
12 |
13 | function allowance(address _owner, address _spender)
14 | external view returns (uint256);
15 |
16 | function transfer(address _to, uint256 _value) external returns (bool);
17 |
18 | function approve(address _spender, uint256 _value)
19 | external returns (bool);
20 |
21 | function transferFrom(address _from, address _to, uint256 _value)
22 | external returns (bool);
23 |
24 | event Transfer(
25 | address indexed from,
26 | address indexed to,
27 | uint256 value
28 | );
29 |
30 | event Approval(
31 | address indexed owner,
32 | address indexed spender,
33 | uint256 value
34 | );
35 | }
--------------------------------------------------------------------------------
/benchmarks/IndividuallyCappedCrowdsale/contracts/IndividuallyCappedCrowdsale.sol:
--------------------------------------------------------------------------------
1 | //pragma solidity ^0.4.24;
2 |
3 | import "./SafeMath.sol";
4 | import "./Crowdsale.sol";
5 | import "./CapperRole.sol";
6 |
7 |
8 | /**
9 | * @title IndividuallyCappedCrowdsale
10 | * @dev Crowdsale with per-beneficiary caps.
11 | */
12 | contract IndividuallyCappedCrowdsale is Crowdsale, CapperRole {
13 | using SafeMath for uint256;
14 |
15 | mapping(address => uint256) private contributions_;
16 | mapping(address => uint256) private caps_;
17 |
18 |
19 | function IndividuallyCappedCrowdsale(uint256 _rate, address _wallet, IERC20 _token) Crowdsale(_rate, _wallet, _token) {}
20 |
21 |
22 | address constant private account0 = 0x2fe5e54e71755a9719fd5b06c8697cefa1283165;
23 | address constant private account1 = 0x9b4ffb882b897fd506116cfb02362af19c96512d;
24 |
25 | function fuzz_always_true_capNotReached() public view returns (bool) {
26 | if (contributions_[account0] != caps_[account0]) {
27 | return true;
28 | }
29 | if (contributions_[account1] != caps_[account1]) {
30 | return true;
31 | }
32 | return false;
33 | }
34 |
35 | /**
36 | * @dev Sets a specific beneficiary's maximum contribution.
37 | * @param _beneficiary Address to be capped
38 | * @param _cap Wei limit for individual contribution
39 | */
40 | function setCap(address _beneficiary, uint256 _cap) external onlyCapper {
41 | caps_[_beneficiary] = _cap;
42 | }
43 |
44 | /**
45 | * @dev Returns the cap of a specific beneficiary.
46 | * @param _beneficiary Address whose cap is to be checked
47 | * @return Current cap for individual beneficiary
48 | */
49 | function getCap(address _beneficiary) public view returns (uint256) {
50 | return caps_[_beneficiary];
51 | }
52 |
53 | /**
54 | * @dev Returns the amount contributed so far by a specific beneficiary.
55 | * @param _beneficiary Address of contributor
56 | * @return Beneficiary contribution so far
57 | */
58 | function getContribution(address _beneficiary)
59 | public view returns (uint256)
60 | {
61 | return contributions_[_beneficiary];
62 | }
63 |
64 | /**
65 | * @dev Extend parent behavior requiring purchase to respect the beneficiary's funding cap.
66 | * @param _beneficiary Token purchaser
67 | * @param _weiAmount Amount of wei contributed
68 | */
69 | function _preValidatePurchase(
70 | address _beneficiary,
71 | uint256 _weiAmount
72 | )
73 | internal
74 | {
75 | super._preValidatePurchase(_beneficiary, _weiAmount);
76 | require(
77 | contributions_[_beneficiary].add(_weiAmount) <= caps_[_beneficiary]);
78 | }
79 |
80 | /**
81 | * @dev Extend parent behavior to update beneficiary contributions
82 | * @param _beneficiary Token purchaser
83 | * @param _weiAmount Amount of wei contributed
84 | */
85 | function _updatePurchasingState(
86 | address _beneficiary,
87 | uint256 _weiAmount
88 | )
89 | internal
90 | {
91 | super._updatePurchasingState(_beneficiary, _weiAmount);
92 | contributions_[_beneficiary] = contributions_[_beneficiary].add(
93 | _weiAmount);
94 | }
95 |
96 | }
97 |
--------------------------------------------------------------------------------
/benchmarks/IndividuallyCappedCrowdsale/contracts/Migrations.sol:
--------------------------------------------------------------------------------
1 | // pragma solidity ^0.4.24;
2 |
3 | contract Migrations {
4 | address public owner;
5 | uint public last_completed_migration;
6 |
7 | modifier restricted() {
8 | if (msg.sender == owner) _;
9 | }
10 |
11 | constructor() public {
12 | owner = msg.sender;
13 | }
14 |
15 | function setCompleted(uint completed) public restricted {
16 | last_completed_migration = completed;
17 | }
18 |
19 | function upgrade(address new_address) public restricted {
20 | Migrations upgraded = Migrations(new_address);
21 | upgraded.setCompleted(last_completed_migration);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/benchmarks/IndividuallyCappedCrowdsale/contracts/Roles.sol:
--------------------------------------------------------------------------------
1 | // pragma solidity ^0.4.24;
2 |
3 |
4 | /**
5 | * @title Roles
6 | * @dev Library for managing addresses assigned to a Role.
7 | */
8 | library Roles {
9 | struct Role {
10 | mapping (address => bool) bearer;
11 | }
12 |
13 | /**
14 | * @dev give an account access to this role
15 | */
16 | function add(Role storage _role, address _account) internal {
17 | _role.bearer[_account] = true;
18 | }
19 |
20 | /**
21 | * @dev remove an account's access to this role
22 | */
23 | function remove(Role storage _role, address _account) internal {
24 | _role.bearer[_account] = false;
25 | }
26 |
27 | /**
28 | * @dev check if an account has this role
29 | * @return bool
30 | */
31 | function has(Role storage _role, address _account)
32 | internal
33 | view
34 | returns (bool)
35 | {
36 | return _role.bearer[_account];
37 | }
38 | }
--------------------------------------------------------------------------------
/benchmarks/IndividuallyCappedCrowdsale/contracts/SafeERC20.sol:
--------------------------------------------------------------------------------
1 | // pragma solidity ^0.4.24;
2 |
3 | import "./ERC20.sol";
4 | import "./IERC20.sol";
5 |
6 |
7 | /**
8 | * @title SafeERC20
9 | * @dev Wrappers around ERC20 operations that throw on failure.
10 | * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
11 | * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
12 | */
13 | library SafeERC20 {
14 | function safeTransfer(
15 | IERC20 _token,
16 | address _to,
17 | uint256 _value
18 | )
19 | internal
20 | {
21 | require(_token.transfer(_to, _value));
22 | }
23 |
24 | function safeTransferFrom(
25 | IERC20 _token,
26 | address _from,
27 | address _to,
28 | uint256 _value
29 | )
30 | internal
31 | {
32 | require(_token.transferFrom(_from, _to, _value));
33 | }
34 |
35 | function safeApprove(
36 | IERC20 _token,
37 | address _spender,
38 | uint256 _value
39 | )
40 | internal
41 | {
42 | require(_token.approve(_spender, _value));
43 | }
44 | }
--------------------------------------------------------------------------------
/benchmarks/IndividuallyCappedCrowdsale/contracts/SafeMath.sol:
--------------------------------------------------------------------------------
1 | // pragma solidity ^0.4.24;
2 |
3 |
4 | /**
5 | * @title SafeMath
6 | * @dev Math operations with safety checks that revert on error
7 | */
8 | library SafeMath {
9 |
10 | /**
11 | * @dev Multiplies two numbers, reverts on overflow.
12 | */
13 | function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
14 | // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
15 | // benefit is lost if 'b' is also tested.
16 | // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
17 | if (_a == 0) {
18 | return 0;
19 | }
20 |
21 | uint256 c = _a * _b;
22 | require(c / _a == _b);
23 |
24 | return c;
25 | }
26 |
27 | /**
28 | * @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
29 | */
30 | function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
31 | require(_b > 0); // Solidity only automatically asserts when dividing by 0
32 | uint256 c = _a / _b;
33 | // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
34 |
35 | return c;
36 | }
37 |
38 | /**
39 | * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
40 | */
41 | function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
42 | require(_b <= _a);
43 | uint256 c = _a - _b;
44 |
45 | return c;
46 | }
47 |
48 | /**
49 | * @dev Adds two numbers, reverts on overflow.
50 | */
51 | function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
52 | uint256 c = _a + _b;
53 | require(c >= _a);
54 |
55 | return c;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/benchmarks/IndividuallyCappedCrowdsale/contracts/SimpleToken.sol:
--------------------------------------------------------------------------------
1 | // pragma solidity ^0.4.24;
2 |
3 |
4 | import "./StandardToken.sol";
5 |
6 |
7 | /**
8 | * @title SimpleToken
9 | * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator.
10 | * Note they can later distribute these tokens as they wish using `transfer` and other
11 | * `StandardToken` functions.
12 | */
13 | contract SimpleToken is StandardToken {
14 |
15 | string public constant name = "SimpleToken";
16 | string public constant symbol = "SIM";
17 | uint8 public constant decimals = 18;
18 |
19 | uint256 public constant INITIAL_SUPPLY = 10000 * (10 ** uint256(decimals));
20 |
21 | /**
22 | * @dev Constructor that gives msg.sender all of existing tokens.
23 | */
24 | constructor() public {
25 | totalSupply_ = INITIAL_SUPPLY;
26 | balances[msg.sender] = INITIAL_SUPPLY;
27 | emit Transfer(address(0), msg.sender, INITIAL_SUPPLY);
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/benchmarks/IndividuallyCappedCrowdsale/contracts/StandardToken.sol:
--------------------------------------------------------------------------------
1 | // pragma solidity ^0.4.24;
2 |
3 | import "./ERC20.sol";
4 | import "./SafeMath.sol";
5 |
6 |
7 | /**
8 | * @title Standard ERC20 token
9 | *
10 | * @dev Implementation of the basic standard token.
11 | * https://github.com/ethereum/EIPs/issues/20
12 | * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
13 | */
14 | contract StandardToken is ERC20 {
15 | using SafeMath for uint256;
16 |
17 | mapping(address => uint256) balances;
18 |
19 | mapping (address => mapping (address => uint256)) internal allowed;
20 |
21 | uint256 totalSupply_;
22 |
23 | /**
24 | * @dev Total number of tokens in existence
25 | */
26 | function totalSupply() public view returns (uint256) {
27 | return totalSupply_;
28 | }
29 |
30 | /**
31 | * @dev Gets the balance of the specified address.
32 | * @param _owner The address to query the the balance of.
33 | * @return An uint256 representing the amount owned by the passed address.
34 | */
35 | function balanceOf(address _owner) public view returns (uint256) {
36 | return balances[_owner];
37 | }
38 |
39 | /**
40 | * @dev Function to check the amount of tokens that an owner allowed to a spender.
41 | * @param _owner address The address which owns the funds.
42 | * @param _spender address The address which will spend the funds.
43 | * @return A uint256 specifying the amount of tokens still available for the spender.
44 | */
45 | function allowance(
46 | address _owner,
47 | address _spender
48 | )
49 | public
50 | view
51 | returns (uint256)
52 | {
53 | return allowed[_owner][_spender];
54 | }
55 |
56 | /**
57 | * @dev Transfer token for a specified address
58 | * @param _to The address to transfer to.
59 | * @param _value The amount to be transferred.
60 | */
61 | function transfer(address _to, uint256 _value) public returns (bool) {
62 | // require(_value <= balances[msg.sender]);
63 | // require(_to != address(0));
64 |
65 | balances[msg.sender] = balances[msg.sender].sub(_value);
66 | balances[_to] = balances[_to].add(_value);
67 | emit Transfer(msg.sender, _to, _value);
68 | return true;
69 | }
70 |
71 | /**
72 | * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
73 | * Beware that changing an allowance with this method brings the risk that someone may use both the old
74 | * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
75 | * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
76 | * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
77 | * @param _spender The address which will spend the funds.
78 | * @param _value The amount of tokens to be spent.
79 | */
80 | function approve(address _spender, uint256 _value) public returns (bool) {
81 | allowed[msg.sender][_spender] = _value;
82 | emit Approval(msg.sender, _spender, _value);
83 | return true;
84 | }
85 |
86 | /**
87 | * @dev Transfer tokens from one address to another
88 | * @param _from address The address which you want to send tokens from
89 | * @param _to address The address which you want to transfer to
90 | * @param _value uint256 the amount of tokens to be transferred
91 | */
92 | function transferFrom(
93 | address _from,
94 | address _to,
95 | uint256 _value
96 | )
97 | public
98 | returns (bool)
99 | {
100 | require(_value <= balances[_from]);
101 | require(_value <= allowed[_from][msg.sender]);
102 | require(_to != address(0));
103 |
104 | balances[_from] = balances[_from].sub(_value);
105 | balances[_to] = balances[_to].add(_value);
106 | allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
107 | emit Transfer(_from, _to, _value);
108 | return true;
109 | }
110 |
111 | /**
112 | * @dev Increase the amount of tokens that an owner allowed to a spender.
113 | * approve should be called when allowed[_spender] == 0. To increment
114 | * allowed value is better to use this function to avoid 2 calls (and wait until
115 | * the first transaction is mined)
116 | * From MonolithDAO Token.sol
117 | * @param _spender The address which will spend the funds.
118 | * @param _addedValue The amount of tokens to increase the allowance by.
119 | */
120 | function increaseApproval(
121 | address _spender,
122 | uint256 _addedValue
123 | )
124 | public
125 | returns (bool)
126 | {
127 | allowed[msg.sender][_spender] = (
128 | allowed[msg.sender][_spender].add(_addedValue));
129 | emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
130 | return true;
131 | }
132 |
133 | /**
134 | * @dev Decrease the amount of tokens that an owner allowed to a spender.
135 | * approve should be called when allowed[_spender] == 0. To decrement
136 | * allowed value is better to use this function to avoid 2 calls (and wait until
137 | * the first transaction is mined)
138 | * From MonolithDAO Token.sol
139 | * @param _spender The address which will spend the funds.
140 | * @param _subtractedValue The amount of tokens to decrease the allowance by.
141 | */
142 | function decreaseApproval(
143 | address _spender,
144 | uint256 _subtractedValue
145 | )
146 | public
147 | returns (bool)
148 | {
149 | uint256 oldValue = allowed[msg.sender][_spender];
150 | if (_subtractedValue >= oldValue) {
151 | allowed[msg.sender][_spender] = 0;
152 | } else {
153 | allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
154 | }
155 | emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
156 | return true;
157 | }
158 |
159 | }
160 |
--------------------------------------------------------------------------------
/benchmarks/IndividuallyCappedCrowdsale/migrations/1_initial_migration.js:
--------------------------------------------------------------------------------
1 | var Migrations = artifacts.require("./Migrations.sol");
2 |
3 | module.exports = function(deployer) {
4 | deployer.deploy(Migrations);
5 | };
6 |
--------------------------------------------------------------------------------
/benchmarks/IndividuallyCappedCrowdsale/migrations/2_deploy_contracts.js:
--------------------------------------------------------------------------------
1 |
2 | var SimpleToken = artifacts.require("./SimpleToken.sol");
3 | var IndividuallyCappedCrowdsale = artifacts.require("./IndividuallyCappedCrowdsale.sol");
4 | var Crowdsale = artifacts.require("./Crowdsale.sol");
5 |
6 |
7 | module.exports = async function(deployer, _, accounts) {
8 |
9 | let token = await SimpleToken.new();
10 | let individuallyCappedCrowdsale = await IndividuallyCappedCrowdsale.new(new web3.utils.BN(1), accounts[0], token.address);
11 | await token.transfer(individuallyCappedCrowdsale.address, new web3.utils.BN('1e22'));
12 | await individuallyCappedCrowdsale.setCap(accounts[0], new web3.utils.BN('1e20'))
13 | await individuallyCappedCrowdsale.setCap(accounts[1], new web3.utils.BN('1e20'))
14 | };
15 |
16 |
--------------------------------------------------------------------------------
/benchmarks/IndividuallyCappedCrowdsale/test/.placeholder:
--------------------------------------------------------------------------------
1 | This is a placeholder file to ensure the parent directory in the git repository. Feel free to remove.
2 |
--------------------------------------------------------------------------------
/benchmarks/IndividuallyCappedCrowdsale/test/Crowdsale.test.js:
--------------------------------------------------------------------------------
1 | const SimpleToken = artifacts.require("SimpleToken");
2 | const Crowdsale = artifacts.require("Crowdsale");
3 |
4 |
5 | // this.token = await SimpleToken.new();
6 | // this.crowdsale = await Crowdsale.new(rate, wallet, this.token.address);
7 | // await this.token.transfer(this.crowdsale.address, tokenSupply);
8 |
9 | contract('Crowdsale test', async (accounts) => {
10 | it("blabla", async () => {
11 | let token = await SimpleToken.new();
12 | let crowdsale = await Crowdsale.new(new web3.BigNumber(1), web3.eth.accounts[0], token.address);
13 | await token.transfer(crowdsale.address, new web3.BigNumber('1e27'));
14 | await crowdsale.buyTokens(web3.eth.accounts[0], {value:5});
15 | await crowdsale.buyTokens(web3.eth.accounts[1], {value:7});
16 |
17 | let balance0 = await token.balanceOf(web3.eth.accounts[0]);
18 | let balance1 = await token.balanceOf(web3.eth.accounts[1]);
19 | console.log(balance0.toNumber())
20 | console.log(balance1.toNumber())
21 | })
22 | })
23 |
--------------------------------------------------------------------------------
/benchmarks/IndividuallyCappedCrowdsale/truffle.js:
--------------------------------------------------------------------------------
1 | // module.exports = {
2 | // // See
3 | // // to customize your Truffle configuration!
4 | // };
5 |
6 |
7 |
8 | module.exports = {
9 | networks: {
10 | development: {
11 | host: "127.0.0.1",
12 | port: 8545,
13 | network_id: "*" // Match any network id
14 | // gas: 0xfffffffff,
15 | // gasPrice: 1
16 | }
17 | },
18 | compilers: {
19 | solc: {
20 | version: "0.4.25", // Fetch exact version from solc-bin (default: truffle's version)
21 | settings: { // See the solidity docs for advice about optimization and evmVersion
22 | optimizer: {
23 | enabled: true,
24 | runs: 200
25 | }
26 | }
27 | }
28 | }
29 | };
30 |
--------------------------------------------------------------------------------
/build/env.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | set -e
4 |
5 | if [ ! -f "build/env.sh" ]; then
6 | echo "$0 must be run from the root of the repository."
7 | exit 2
8 | fi
9 |
10 | if [ ! -L "$GOPATH/src/fuzzer/vendor" ]; then
11 | ln -s "$GOPATH/src/github.com/ethereum/go-ethereum/vendor" $GOPATH/src/fuzzer/vendor
12 | fi
13 |
14 | # Launch the arguments with the configured environment.
15 | exec "$@"
16 | # /bin/bash
17 |
--------------------------------------------------------------------------------
/build/extract.js:
--------------------------------------------------------------------------------
1 | module.exports = async function(callback) {
2 | var fs = require('fs');
3 | var logFile = process.cwd() + `/transactions.json`;
4 |
5 | // remove log file
6 | fs.unlink(logFile, (err) => {
7 | if (!err) {
8 | console.log(logFile, ' was deleted');
9 | }
10 | });
11 |
12 | console.log(`creating file ${logFile}`)
13 | console.log("total number of blocks", await web3.eth.getBlockNumber())
14 |
15 | // start from first block, block 0 is genesis, it doesn't contain any transaction
16 | for (var i = 1; i <= await web3.eth.getBlockNumber(); i++) {
17 | var block = await web3.eth.getBlock(i)
18 | for (var idx = 0; idx < block.transactions.length; idx++)
19 | var transaction = await web3.eth.getTransaction(block.transactions[idx])
20 | console.log("from: " + transaction.from + " to:" + transaction.to + " Nonce:" + transaction.nonce)
21 | var tx_json = JSON.stringify(transaction) + "\n"
22 | fs.appendFileSync(logFile, tx_json);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/build/extract.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -e
4 |
5 | RED='\033[0;31m'
6 | NC='\033[0m'
7 | GREEN='\033[1;32m'
8 | YELLOW='\033[1;33m'
9 | CYAN='\033[0;36m'
10 |
11 | display_usage() {
12 | printf "${RED}You must provide path to truffle project that you want to deploy and extract transactions from${NC}\n"
13 | printf "Usage:\n"
14 | printf "\t-p, --path\tpath to the first version of truffle project\n"
15 | printf "\n\n"
16 | printf "Example:\n\t./extract.sh -p /home/anodar/Desktop/thesis/MetaCoin\n"
17 | printf "\n\n"
18 | }
19 |
20 | if [ $# -le 1 ]
21 | then
22 | display_usage
23 | exit 1
24 | fi
25 |
26 |
27 | POSITIONAL=()
28 | while [[ $# -gt 0 ]]
29 | do
30 | key="$1"
31 |
32 | case $key in
33 | -p|--path)
34 | TRUFFLE_DIR="$2"
35 | shift # past argument
36 | shift # past value
37 | ;;
38 | -s|--solc)
39 | SOLC_V="$2"
40 | shift # past argument
41 | shift # past value
42 | ;;
43 | --default)
44 | DEFAULT=YES
45 | shift # past argument
46 | ;;
47 | *) # unknown option
48 | POSITIONAL+=("$1") # save it in an array for later
49 | shift # past argument
50 | ;;
51 | esac
52 | done
53 | set -- "${POSITIONAL[@]}" # restore positional parameters
54 |
55 | echo truffle directory = "${TRUFFLE_DIR}"
56 | VERSION=$(echo ${TRUFFLE_DIR} | sha1sum | awk '{print $1}')
57 | echo truffle project version = "${VERSION}"
58 |
59 | kill_ganache_if_running() {
60 | # kill ganache-cli if running (kills node TODO: somehow kill only ganache)
61 | if pgrep -f /usr/bin/ganache-cli
62 | then
63 | pkill -9 -f /usr/bin/ganache-cli
64 | fi
65 | }
66 |
67 | install_solc() {
68 | # set specified solc version for truffle if present
69 | if [ ! -z "$SOLC_V" ]
70 | then
71 | echo "!!================================================================================!!"
72 | echo "Please do not use -s with truffle 5, but set the correct solc version in truffle.js"
73 | echo "!!================================================================================!!"
74 | exit
75 | fi
76 | }
77 |
78 | extract_transactions() {
79 | extract_script=$PWD"/build/extract.js"
80 |
81 | # move to truffle directory and deploy contracts
82 | cd ${TRUFFLE_DIR}
83 | # convert truffle dir to absolute path
84 | TRUFFLE_DIR=$PWD
85 | printf "\n${YELLOW} deploying contracts on Ganache${NC}\n"
86 | rm -rf build
87 | truffle deploy # > /dev/null TODO
88 | printf "\n${GREEN} contracts has been deployed on Ganache${NC}\n"
89 | # execute transaction extraction javascript in truffle console
90 | truffle compile
91 | printf "\n${YELLOW} extracting transactions ${NC}\n"
92 | truffle exec ${extract_script}
93 | printf "\n${GREEN} transactions has been extracted${NC}\n"
94 | # rename transactions file according to project VERSION
95 | mv ${TRUFFLE_DIR}/transactions.json ${TRUFFLE_DIR}/fuzz_config/transactions_$VERSION.json
96 | }
97 |
98 | # check if truffle directories exist
99 | for i in "${TRUFFLE_DIR}"
100 | do
101 | if [ ! -d $i ]; then
102 | printf "\n${RED}Truffle directory: ${NC}$i ${RED} doesn't exist ${NC}\n"
103 | exit 1
104 | fi
105 | done
106 |
107 | mkdir -p build/gen
108 | mkdir -p ${TRUFFLE_DIR}/fuzz_config
109 | # write metadata in file
110 | metadata_JSON=${TRUFFLE_DIR}/fuzz_config/metadata_$VERSION.json
111 | metadata="{\n\t\"tuffleProjDir\": \"${TRUFFLE_DIR}\",
112 | \t\"transactions\": \"${TRUFFLE_DIR}/fuzz_config/transactions_${VERSION}.json\",
113 | \t\"accounts\": \"${TRUFFLE_DIR}/fuzz_config/accounts.json\",
114 | \t\"config\": \"${TRUFFLE_DIR}/fuzz_config/config.json\"
115 | }"
116 | printf "$metadata" > $metadata_JSON
117 |
118 | # Create default configs if they don't exist
119 | if [ ! -f "${TRUFFLE_DIR}/fuzz_config/config.json" ]; then
120 | cp ${PWD}/config/config.json ${TRUFFLE_DIR}/fuzz_config/
121 | fi
122 |
123 | if [ ! -f "${TRUFFLE_DIR}/fuzz_config/accounts.json" ]; then
124 | cp ${PWD}/config/accounts.json ${TRUFFLE_DIR}/fuzz_config/
125 | fi
126 |
127 | # remove transactions json files if exists
128 | if [ -f "${TRUFFLE_DIR}/fuzz_config/transactions_${VERSION}.json" ]; then
129 | rm "${TRUFFLE_DIR}/fuzz_config/transactions_${VERSION}.json"
130 | fi
131 |
132 | kill_ganache_if_running
133 |
134 | # install specified version of solc
135 | install_solc
136 |
137 | go_project_dir=$PWD
138 |
139 | # run ganache-cli on background
140 | python3 $PWD"/build/ganache.py" "${TRUFFLE_DIR}/fuzz_config/accounts.json" > /dev/null &
141 |
142 | extract_transactions
143 |
144 | kill_ganache_if_running
145 |
146 | printf "\t${CYAN}Project metadata was written to: ${GREEN}${metadata_JSON} ${NC}\n"
147 | sleep .5
148 | printf "\t${CYAN} Done. Time to run: ${GREEN} ./build/bin/fuzzer --metadata ${metadata_JSON} --limit 10000 ${NC}\n"
149 |
--------------------------------------------------------------------------------
/build/ganache.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import json
4 | import subprocess
5 | import sys
6 | from pprint import pprint
7 |
8 | print(sys.argv)
9 | if len(sys.argv) < 2:
10 | print("you must provide accounts file")
11 | exit(1)
12 |
13 | # read the accounts (key, balance) and start ganache-cli with those accounts
14 | cmd = ""
15 | with open(sys.argv[1]) as f:
16 | data = json.load(f)
17 | for account in data['accounts']:
18 | cmd = "{} --account=\"0x{},{}\"".format(cmd, account['key'], account['amount'])
19 |
20 | process = subprocess.call(["ganache-cli --allowUnlimitedContractSize --gasLimit 0xfffffffffff {} > /dev/null".format(cmd)], shell=True)
21 |
--------------------------------------------------------------------------------
/build/patch:
--------------------------------------------------------------------------------
1 | diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go
2 | index 66f533102..151a0a66b 100644
3 | --- a/cmd/utils/flags.go
4 | +++ b/cmd/utils/flags.go
5 | @@ -1559,6 +1559,7 @@ func MakeGenesis(ctx *cli.Context) *core.Genesis {
6 |
7 | // MakeChain creates a chain manager from set command line flags.
8 | func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chainDb ethdb.Database) {
9 | + os.Exit(1)
10 | var err error
11 | chainDb = MakeChainDatabase(ctx, stack)
12 | config, _, err := core.SetupGenesisBlock(chainDb, MakeGenesis(ctx))
13 | diff --git a/consensus/ethash/consensus.go b/consensus/ethash/consensus.go
14 | index 62e3f8fca..9a199a39c 100644
15 | --- a/consensus/ethash/consensus.go
16 | +++ b/consensus/ethash/consensus.go
17 | @@ -311,6 +311,7 @@ func (ethash *Ethash) CalcDifficulty(chain consensus.ChainReader, time uint64, p
18 | // the difficulty that a new block should have when created at time
19 | // given the parent block's time and difficulty.
20 | func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int {
21 | + return big.NewInt(1)
22 | next := new(big.Int).Add(parent.Number, big1)
23 | switch {
24 | case config.IsConstantinople(next):
25 | diff --git a/consensus/ethash/ethash.go b/consensus/ethash/ethash.go
26 | index 78892e1da..5fcda7b57 100644
27 | --- a/consensus/ethash/ethash.go
28 | +++ b/consensus/ethash/ethash.go
29 | @@ -50,7 +50,7 @@ var (
30 | two256 = new(big.Int).Exp(big.NewInt(2), big.NewInt(256), big.NewInt(0))
31 |
32 | // sharedEthash is a full instance that can be shared between multiple users.
33 | - sharedEthash = New(Config{"", 3, 0, "", 1, 0, ModeNormal}, nil, false)
34 | + // sharedEthash = New(Config{"", 3, 0, "", 1, 0, ModeNormal}, nil, false)
35 |
36 | // algorithmRevision is the data structure version used for file naming.
37 | algorithmRevision = 23
38 | @@ -470,6 +470,7 @@ type Ethash struct {
39 | // remote mining, also optionally notifying a batch of remote services of new work
40 | // packages.
41 | func New(config Config, notify []string, noverify bool) *Ethash {
42 | + panic("Creation of full-sized Hash requested")
43 | if config.CachesInMem <= 0 {
44 | log.Warn("One ethash cache must always be in memory", "requested", config.CachesInMem)
45 | config.CachesInMem = 1
46 | @@ -565,7 +566,8 @@ func NewFullFaker() *Ethash {
47 | // NewShared creates a full sized ethash PoW shared between all requesters running
48 | // in the same process.
49 | func NewShared() *Ethash {
50 | - return &Ethash{shared: sharedEthash}
51 | + return NewFaker()
52 | +// return &Ethash{shared: sharedEthash}
53 | }
54 |
55 | // Close closes the exit channel to notify all backend threads exiting.
56 | diff --git a/core/chain_makers.go b/core/chain_makers.go
57 | index 0b5a3d184..fe012e0b0 100644
58 | --- a/core/chain_makers.go
59 | +++ b/core/chain_makers.go
60 | @@ -266,6 +266,38 @@ func makeBlockChain(parent *types.Block, n int, engine consensus.Engine, db ethd
61 | return blocks
62 | }
63 |
64 | +
65 | +func ExpNewCanonical(engine consensus.Engine, n int, full bool) (ethdb.Database, *BlockChain, error) {
66 | + return newCanonical(engine, n, full)
67 | +}
68 | +
69 | +// newCanonical creates a chain database, and injects a deterministic canonical
70 | +// chain. Depending on the full flag, if creates either a full block chain or a
71 | +// header only chain.
72 | +func newCanonical(engine consensus.Engine, n int, full bool) (ethdb.Database, *BlockChain, error) {
73 | + var (
74 | + db = ethdb.NewMemDatabase()
75 | + genesis = new(Genesis).MustCommit(db)
76 | + )
77 | +
78 | + // Initialize a fresh chain with only a genesis block
79 | + blockchain, _ := NewBlockChain(db, nil, params.AllEthashProtocolChanges, engine, vm.Config{}, nil)
80 | + // Create and inject the requested chain
81 | + if n == 0 {
82 | + return db, blockchain, nil
83 | + }
84 | + if full {
85 | + // Full block-chain requested
86 | + blocks := makeBlockChain(genesis, n, engine, db, 1)
87 | + _, err := blockchain.InsertChain(blocks)
88 | + return db, blockchain, err
89 | + }
90 | + // Header-only chain requested
91 | + headers := makeHeaderChain(genesis.Header(), n, engine, db, 1)
92 | + _, err := blockchain.InsertHeaderChain(headers, 1)
93 | + return db, blockchain, err
94 | +}
95 | +
96 | type fakeChainReader struct {
97 | config *params.ChainConfig
98 | genesis *types.Block
99 | diff --git a/core/state/state_object.go b/core/state/state_object.go
100 | index f41ab0409..76ccddf02 100644
101 | --- a/core/state/state_object.go
102 | +++ b/core/state/state_object.go
103 | @@ -88,6 +88,10 @@ type stateObject struct {
104 | deleted bool
105 | }
106 |
107 | +func (s *stateObject) GetTrie() Trie {
108 | + return s.trie
109 | +}
110 | +
111 | // empty returns whether the account is considered empty.
112 | func (s *stateObject) empty() bool {
113 | return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash)
114 | diff --git a/eth/backend.go b/eth/backend.go
115 | index 6a136182a..5ffccbbed 100644
116 | --- a/eth/backend.go
117 | +++ b/eth/backend.go
118 | @@ -233,11 +233,16 @@ func CreateConsensusEngine(ctx *node.ServiceContext, chainConfig *params.ChainCo
119 | if chainConfig.Clique != nil {
120 | return clique.New(chainConfig.Clique, db)
121 | }
122 | + config.PowMode = ethash.ModeFake
123 | // Otherwise assume proof-of-work
124 | switch config.PowMode {
125 | case ethash.ModeFake:
126 | log.Warn("Ethash used in fake mode")
127 | return ethash.NewFaker()
128 | + case config.PowMode == ethash.ModeFullFake:
129 | + log.Warn("Ethash used in full fake mode")
130 | + engine := ethash.NewFullFaker()
131 | + return engine
132 | case ethash.ModeTest:
133 | log.Warn("Ethash used in test mode")
134 | return ethash.NewTester(nil, noverify)
135 | diff --git a/ethdb/memory_database.go b/ethdb/memory_database.go
136 | index 727f2f7ca..18eac6a3f 100644
137 | --- a/ethdb/memory_database.go
138 | +++ b/ethdb/memory_database.go
139 | @@ -43,6 +43,10 @@ func NewMemDatabaseWithCap(size int) *MemDatabase {
140 | }
141 | }
142 |
143 | +func (db *MemDatabase) GetDB() map[string][]byte{
144 | + return db.db;
145 | +}
146 | +
147 | func (db *MemDatabase) Put(key []byte, value []byte) error {
148 | db.lock.Lock()
149 | defer db.lock.Unlock()
150 |
--------------------------------------------------------------------------------
/config/accounts.json:
--------------------------------------------------------------------------------
1 | {
2 | "accounts": [
3 | {
4 | "key": "1c6dbb1fe61bbb7c256f0ffcbd34087e211173dbc8454220b8b166ed6ada5c00",
5 | "amount": 100000000000000000000000000000
6 | },
7 | {
8 | "key": "b1cff43bf95333788b080b6cd5c5e2fcbe321ccd4132ed80cb3e72478c69e9a7",
9 | "amount": 100000000000000000000000000001
10 | },
11 | {
12 | "key": "aa3eeb453426d9c9292f89be5fa7e6caa0330d312255f84c0caa6764ae1adf00",
13 | "amount": 100000000000000000000000000002
14 | },
15 | {
16 | "key": "34a5a824b045c9ce797589d334394c11ee28d9cd8757f1a9b0ccf0fd0008c641",
17 | "amount": 100000000000000000000000000003
18 | },
19 | {
20 | "key": "a7a163dcb33958498cf5736282f53e39bd6cb7a58f5d4a948445dc86faa34f90",
21 | "amount": 100000000000000000000000000004
22 | },
23 | {
24 | "key": "a98b4df37871a2019093bf0226e0b125696072a6609c4865c02593cb3a32e4ac",
25 | "amount": 100000000000000000000000000005
26 | },
27 | {
28 | "key": "2cc883a2b2633dfd15c291f94665f814f1a00c238be1803867412f60b8464a9e",
29 | "amount": 100000000000000000000000000006
30 | },
31 | {
32 | "key": "a137fcd97f7b8662bcbcb4f94cbfaed970de9f21e2c9cc4bab931e6abc8a2d81",
33 | "amount": 100000000000000000000000000007
34 | },
35 | {
36 | "key": "404dcae8703253d3a1cf05b4c408871780f5a074698fe4776c3fcb60b8604415",
37 | "amount": 100000000000000000000000000008
38 | },
39 | {
40 | "key": "a26c4fdda6f32fa1fcd6aef8569dea6baee866a8494e809cd3777a247a2a0034",
41 | "amount": 100000000000000000000000000009
42 | },
43 | {
44 | "key": "d8f407b39c5c4a927568014d1decec558a0753b0671f15f9808a90c3af8b5e41",
45 | "amount": 100000000000000000000000000010
46 | },
47 | {
48 | "key": "327c7aba380bf2f32070e1a94d1db706c08dca1fe294ba9f147ef196142c97d2",
49 | "amount": 100000000000000000000000000011
50 | },
51 | {
52 | "key": "25a8f5cb535ce026a918cb1957f21cf94b488cb0fedf97d2586b0a20766ccdd4",
53 | "amount": 100000000000000000000000000012
54 | },
55 | {
56 | "key": "82ecabd2b6c431ef0d15fc28173a6a0d04ec29036a9e2ae63f7b6effaf1b78f4",
57 | "amount": 100000000000000000000000000013
58 | },
59 | {
60 | "key": "cecbb3e8882ca3d5d00c7195833205d591f80ed84578f40d675a94bcc60641a2",
61 | "amount": 100000000000000000000000000014
62 | },
63 | {
64 | "key": "2bae00bb1faa61071dd84dc4e9b6dcbf61d13a4e7da6b852b465dfa8f4a4dfbf",
65 | "amount": 100000000000000000000000000015
66 | },
67 | {
68 | "key": "67c710927a13093aa090332a647d675ac4b3a101e952147ff711a144657a9c68",
69 | "amount": 100000000000000000000000000016
70 | },
71 | {
72 | "key": "c458f805686afdd46651688f2b2877b95eaa6d13645ff5d3addb06bfc601993f",
73 | "amount": 100000000000000000000000000017
74 | },
75 | {
76 | "key": "be117fa7d717acbd4607657899861bd341ba1b5151de8c5984c2626b5c484b6c",
77 | "amount": 100000000000000000000000000018
78 | },
79 | {
80 | "key": "ebf3a5b70776360b8b88e1178d14ee885787a4454a17b489f96deda93fbaa8a1",
81 | "amount": 100000000000000000000000000019
82 | }
83 | ]
84 | }
85 |
--------------------------------------------------------------------------------
/config/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "Contract": {
3 | "ignore": ["method", "method1"],
4 | "timestamps": [1503756000, 1803756000]
5 | },
6 | "SomeToken": {
7 | "ignore": ["name", "symbol", "decimals", "pause", "unpause", "renounceOwnership", "transferOwnership"]
8 | },
9 | "Migrations": {
10 | "ignore_all": true
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/fuzzer/fuzzer.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package main
23 |
24 | import (
25 | "fmt"
26 | "math/big"
27 | "os"
28 | "runtime"
29 | "runtime/pprof"
30 | "time"
31 | "strings"
32 |
33 | "fuzzer/argpool"
34 | "fuzzer/utils"
35 |
36 | "github.com/ethereum/go-ethereum/log"
37 | "gopkg.in/urfave/cli.v1"
38 | )
39 |
40 | const (
41 | LatestStateRootKey = "evm:LatestStateRootKey"
42 | )
43 |
44 | var (
45 | app *cli.App
46 | logLevelFlag = cli.IntFlag{
47 | Name: "loglevel",
48 | Usage: "log level to emit to the screen",
49 | Value: int(log.LvlInfo),
50 | }
51 | metadataFileFlag = cli.StringFlag{
52 | Name: "metadata",
53 | Usage: "metadata file of truffle project to fuzz (generated from extract.sh script)",
54 | Value: "",
55 | }
56 | contractFlag = cli.StringFlag{
57 | Name: "contract",
58 | Usage: "name of contract to fuzz",
59 | Value: "",
60 | }
61 | limitFlag = cli.IntFlag{
62 | Name: "limit",
63 | Usage: "stop fuzzing after specified number of transactions",
64 | Value: 10000,
65 | }
66 | // optimizations mode is encoded in bits (similar to unix file permissions)
67 | // see OptMode struct
68 | optimizationsFlag = cli.IntFlag{
69 | Name: "o",
70 | Usage: "bitset of optimizations mode (check struct OptMode for more)",
71 | Value: 0,
72 | }
73 | interactiveModeFlag = cli.BoolFlag{
74 | Name: "it",
75 | Usage: "Interactive mode for guiding fuzzer/checking state",
76 | // Value: false,
77 | }
78 | // number of accounts to be used additionally to what is was during deployment
79 | accountsFlag = cli.IntFlag{
80 | Name: "a",
81 | Usage: "number of accounts to use during fuzzing (additionally to what is was during deployment)",
82 | Value: 1,
83 | }
84 | cpuProfileFlag = cli.StringFlag{
85 | Name: "cpuprofile",
86 | // example --cpuprofile cpu.prof
87 | Usage: "flag for profiling cpu, specify filename to save profile",
88 | Value: "",
89 | }
90 | memProfileFlag = cli.StringFlag{
91 | Name: "memprofile",
92 | Usage: "flag for profiling memory, specify filename to save profile",
93 | Value: "",
94 | }
95 | )
96 |
97 | type Flags struct {
98 | Metadata string
99 | Contract string
100 | Limit int
101 | Interactive bool
102 | OptMode *utils.OptMode
103 | Accounts int
104 | LogLevel int
105 | }
106 |
107 | func init() {
108 | app = cli.NewApp()
109 | app.Name = "Fuzzer"
110 | app.Author = "ChainSecurity"
111 | app.Email = "contact@chainsecurity.com"
112 | app.Version = "0.1"
113 | app.Usage = "Fuzzing Ethereum smart contracts"
114 | app.Flags = []cli.Flag{
115 | metadataFileFlag,
116 | contractFlag,
117 | limitFlag,
118 | optimizationsFlag,
119 | interactiveModeFlag,
120 | logLevelFlag,
121 | cpuProfileFlag,
122 | memProfileFlag,
123 | }
124 | app.Action = run
125 | }
126 |
127 | func getCLFlags(ctx *cli.Context) *Flags {
128 | metadata := ctx.GlobalString(metadataFileFlag.Name)
129 | if metadata == "" {
130 | log.Error("please provide metadata file with --metadata option")
131 | os.Exit(1)
132 | }
133 | contract := ctx.GlobalString(contractFlag.Name)
134 | if contract == "" {
135 | log.Warn("Contract was not provided (you can use --contract option)")
136 | }
137 | limit := ctx.GlobalInt(limitFlag.Name)
138 | optimizations := ctx.GlobalInt(optimizationsFlag.Name)
139 | optMode := &utils.OptMode{}
140 | optMode.SetFlag(optimizations)
141 | accounts := ctx.GlobalInt(accountsFlag.Name)
142 |
143 | return &Flags{
144 | Metadata: metadata,
145 | Contract: contract,
146 | Limit: limit,
147 | Interactive: ctx.GlobalBool(interactiveModeFlag.Name),
148 | OptMode: optMode,
149 | Accounts: accounts,
150 | LogLevel: ctx.Int(logLevelFlag.Name),
151 | }
152 | }
153 |
154 | func getCoverage(metadata string, contract string, backend *utils.Backend) (int, int) {
155 | indices := utils.GetOpcodeIndices(metadata, contract)
156 | contractAddress := backend.DeployedContracts[contract].Addresses[0]
157 | coveredIndices := backend.OpcodeIndices[contractAddress]
158 | return len(coveredIndices), len(indices)
159 | }
160 |
161 | // resets all global variables that are used for caching
162 | // only useful when testing several projects at the same time
163 | func Reset() {
164 | utils.ResetContractData()
165 | argpool.ResetArgPool()
166 | }
167 |
168 | func fuzz(ctx *cli.Context) {
169 | flags := getCLFlags(ctx)
170 | argPool := argpool.GetArgPool()
171 | backend := utils.NewBackend(flags.Metadata, argPool)
172 | result := make(utils.ResultsMap)
173 | utils.SnapshotBackend(backend)
174 |
175 | // start timer
176 | start := time.Now()
177 |
178 | options := &utils.Options{
179 | UpdateCoverage: true,
180 | CheckDeployedContract: false,
181 | UpdateArgPool: true,
182 | }
183 |
184 | // initial transactions to cover corner cases:
185 | // - fallbacks for all contracts
186 | // - paying non-payable methods
187 | for contract, _ := range backend.DeployedContracts {
188 | if contract == "Migrations" {
189 | continue
190 | }
191 | hint := &utils.Hint{Contract: contract, Fallback: true}
192 | utils.Rec(backend, argPool, hint, options, result, flags.OptMode, 0)
193 | for _, method := range backend.DeployedContracts[contract].Methods {
194 | // send ether to all un-payable function except fuzz_always_true
195 | if !utils.IsPayable(contract, method) && strings.Index(method, "fuzz_always_true") != 0 {
196 | hint = &utils.Hint{Contract: contract, Method: method, Amount: big.NewInt(1)}
197 | utils.Rec(backend, argPool, hint, options, result, flags.OptMode, 0)
198 | }
199 | }
200 | }
201 |
202 | backend.TxCount = 0
203 | // increase limit by number of deployment transactions
204 | flags.Limit = flags.Limit + backend.TxCount
205 | for i := backend.TxCount; i < flags.Limit; i++ {
206 | // ADVICED NOT TO SPECIFY HINT FOR ALL TRANSACTIONS (in Hint obj)
207 | // even when you only want to test specific contract extracted values
208 | // from other contracts are important for fuzzing main contract
209 | hint := &utils.Hint{}
210 | terminate := utils.Rec(backend, argPool, hint, options, result, flags.OptMode, 0)
211 | if terminate || backend.TxCount > flags.Limit {
212 | break
213 | }
214 | if flags.OptMode.SnapshotsEnabled && (i&8192 != 0) {
215 | utils.RevertBackend(backend)
216 | }
217 |
218 | if flags.LogLevel <= int(log.LvlInfo) {
219 | fmt.Printf("\rTransactions: %v/%v, %v%%", backend.TxCount, flags.Limit, 100.0*backend.TxCount/flags.Limit)
220 | }
221 | }
222 | fmt.Println()
223 |
224 | // stop timer, and check coverage
225 | elapsed := time.Since(start)
226 | log.Info("Calculating coverage. (needs to read and analyse bytecode opcodes)")
227 | for contract, _ := range backend.DeployedContracts {
228 | if result[contract] == nil {
229 | continue
230 | }
231 |
232 | covered, total := getCoverage(flags.Metadata, contract, backend)
233 | s := fmt.Sprintf("%v/%v, %v%%", covered, total, 100.0*covered/total)
234 | result[contract]["covered"] = s
235 | }
236 |
237 | log.Info(fmt.Sprintf("Fuzzing result: %+v", utils.PrettyPrint(result)))
238 | log.Trace(fmt.Sprintf("Arg pool sizes: %+v", utils.PrettyPrint(argPool.GetSizes())))
239 | if flags.OptMode.GenStatistics {
240 | log.Info(fmt.Sprintf("Stats: %+v", utils.PrettyPrint(backend.Stats.GetStats())))
241 | }
242 |
243 | log.Info(fmt.Sprintf("fuzzed: %v tx in %.2fsec. (rate: %.2f tx/s)",
244 | backend.TxCount, elapsed.Seconds(), float64(backend.TxCount)/elapsed.Seconds(),
245 | ))
246 | }
247 |
248 | func run(ctx *cli.Context) error {
249 | cpuprofile := ctx.GlobalString(cpuProfileFlag.Name)
250 | if cpuprofile != "" {
251 | f, err := os.Create(cpuprofile)
252 | if err != nil {
253 | log.Error(fmt.Sprintf("could not create CPU profile: ", err))
254 | }
255 | if err := pprof.StartCPUProfile(f); err != nil {
256 | log.Error(fmt.Sprintf("could not start CPU profile: ", err))
257 | }
258 | defer pprof.StopCPUProfile()
259 | }
260 |
261 | log.Root().SetHandler(log.LvlFilterHandler(
262 | log.Lvl(ctx.Int(logLevelFlag.Name)),
263 | log.StreamHandler(os.Stderr, log.TerminalFormat(true)),
264 | ))
265 | fuzz(ctx)
266 |
267 | memprofile := ctx.GlobalString(memProfileFlag.Name)
268 | if memprofile != "" {
269 | f, err := os.Create(memprofile)
270 | if err != nil {
271 | log.Error(fmt.Sprintf("could not create memory profile: ", err))
272 | }
273 | runtime.GC() // get up-to-date statistics
274 | if err := pprof.WriteHeapProfile(f); err != nil {
275 | log.Error(fmt.Sprintf("could not write memory profile: ", err))
276 | }
277 | f.Close()
278 | }
279 | return nil
280 | }
281 |
282 | func main() {
283 | if err := app.Run(os.Args); err != nil {
284 | fmt.Fprintln(os.Stderr, err)
285 | os.Exit(1)
286 | }
287 | }
288 |
--------------------------------------------------------------------------------
/utils/accounts.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package utils
23 |
24 | import (
25 | "crypto/ecdsa"
26 | "encoding/json"
27 | "fmt"
28 | "io/ioutil"
29 | "math/big"
30 | "math/rand"
31 |
32 | "github.com/ethereum/go-ethereum/common"
33 | "github.com/ethereum/go-ethereum/crypto"
34 | )
35 |
36 | // non exported structure used only for parsing accounts json
37 | type accountJSON struct {
38 | Key string `json:"key"`
39 | Amount *big.Int `json:"amount"`
40 | }
41 |
42 | // non exported structure used only for parsing accounts json
43 | type profileJSON struct {
44 | Accounts []accountJSON `json:"accounts"`
45 | }
46 |
47 | type Account struct {
48 | Key *ecdsa.PrivateKey
49 | Address common.Address
50 | Amount *big.Int
51 | // field to mark if account was used during deployment
52 | Used bool
53 | }
54 |
55 | var (
56 | accounts []Account
57 | keyToAddress map[ecdsa.PrivateKey]common.Address
58 | addressToKey map[common.Address]*ecdsa.PrivateKey
59 | )
60 |
61 | func GetAddressFromKey(key ecdsa.PrivateKey) common.Address {
62 | if address, found := keyToAddress[key]; found {
63 | return address
64 | }
65 | panic(fmt.Sprintf("key: %v was not found in accounts", key))
66 | }
67 |
68 | func GetKeyFromAddress(address common.Address) *ecdsa.PrivateKey {
69 | if key, found := addressToKey[address]; found {
70 | return key
71 | }
72 | panic(fmt.Sprintf("address: %v was not found in accounts", address))
73 | }
74 |
75 | func GetAccountFromAddress(address common.Address) *Account {
76 | for i := 0; i < len(accounts); i++ {
77 | if accounts[i].Address == address {
78 | return &accounts[i]
79 | }
80 | }
81 | panic(fmt.Sprintf("account wasn't found for address: %v", address))
82 | }
83 |
84 | // singleton pattern
85 | // reads accounts from JSON file and returns array of accounts
86 | // containing Key, Address and initial Balance for account
87 | func ReadAccounts(metadata string) []Account {
88 | if accounts != nil {
89 | return accounts
90 | }
91 | f := getAccountsJSONFile(metadata)
92 | accountsJSON, err := ioutil.ReadFile(f)
93 | if err != nil {
94 | panic(fmt.Errorf("error reading accounts file: %v %+v\n", f, err))
95 | }
96 | var p profileJSON
97 | err = json.Unmarshal(accountsJSON, &p)
98 | if err != nil {
99 | panic(err)
100 | }
101 | accounts = make([]Account, 0)
102 | keyToAddress = make(map[ecdsa.PrivateKey]common.Address)
103 | addressToKey = make(map[common.Address]*ecdsa.PrivateKey)
104 | for _, account := range p.Accounts {
105 | key, err := crypto.HexToECDSA(account.Key)
106 | if err != nil {
107 | panic(fmt.Errorf("Incorrect hex key: %+v", err))
108 | }
109 | acc := Account{
110 | Key: key,
111 | Address: crypto.PubkeyToAddress(key.PublicKey),
112 | Amount: account.Amount,
113 | }
114 | accounts = append(accounts, acc)
115 | addressToKey[acc.Address] = acc.Key
116 | keyToAddress[*acc.Key] = acc.Address
117 | }
118 | return accounts
119 | }
120 |
121 | func GetRandAccount(metadata string) Account {
122 | n := len(ReadAccounts(metadata))
123 | return ReadAccounts(metadata)[rand.Intn(n)]
124 | }
125 |
126 | func init() {
127 | }
128 |
--------------------------------------------------------------------------------
/utils/args.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package utils
23 |
24 | import (
25 | "fmt"
26 | "math"
27 | "math/big"
28 | "math/rand"
29 | "reflect"
30 |
31 | "fuzzer/argpool"
32 |
33 | "github.com/ethereum/go-ethereum/accounts/abi"
34 | "github.com/ethereum/go-ethereum/common"
35 | "github.com/ethereum/go-ethereum/log"
36 | )
37 |
38 | func fillRecursively(T reflect.Type, argPool *argpool.ArgPool) reflect.Value {
39 | var ret reflect.Value
40 | ret = reflect.New(T).Elem()
41 |
42 | switch T {
43 | case Int8Type:
44 | return reflect.ValueOf(argPool.NextInt8())
45 | case UInt8Type:
46 | return reflect.ValueOf(uint8(argPool.NextInt8()))
47 | case Int16Type:
48 | return reflect.ValueOf(argPool.NextInt16())
49 | case UInt16Type:
50 | return reflect.ValueOf(uint16(argPool.NextInt16()))
51 | case Int32Type:
52 | return reflect.ValueOf(argPool.NextInt32())
53 | case UInt32Type:
54 | return reflect.ValueOf(uint32(argPool.NextInt32()))
55 | case Int64Type:
56 | return reflect.ValueOf(argPool.NextInt64())
57 | case UInt64Type:
58 | return reflect.ValueOf(uint64(argPool.NextInt64()))
59 | case Bytes32Type:
60 | return reflect.ValueOf(argPool.NextBytes32())
61 | case AddressType:
62 | return reflect.ValueOf(argPool.NextAddress())
63 | case StringType:
64 | return reflect.ValueOf(argPool.NextString())
65 | case BoolType:
66 | x := rand.Int() % 2
67 | if x == 0 {
68 | reflect.ValueOf(true)
69 | }
70 | return reflect.ValueOf(false)
71 | case BigIntType:
72 | return reflect.ValueOf(argPool.NextBigInt())
73 | }
74 |
75 | if T.Kind() == reflect.Array {
76 | for i := 0; i < T.Len(); i++ {
77 | val := fillRecursively(ret.Index(i).Type(), argPool)
78 | ret.Index(i).Set(val)
79 | }
80 | return ret
81 | }
82 | if T.Kind() == reflect.Slice {
83 | len := (rand.Int() & 15) + 1
84 | for i := 0; i < len; i++ {
85 | val := fillRecursively(T.Elem(), argPool)
86 | ret = reflect.Append(ret, val)
87 | }
88 | return ret
89 | }
90 | panic(fmt.Sprintf("type: %v was not recognized", T))
91 | }
92 |
93 | func updateRecursively(val reflect.Value, argPool *argpool.ArgPool) {
94 | T := val.Type()
95 |
96 | switch T {
97 | case Int8Type, UInt8Type, BoolType:
98 | // ignore
99 | return
100 | case Int16Type:
101 | argPool.AddInt16(int16(val.Int()))
102 | return
103 | case UInt16Type:
104 | argPool.AddInt16(int16(val.Uint()))
105 | return
106 | case Int32Type:
107 | argPool.AddInt32(int32(val.Int()))
108 | return
109 | case UInt32Type:
110 | argPool.AddInt32(int32(val.Uint()))
111 | return
112 | case Int64Type:
113 | argPool.AddInt64(val.Int())
114 | return
115 | case UInt64Type:
116 | argPool.AddInt64(int64(val.Uint()))
117 | return
118 | case BigIntType:
119 | argPool.AddBigInt(val.Interface().(*big.Int))
120 | return
121 | case AddressType:
122 | argPool.AddAddress(val.Interface().(common.Address))
123 | return
124 | case StringType:
125 | argPool.AddString(val.String())
126 | return
127 | case Bytes32Type:
128 | argPool.AddBytes32(val.Interface().([32]byte))
129 | return
130 | }
131 |
132 | if T.Kind() == reflect.Array || T.Kind() == reflect.Slice {
133 | for i := 0; i < val.Len(); i++ {
134 | updateRecursively(val.Index(i), argPool)
135 | }
136 | return
137 | }
138 | }
139 |
140 | // Constructs arguments for function from ABI recursively
141 | func ConstructArgs(args []abi.Argument, argPool *argpool.ArgPool) []interface{} {
142 | var out []interface{}
143 | for _, arg := range args {
144 | val := fillRecursively(arg.Type.Type, argPool)
145 | out = append(out, val.Interface())
146 | }
147 | return out
148 | }
149 |
150 | // Updates corresponding pools with values returned from function
151 | // (e.g. if function returns stringpool and int8pool will be updated)
152 | func UpdatePool(input *LastTxInput, argPool *argpool.ArgPool, output []byte) {
153 | values, err := input.OutArgs.UnpackValues(output)
154 | if err != nil {
155 | log.Error(fmt.Sprintf("Error unpacking returned arguments: %+v\n", err))
156 | }
157 | for _, value := range values {
158 | updateRecursively(reflect.ValueOf(value), argPool)
159 | }
160 | }
161 |
162 | func InitArgPool(argPool *argpool.ArgPool, metadata string) {
163 | // adding dummy bigInt values (powers of 2)
164 | argPool.AddBigInt(big.NewInt(0))
165 | argPool.AddInt64(-1)
166 | for i := int64(1); i < 1E18; i = i * 2 {
167 | if i <= int64(math.MaxInt32) {
168 | argPool.AddInt32(int32(i))
169 | }
170 | if i <= int64(math.MaxInt16) {
171 | argPool.AddInt16(int16(i))
172 | }
173 | argPool.AddBigInt(big.NewInt(i))
174 | argPool.AddInt64(i)
175 | }
176 | // add random byte32 arrays
177 | for cnt := 0; cnt < 10; cnt++ {
178 | byteArr := [32]byte{}
179 | for i := 0; i < 32; i++ {
180 | byteArr[i] = byte(rand.Int() % 256)
181 | }
182 | argPool.AddBytes32(byteArr)
183 | }
184 | // adding dummy string
185 | argPool.AddString("ChainSecurity")
186 | // adding dummy byte/bytes
187 | for i := 0; i < 256; i++ {
188 | argPool.AddInt8(int8(i))
189 | argPool.AddInt16(int16(i))
190 | argPool.AddInt32(int32(i))
191 | argPool.AddInt64(int64(i))
192 | }
193 |
194 | accounts := ReadAccounts(metadata)
195 | // adding dummy addresses
196 | for _, account := range accounts {
197 | argPool.AddAddress(account.Address)
198 | argPool.AddBigInt(account.Amount)
199 | }
200 | }
201 |
--------------------------------------------------------------------------------
/utils/backend.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package utils
23 |
24 | import (
25 | "fmt"
26 | "math/big"
27 | "os"
28 |
29 | "fuzzer/argpool"
30 |
31 | "github.com/ethereum/go-ethereum/accounts/abi"
32 | "github.com/ethereum/go-ethereum/common"
33 | "github.com/ethereum/go-ethereum/consensus/ethash"
34 | "github.com/ethereum/go-ethereum/core"
35 | "github.com/ethereum/go-ethereum/core/state"
36 | "github.com/ethereum/go-ethereum/core/types"
37 | "github.com/ethereum/go-ethereum/core/vm"
38 | "github.com/ethereum/go-ethereum/log"
39 | "github.com/ethereum/go-ethereum/params"
40 | )
41 |
42 | var (
43 | maxGasPool = (new(core.GasPool).AddGas(8000000))
44 | coinBase = common.HexToAddress(NullAddress)
45 | )
46 |
47 | type LastTxInput struct {
48 | Contract string `json:"contract"`
49 | Method string `json:"method"`
50 | Const bool `json:"const:"`
51 | Ether *big.Int `json:"ether"`
52 | Input *[]interface{} `json:"arguments"`
53 | OutArgs abi.Arguments `json:"-"`
54 | Sender *common.Address `json:"from"`
55 | }
56 |
57 | type LastTxResult struct {
58 | Output []byte
59 | RevertAtDepth int
60 | AssertionAtDepth int
61 | Receipt *types.Receipt
62 | Overflow string
63 | StructLogger *vm.StructLogger
64 | }
65 |
66 | type Backend struct {
67 | BlockChain *core.BlockChain
68 | StateDB *state.StateDB
69 | ChainConfig *params.ChainConfig
70 | DeployedContracts map[string]*Contract
71 | // flattened list of deployed contracts for efficient random generation
72 | ContractsList []string
73 | // metadata file of truffle project that is being fuzzed
74 | Metadata string
75 | // input and output of last transaction
76 | LastTxIn *LastTxInput
77 | LastTxRes LastTxResult
78 |
79 | // instruction indices
80 | // set of indices for each contract to calculate coverage finally
81 | OpcodeIndices map[common.Address]map[uint64]bool
82 | // statistics about execution
83 | Stats Stats
84 | TxCount int
85 | }
86 |
87 | func (b *Backend) CommitTransaction(tx *types.Transaction,
88 | argPool *argpool.ArgPool, options *Options, header *types.Header) (
89 | error, []*types.Log) {
90 | b.TxCount = b.TxCount + 1
91 | b.LastTxRes.StructLogger = nil
92 | b.LastTxRes.Receipt = nil
93 | gasPool := *maxGasPool
94 | err, logs := b.commitTransaction(tx, b.BlockChain, coinBase, &gasPool,
95 | b.ChainConfig, b.StateDB, header, argPool, options,
96 | )
97 | return err, logs
98 | }
99 |
100 | func (b *Backend) commitTransaction(
101 | tx *types.Transaction,
102 | bc *core.BlockChain,
103 | coinbase common.Address,
104 | gp *core.GasPool,
105 | config *params.ChainConfig,
106 | state *state.StateDB,
107 | header *types.Header,
108 | argPool *argpool.ArgPool,
109 | options *Options,
110 | ) (error, []*types.Log) {
111 | snap := state.Snapshot()
112 |
113 | logconfig := &vm.LogConfig{
114 | DisableMemory: false,
115 | DisableStack: false,
116 | // Do not print evm log on console
117 | Debug: false,
118 | }
119 |
120 | b.LastTxRes.StructLogger = vm.NewStructLogger(logconfig)
121 | tracer := b.LastTxRes.StructLogger
122 | vmConfig := vm.Config{
123 | Debug: true,
124 | Tracer: tracer,
125 | }
126 | receipt, _, err := core.ApplyTransaction(config, bc, &coinbase, gp, state,
127 | header, tx, &header.GasUsed, vmConfig,
128 | )
129 | if err != nil {
130 | state.RevertToSnapshot(snap)
131 | log.Error(fmt.Sprintf("%v", err))
132 | return err, nil
133 | }
134 |
135 | b.processLogs(receipt, tx, argPool, options)
136 |
137 | return nil, receipt.Logs
138 | }
139 |
140 | // Returns blockchain, statedb and config for fast fuzzing
141 | // also: - initializes accounts: sets initial balances
142 | // - reads transactions extracted from truffle project
143 | // - specified in metadata file and applies to backend
144 | func NewBackend(metadata string, argPool *argpool.ArgPool) *Backend {
145 | GetABIMap(metadata)
146 | db, blockchain, err := core.ExpNewCanonical(ethash.NewFullFaker(), 1, true)
147 | if err != nil {
148 | panic(fmt.Errorf("error creating blockchain: %v\n", err))
149 | }
150 | statedb, _ := state.New(common.Hash{}, state.NewDatabase(db))
151 | // can't use TestChainConfig, because tracing doesn't work, IsEIP158() messes up stuff
152 | chainConfig := ¶ms.ChainConfig{
153 | ChainID: big.NewInt(1),
154 | HomesteadBlock: big.NewInt(0),
155 | DAOForkBlock: nil,
156 | DAOForkSupport: false,
157 | EIP150Block: big.NewInt(0),
158 | EIP150Hash: common.Hash{},
159 | EIP155Block: big.NewInt(0),
160 | EIP158Block: nil, //big.NewInt(0),
161 | ByzantiumBlock: big.NewInt(0),
162 | ConstantinopleBlock: nil,
163 | Ethash: new(params.EthashConfig),
164 | Clique: nil,
165 | }
166 | // read acccounts from JSON file and set initial balances
167 | // shadows global variable in this package (accounts.go)
168 | accounts := ReadAccounts(metadata)
169 | for _, account := range accounts {
170 | statedb.SetBalance(account.Address, account.Amount)
171 | }
172 |
173 | backend := &Backend{
174 | BlockChain: blockchain,
175 | StateDB: statedb,
176 | ChainConfig: chainConfig,
177 | DeployedContracts: make(map[string]*Contract),
178 | ContractsList: make([]string, 0),
179 | Metadata: metadata,
180 | OpcodeIndices: make(map[common.Address]map[uint64]bool),
181 | }
182 |
183 | // read transactions json file and apply transactions to backend
184 | for _, tx := range ReadTransactions(getTxJSONFile(metadata)) {
185 | backend.CommitTransaction(tx, argPool, &Options{
186 | UpdateCoverage: true,
187 | CheckDeployedContract: true,
188 | UpdateArgPool: false,
189 | ExtractTimestamps: true,
190 | }, GetDefaultHeader(backend))
191 | }
192 | InitArgPool(argPool, metadata)
193 | RemoveLibraries(backend)
194 |
195 | for contract, _ := range backend.DeployedContracts {
196 | for method := range GetContractABI(contract, metadata).Methods {
197 | backend.DeployedContracts[contract].Methods = append(backend.DeployedContracts[contract].Methods, method)
198 | }
199 | if contract != "Migrations" && len(GetContractABI(contract, backend.Metadata).Methods) > 0 {
200 | backend.ContractsList = append(backend.ContractsList, contract)
201 | }
202 | }
203 |
204 | ProcessConfig(metadata, argPool, backend)
205 | if len(backend.ContractsList) < 1 {
206 | log.Error(fmt.Sprintf("Truffle deployment script doesn't deploy any contract"))
207 | os.Exit(0)
208 | }
209 | return backend
210 | }
211 |
--------------------------------------------------------------------------------
/utils/contracts.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package utils
23 |
24 | import (
25 | "bytes"
26 | "encoding/hex"
27 | "encoding/json"
28 | "fmt"
29 | "io/ioutil"
30 | "math/rand"
31 | "strings"
32 |
33 | "fuzzer/argpool"
34 |
35 | "github.com/ethereum/go-ethereum/accounts/abi"
36 | "github.com/ethereum/go-ethereum/common"
37 | "github.com/ethereum/go-ethereum/core/asm"
38 | "github.com/ethereum/go-ethereum/log"
39 | )
40 |
41 | var (
42 | ContractHashes map[string]map[string]string
43 | DeployedBytecodes map[string]string
44 | ABIMap map[string]abi.ABI
45 | // in method ABI there's no information whether it's payable or not
46 | // so we keep that info in payable map: payable[contract][method]
47 | Payable map[string]map[string]bool
48 | Libraries map[string]bool
49 | // swarm hash prefix in bytecode
50 | bzzr0 = fmt.Sprintf("%x", append([]byte{0xa1, 0x65}, []byte("bzzr0")...))
51 | )
52 |
53 | type Contract struct {
54 | Addresses []common.Address
55 | Methods []string
56 | }
57 |
58 | // reset global maps, should be used when testing fuzzing
59 | // multiple projects is needed
60 | func ResetContractData() {
61 | ContractHashes = nil
62 | DeployedBytecodes = nil
63 | ABIMap = nil
64 | Payable = nil
65 | Libraries = nil
66 | }
67 |
68 | func IsPayable(contract, method string) bool {
69 | return Payable[contract][method]
70 | }
71 |
72 | // extracts swarm hash from deployment bytecode
73 | func GetSwarmHash(bytecode string) (string, bool) {
74 | idx := strings.LastIndex(bytecode, bzzr0)
75 | if idx == -1 {
76 | return "", false
77 | }
78 | swarmHash := bytecode[idx+len(bzzr0) : idx+len(bzzr0)+64]
79 | return swarmHash, true
80 | }
81 |
82 | func ReadDeployedBytecodes(metadata string) map[string]string {
83 | if DeployedBytecodes != nil {
84 | return DeployedBytecodes
85 | }
86 | DeployedBytecodes := make(map[string]string)
87 |
88 | truffleDir := getTruffleDir(metadata)
89 | files, err := ioutil.ReadDir(fmt.Sprintf("%v/build/contracts/", truffleDir))
90 | if err != nil {
91 | panic(fmt.Errorf("truffle project folder doesn't exist: %+v\n", err))
92 | }
93 | for _, f := range files {
94 | contractFile := fmt.Sprintf("%v/build/contracts/%v", truffleDir, f.Name())
95 | contractJSON, _ := ioutil.ReadFile(contractFile)
96 | var M map[string]string
97 | json.Unmarshal(contractJSON, &M)
98 | // trim 0x prefix from deployed code
99 | DeployedBytecodes[getFilename(f.Name())] = M["deployedBytecode"][2:]
100 | }
101 | return DeployedBytecodes
102 | }
103 |
104 | // returns map of ContractName -> Swarm hash (of deployment code)
105 | func ReadContractsHashes(metadata string) map[string]string {
106 | if ContractHashes == nil {
107 | ContractHashes = make(map[string]map[string]string)
108 | }
109 | if ContractHashes[metadata] != nil {
110 | return ContractHashes[metadata]
111 | }
112 | ContractHashes[metadata] = make(map[string]string)
113 |
114 | deployedCodes := ReadDeployedBytecodes(metadata)
115 | for filename, code := range deployedCodes {
116 | hash, found := GetSwarmHash(code)
117 | if !found {
118 | log.Trace(fmt.Sprintf("swarm hash was not found in contract ABI: %+v",
119 | filename,
120 | ))
121 | continue
122 | }
123 | ContractHashes[metadata][hash] = filename
124 | }
125 | return ContractHashes[metadata]
126 | }
127 |
128 | func GetContractNameByHash(hash string, metadata string) string {
129 | if contractName, found := ReadContractsHashes(metadata)[hash]; found {
130 | return contractName
131 | }
132 | panic(fmt.Sprintf("Contract with hash: %v was not found\n", hash))
133 | }
134 |
135 | // returns map of ContractName -> ABI (functs, events ... )
136 | func GetABIMap(metadata string) map[string]abi.ABI {
137 | if ABIMap != nil {
138 | return ABIMap
139 | }
140 | type JSONNode struct {
141 | ContractKind string `json:"contractKind,omitempty"`
142 | Name string `json:"name,omitempty"`
143 | }
144 | type JSONNodes struct {
145 | Nodes []JSONNode `json:"nodes"`
146 | }
147 | type JSONAST struct {
148 | ContractName string `json:"contractName"`
149 | AST JSONNodes `json:"ast"`
150 | }
151 | type JSONABI struct {
152 | ABI abi.ABI `json:"abi"`
153 | }
154 |
155 | truffleDir := getTruffleDir(metadata)
156 | ABIMap = make(map[string]abi.ABI)
157 | Payable = make(map[string]map[string]bool)
158 | Libraries = make(map[string]bool)
159 |
160 | files, err := ioutil.ReadDir(fmt.Sprintf("%v/build/contracts/", truffleDir))
161 | if err != nil {
162 | panic(fmt.Errorf("truffle project folder doesn't exist: %+v\n", err))
163 | }
164 | for _, f := range files {
165 | abiFile := fmt.Sprintf("%v/build/contracts/%v", truffleDir, f.Name())
166 | abiBytes, err := ioutil.ReadFile(abiFile)
167 | if err != nil {
168 | panic(fmt.Errorf("Error reading abi file: %+v\n", err))
169 | }
170 | dec := json.NewDecoder(strings.NewReader(string(abiBytes)))
171 | var ast JSONAST
172 | if err := dec.Decode(&ast); err != nil {
173 | panic(fmt.Errorf("Error processing contract ast: %+v\n", err))
174 | }
175 | for _, node := range ast.AST.Nodes {
176 | if node.ContractKind == "library" {
177 | Libraries[node.Name] = true
178 | }
179 | }
180 | // if contract is library ignore it's abi
181 | if _, ok := Libraries[ast.ContractName]; ok {
182 | continue
183 | }
184 | dec = json.NewDecoder(strings.NewReader(string(abiBytes)))
185 |
186 | var jsonABI JSONABI
187 | if err := dec.Decode(&jsonABI); err != nil {
188 | panic(fmt.Errorf("Error processing contract ABI: %+v\n", err))
189 | }
190 | evmABI := jsonABI.ABI
191 | filename := getFilename(f.Name())
192 | ABIMap[filename] = evmABI
193 | // Extract payable information about methods
194 | type method struct {
195 | Name string `json:"name"`
196 | Payable bool `json:"payable"`
197 | }
198 | type methods struct {
199 | Methods []method `json:"abi"`
200 | }
201 | dat := methods{}
202 | if err := json.Unmarshal(abiBytes, &dat); err != nil {
203 | panic(err)
204 | }
205 | Payable[filename] = make(map[string]bool)
206 | for _, method := range dat.Methods {
207 | Payable[filename][method.Name] = method.Payable
208 | }
209 | }
210 | return ABIMap
211 | }
212 |
213 | func GetContractABI(contract string, metadata string) abi.ABI {
214 | evmABI, found := GetABIMap(metadata)[contract]
215 | if !found {
216 | panic(fmt.Sprintf("Contract: %v not found", contract))
217 | }
218 | return evmABI
219 | }
220 |
221 | // returns abi of method
222 | func GetContractMethod(contract string, method string, metadata string) abi.Method {
223 | evmABI := GetContractABI(contract, metadata)
224 | if method == "" {
225 | return evmABI.Constructor
226 | }
227 | if abiMethod, found := evmABI.Methods[method]; found {
228 | return abiMethod
229 | }
230 | panic(fmt.Sprintf("Contract: %v, method: %v not found", contract, method))
231 | }
232 |
233 | func GetRandomContract(backend *Backend) string {
234 | size := len(backend.ContractsList)
235 | return backend.ContractsList[rand.Int()%size]
236 | }
237 |
238 | func GetRandomMethod(contract string, backend *Backend) string {
239 | methods := backend.DeployedContracts[contract].Methods
240 | return methods[rand.Int()%len(methods)]
241 | }
242 |
243 | // returns bytecode for contract method call with specified arguments
244 | func GetCallBytecode(contract string, method string, args []interface{},
245 | metadata string) []byte {
246 | evmABI := GetContractABI(contract, metadata)
247 |
248 | input, err := evmABI.Pack(method, args...)
249 | if err != nil {
250 | panic(fmt.Errorf("Error generating bytecode for method call: %v, err: %v\n",
251 | method, err,
252 | ))
253 | }
254 | return input
255 | }
256 |
257 | func GetOpcodeIndices(metadata string, contract string) []uint64 {
258 | bytecodes := ReadDeployedBytecodes(metadata)
259 | bytecode := bytecodes[contract]
260 | idx := strings.LastIndex(bytecode, bzzr0)
261 | // last opcode is STOP
262 | bytecode = bytecode[:idx-1]
263 | var res []uint64
264 | script, _ := hex.DecodeString(ReplacePlaceHolders(bytecode))
265 | it := asm.NewInstructionIterator(script)
266 | for it.Next() {
267 | res = append(res, it.PC())
268 | }
269 | return res
270 | }
271 |
272 | func deleteFromSlice(val string, a []string) []string {
273 | for i, s := range a {
274 | if s == val {
275 | a[i] = a[len(a)-1]
276 | return a[:len(a)-1]
277 | }
278 | }
279 | return a
280 | }
281 |
282 | func IgnoreContract(contract string, backend *Backend) {
283 | if _, found := backend.DeployedContracts[contract]; found {
284 | delete(backend.DeployedContracts, contract)
285 | backend.ContractsList = deleteFromSlice(contract, backend.ContractsList)
286 | }
287 | }
288 |
289 | func IgnoreContractMethod(contract string, method string, backend *Backend) {
290 | if _, found := backend.DeployedContracts[contract]; found {
291 | backend.DeployedContracts[contract].Methods = deleteFromSlice(
292 | method, backend.DeployedContracts[contract].Methods,
293 | )
294 | }
295 | }
296 |
297 | func ReplacePlaceHolders(bytecode string) string {
298 | var buffer bytes.Buffer
299 | for i := 0; i < len(bytecode); i++ {
300 | if bytecode[i] == '_' {
301 | i += 39
302 | buffer.WriteString("0000000000000000000000000000000000000000")
303 | continue
304 | }
305 | buffer.WriteString(string(bytecode[i]))
306 | }
307 | return buffer.String()
308 | }
309 |
310 | // reads config file and ignores all contract/method during fuzzing according
311 | // to configuration, adds timestamps from config to pool
312 | func ProcessConfig(metadata string, argPool *argpool.ArgPool, backend *Backend) {
313 | fuzzingConfig := GetConfig(metadata)
314 | for contract, config := range fuzzingConfig {
315 | log.Debug(fmt.Sprintf("Ignoring Config for Contract: %v - %v", contract, config))
316 | for _, timestamp := range config.Timestamps {
317 | argPool.AddTimestamp(timestamp)
318 | }
319 | if config.IgnoreAll {
320 | IgnoreContract(contract, backend)
321 | continue
322 | }
323 | for _, method := range config.IgnoredFunctions {
324 | log.Debug(fmt.Sprintf("For Contract %v ignoring %v", contract, method))
325 | IgnoreContractMethod(contract, method, backend)
326 | }
327 | }
328 | }
329 |
330 | func RemoveLibraries(backend *Backend) {
331 | for contract, _ := range Libraries {
332 | if _, ok := backend.DeployedContracts[contract]; ok {
333 | log.Debug(fmt.Sprintf("removing library: %v from deployed contracts", contract))
334 | delete(backend.DeployedContracts, contract)
335 | }
336 | }
337 | }
338 |
--------------------------------------------------------------------------------
/utils/generator.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package utils
23 |
24 | import (
25 | "crypto/ecdsa"
26 | "math/big"
27 |
28 | "fuzzer/argpool"
29 |
30 | "github.com/ethereum/go-ethereum/common"
31 | "github.com/ethereum/go-ethereum/core/types"
32 | )
33 |
34 | type Hint struct {
35 | Contract string
36 | Method string
37 | Args []interface{}
38 | Amount *big.Int
39 | Sender *common.Address
40 | // generate fallback transaction
41 | Fallback bool
42 | }
43 |
44 | func getRandomAmountFromAddress(address common.Address, argPool *argpool.ArgPool, backend *Backend) *big.Int {
45 | balance := backend.StateDB.GetBalance(address)
46 | ret := argPool.NextBigInt()
47 | for ret.Cmp(balance) >= 1 {
48 | ret = argPool.NextBigInt()
49 | }
50 | return ret
51 | }
52 |
53 | func GenTransaction(backend *Backend, argPool *argpool.ArgPool, hint *Hint) *types.Transaction {
54 | var (
55 | contract string
56 | method string
57 | args []interface{}
58 | senderAddress *common.Address
59 | senderKey *ecdsa.PrivateKey
60 | )
61 | if hint != nil && hint.Contract != "" {
62 | contract = hint.Contract
63 | } else {
64 | contract = GetRandomContract(backend)
65 | }
66 |
67 | if hint != nil && hint.Method != "" {
68 | method = hint.Method
69 | } else {
70 | method = GetRandomMethod(contract, backend)
71 | }
72 | if hint.Fallback {
73 | method = ""
74 | }
75 |
76 | contractAddress := backend.DeployedContracts[contract].Addresses[0]
77 | methodABI := GetContractMethod(contract, method, backend.Metadata)
78 | if hint != nil && hint.Args != nil {
79 | args = hint.Args
80 | } else {
81 | args = ConstructArgs(methodABI.Inputs, argPool)
82 | }
83 |
84 | input := GetCallBytecode(contract, method, args, backend.Metadata)
85 |
86 | if hint != nil && hint.Sender != nil {
87 | senderAddress = hint.Sender
88 | senderKey = GetKeyFromAddress(*senderAddress)
89 | } else {
90 | randAccount := GetRandAccount(backend.Metadata)
91 | senderAddress = &randAccount.Address
92 | senderKey = randAccount.Key
93 | }
94 | // only transfer ether if method is payable
95 | amount := big.NewInt(0)
96 | // for each payable function send ether once to cover that case in bytecode
97 | if hint != nil && hint.Amount != nil {
98 | amount = hint.Amount
99 | } else {
100 | if IsPayable(contract, method) {
101 | amount = getRandomAmountFromAddress(*senderAddress, argPool, backend)
102 | }
103 | }
104 |
105 | // save transaction details in hint object
106 | hint.Contract = contract
107 | hint.Method = method
108 | hint.Amount = amount
109 |
110 | tx := types.NewTransaction(backend.StateDB.GetNonce(*senderAddress),
111 | contractAddress,
112 | amount,
113 | uint64(*maxGasPool),
114 | big.NewInt(0),
115 | input,
116 | )
117 | signed_tx, _ := types.SignTx(tx, types.HomesteadSigner{}, senderKey)
118 | backend.LastTxIn = &LastTxInput{
119 | Contract: contract,
120 | Method: method,
121 | Const: methodABI.Const,
122 | Ether: amount,
123 | Input: &args,
124 | OutArgs: methodABI.Outputs,
125 | Sender: senderAddress,
126 | }
127 | return signed_tx
128 | }
129 |
--------------------------------------------------------------------------------
/utils/heuristics.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package utils
23 |
24 | import (
25 | "fmt"
26 | "math"
27 | "math/big"
28 | "strings"
29 | "time"
30 |
31 | "encoding/json"
32 | "io/ioutil"
33 |
34 | "fuzzer/argpool"
35 |
36 | "github.com/ethereum/go-ethereum/core/types"
37 | "github.com/ethereum/go-ethereum/log"
38 | )
39 |
40 | type ResultsMap map[string]map[string]string
41 |
42 | // Bitset of optimizations optimizations mode
43 | // bits from least significant bit to most
44 | type OptMode struct {
45 | // if transaction fails retry it with half the ether
46 | RetryHalfEther bool
47 | // retry failed transaction with different sender
48 | RetryDiffSender bool
49 | // snapshot state and if "too many transactions fail" revert the state
50 | SnapshotsEnabled bool
51 | // process statistics, which method was called how many times and rate of failure
52 | GenStatistics bool
53 | }
54 |
55 | func (o *OptMode) SetFlag(optFlag int) {
56 | if optFlag&1 != 0 {
57 | o.RetryHalfEther = true
58 | }
59 | if optFlag&2 != 0 {
60 | o.RetryDiffSender = true
61 | }
62 | if optFlag&4 != 0 {
63 | o.SnapshotsEnabled = true
64 | }
65 | if optFlag&8 != 0 {
66 | o.GenStatistics = true
67 | }
68 | }
69 |
70 | func GenTimestamp(backend *Backend, argPool *argpool.ArgPool) *big.Int {
71 | // submit 2048 transactions for each counter
72 | if backend.Stats.GetCount() < 2048 {
73 | return argPool.CurrentTimestamp()
74 | }
75 | timestamp, shouldRevert := argPool.NextTimestamp()
76 | backend.Stats.ResetCounter()
77 | if shouldRevert {
78 | RevertBackend(backend)
79 | }
80 | return timestamp
81 | }
82 |
83 | func SaveJson(filename string, backend *Backend){
84 | jsonOut, _ := json.MarshalIndent(backend.LastTxRes.StructLogger.StructLogs(),""," ")
85 | _ = ioutil.WriteFile(filename, jsonOut, 0644)
86 | log.Debug(fmt.Sprintf("Saved transaction to %v.", filename))
87 | }
88 |
89 |
90 | func Rec(backend *Backend, argPool *argpool.ArgPool, hint *Hint,
91 | options *Options, result ResultsMap, optMode *OptMode, depth int) bool {
92 |
93 | header := GetDefaultHeader(backend)
94 | header.Time = GenTimestamp(backend, argPool)
95 | tx := GenTransaction(backend, argPool, hint)
96 | desc := backend.LastTxIn
97 | if result[desc.Contract] == nil {
98 | result[desc.Contract] = make(map[string]string)
99 | }
100 | log.Debug(fmt.Sprintf(fmt.Sprintf("%v. Fuzzing:\t%+v", backend.TxCount+1, PrettyPrint(desc))))
101 | backend.CommitTransaction(tx, argPool, options, header)
102 |
103 | log.Debug(fmt.Sprintf("output: %+v\n", backend.LastTxRes.StructLogger.Output()))
104 |
105 | reverted := backend.LastTxRes.RevertAtDepth == 1
106 | // If overflow happens and transaction is not reverted
107 | if backend.LastTxRes.Overflow != "" && !reverted {
108 | log.Debug("Overflow detected")
109 | log.Debug(backend.LastTxRes.Overflow)
110 | SaveJson(fmt.Sprintf("/tmp/overflow_%v.json", backend.TxCount), backend)
111 | s := fmt.Sprintf("%v: Overflow", desc.Method)
112 | result[desc.Contract][s] = backend.LastTxRes.Overflow
113 | }
114 |
115 | if backend.LastTxRes.AssertionAtDepth != -1 {
116 | log.Debug(fmt.Sprintf("Assertion failure.\ttook: %v transactions", backend.TxCount))
117 | s := fmt.Sprintf("%v: %v", desc.Method, "AssertionFailure")
118 | SaveJson(fmt.Sprintf("/tmp/assertion_%v.json", backend.TxCount), backend)
119 | result[desc.Contract][s] = ""
120 | }
121 |
122 | if strings.Index(desc.Method, "fuzz_always_true") == 0 {
123 |
124 | if !reverted && len(backend.LastTxRes.StructLogger.Output()) == 32 && backend.LastTxRes.StructLogger.Output()[31] != 1 {
125 | log.Debug(fmt.Sprintf("property violation, not always true.\ttook: %v transactions", backend.TxCount))
126 | s := fmt.Sprintf("%v: %v", desc.Method, "Property violation")
127 | SaveJson("/tmp/violation.json", backend)
128 |
129 | result[desc.Contract][s] = ""
130 | return true
131 | }
132 |
133 | // stop fuzzing once a fuzz_always_true function reverts
134 | if reverted {
135 | log.Debug(fmt.Sprintf("revert in fuzz function.\ttook: %v transactions", backend.TxCount))
136 | s := fmt.Sprintf("%v: %v", desc.Method, "Revert in fuzz function")
137 | SaveJson("/tmp/reverted_fuzz.json", backend)
138 |
139 | result[desc.Contract][s] = ""
140 | return true
141 | }
142 | }
143 |
144 | if optMode.GenStatistics {
145 | failed := backend.LastTxRes.RevertAtDepth == 1
146 | backend.Stats.AddTx(backend.LastTxIn.Contract, backend.LastTxIn.Method, failed)
147 | } else {
148 | // update transactions counter even if statistics option is not used
149 | backend.Stats.IncTxCnt()
150 | }
151 |
152 | // Heuristics for reverted transactions
153 | // if transaction was not reverted return
154 | if backend.LastTxRes.RevertAtDepth != 1 {
155 | return false
156 | }
157 |
158 | if optMode.RetryHalfEther {
159 | // half the value of ether for transaction
160 | if tx.Value().Sign() == 1 {
161 | // divide by 2 (bitwise right shift by 1)
162 | hint.Amount.Rsh(hint.Amount, 1)
163 | hint.Sender = backend.LastTxIn.Sender
164 | Rec(backend, argPool, hint, options, result, optMode, depth+1)
165 | }
166 | }
167 |
168 | if optMode.RetryDiffSender {
169 | if depth < 4 {
170 | log.Trace("Retrying transaction with different sender")
171 | hint.Sender = nil
172 | Rec(backend, argPool, hint, options, result, optMode, depth+1)
173 | }
174 | }
175 | return false
176 | }
177 |
178 | var defaultHeader *types.Header
179 |
180 | func GetDefaultHeader(b *Backend) *types.Header {
181 | if defaultHeader == nil {
182 | defaultHeader = &types.Header{
183 | Coinbase: coinBase,
184 | ParentHash: b.BlockChain.CurrentBlock().Hash(),
185 | Number: big.NewInt(1),
186 | GasLimit: math.MaxUint64,
187 | Difficulty: big.NewInt(int64(1)),
188 | Extra: nil,
189 | Time: big.NewInt(time.Now().Unix()),
190 | }
191 | }
192 | return defaultHeader
193 | }
194 |
--------------------------------------------------------------------------------
/utils/processor.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package utils
23 |
24 | import (
25 | "fmt"
26 | "math/big"
27 |
28 | "fuzzer/argpool"
29 |
30 | "github.com/ethereum/go-ethereum/common"
31 | "github.com/ethereum/go-ethereum/core/types"
32 | "github.com/ethereum/go-ethereum/core/vm"
33 | "github.com/ethereum/go-ethereum/crypto"
34 | "github.com/ethereum/go-ethereum/log"
35 | )
36 |
37 | type Options struct {
38 | UpdateCoverage bool
39 | CheckDeployedContract bool
40 | UpdateArgPool bool
41 | ExtractTimestamps bool
42 | }
43 |
44 | var operators = map[vm.OpCode]func(a, b *big.Int) *big.Int{
45 | vm.SUB: func(a, b *big.Int) *big.Int {
46 | res := big.NewInt(0)
47 | negB := big.NewInt(0)
48 | return res.Add(a, negB.Neg(b))
49 | },
50 | vm.ADD: func(a, b *big.Int) *big.Int {
51 | res := big.NewInt(0)
52 | return res.Add(a, b)
53 | },
54 | vm.MUL: func(a, b *big.Int) *big.Int {
55 | res := big.NewInt(0)
56 | return res.Mul(a, b)
57 | },
58 | // ADDMOD, MULMOD are not necessary, they probably should't overflow.
59 | // as yellowpaper states: All intermediate calculations of this operation
60 | // (ADDMOD, MULMOD) are not subject to the 2^256 modulo
61 |
62 | vm.EXP: func(a, b *big.Int) *big.Int {
63 | res := big.NewInt(0)
64 | return res.Exp(a, b, nil)
65 | },
66 | }
67 |
68 | var (
69 | earliestTime = uint64(1420070400) //2015.01.01
70 | latestTime = uint64(1735689600) // 2025.01.01
71 | )
72 |
73 | func getDeployedContractAddress(tx *types.Transaction) common.Address {
74 | from, err := types.Sender(types.HomesteadSigner{}, tx)
75 | if err != nil {
76 | panic(err)
77 | }
78 | // address of deployed contract
79 | return crypto.CreateAddress(from, tx.Nonce())
80 | }
81 |
82 | type callStack struct {
83 | stack []*common.Address
84 | }
85 |
86 | func (c *callStack) Push(address *common.Address) {
87 | c.stack = append(c.stack, address)
88 | }
89 |
90 | func (c *callStack) Top() *common.Address {
91 | return c.stack[len(c.stack)-1]
92 | }
93 |
94 | func (c *callStack) Pop() {
95 | c.stack = c.stack[:len(c.stack)-1]
96 | }
97 |
98 | func (b *Backend) processLogs(receipt *types.Receipt, tx *types.Transaction,
99 | argPool *argpool.ArgPool, options *Options) {
100 |
101 | checkDeployedContract := (options == nil) || options.CheckDeployedContract
102 | updateCoverage := (options == nil) || options.UpdateCoverage
103 | // Update coverage if transaction is sent to some contract
104 | updateCoverage = updateCoverage && (tx.To() != nil)
105 | updateArgPool := (argPool != nil) && (options != nil) && options.UpdateArgPool
106 |
107 | b.LastTxRes.Output = b.LastTxRes.StructLogger.Output()
108 | b.LastTxRes.Receipt = receipt
109 |
110 | if updateArgPool && len(b.LastTxRes.Output) > 0 {
111 | UpdatePool(b.LastTxIn, argPool, b.LastTxRes.Output)
112 | }
113 |
114 | b.LastTxRes.AssertionAtDepth = -1
115 | b.LastTxRes.RevertAtDepth = -1
116 | b.LastTxRes.Overflow = ""
117 | // there's no INVALID defined in opcodes.go in go-ethereum
118 | assertOp := vm.OpCode(0xfe)
119 | structLogs := b.LastTxRes.StructLogger.StructLogs()
120 | // call stack of contract addresses, top address is currently executing
121 | // used for coverage calculations, and determining which opcode is from
122 | // which contract
123 | callSt := callStack{}
124 | callSt.Push(tx.To())
125 | for idx, structLog := range structLogs {
126 |
127 | if options.ExtractTimestamps {
128 | for _, val := range structLog.Stack {
129 | if !val.IsUint64() {
130 | continue
131 | }
132 | value := val.Uint64()
133 | if value > earliestTime && value < latestTime {
134 | log.Trace(fmt.Sprintf("extracted timestamp: %v", value))
135 | argPool.AddTimestamp(value)
136 | }
137 | }
138 | }
139 |
140 | // check overflows
141 | if b.LastTxRes.Overflow == "" {
142 | if fn, found := operators[structLog.Op]; found {
143 | st := structLog.Stack
144 | stLen := len(st)
145 | operandA := st[stLen-1]
146 | operandB := st[stLen-2]
147 |
148 | // Out of gas can happen after math opcode, therefore there won't be
149 | // next log that should include the result
150 | if idx < len(structLogs) - 1 {
151 | nextSt := structLogs[idx+1].Stack
152 | result := nextSt[len(nextSt)-1]
153 | expected := fn(operandA, operandB)
154 | if result.Cmp(expected) != 0 {
155 | b.LastTxRes.Overflow = fmt.Sprintf("(%v %v %v=%v), expected:%v",
156 | operandA, structLog.Op, operandB, result, expected,
157 | )
158 | }
159 | }
160 | }
161 | }
162 |
163 | // check if assertion failure happend in the contract
164 | if structLog.Op == assertOp {
165 | if b.LastTxRes.AssertionAtDepth == -1 || b.LastTxRes.AssertionAtDepth > structLog.Depth {
166 | b.LastTxRes.AssertionAtDepth = structLog.Depth
167 | }
168 | }
169 |
170 | // check if REVERT opcode occured in the trace
171 | if structLog.Op == vm.REVERT {
172 | if b.LastTxRes.RevertAtDepth == -1 || b.LastTxRes.RevertAtDepth > structLog.Depth {
173 | b.LastTxRes.RevertAtDepth = structLog.Depth
174 | }
175 | }
176 |
177 | // update coverage for initially called contract only
178 | if updateCoverage {
179 | if idx > 0 {
180 | // contract making call to another contract
181 | if structLog.Depth > structLogs[idx-1].Depth {
182 | prevStack := structLogs[idx-1].Stack
183 | // address of callee is second to last in stack of previous structlog
184 | callee := common.BigToAddress(prevStack[len(prevStack)-2])
185 | callSt.Push(&callee)
186 | }
187 | // return from call
188 | if structLog.Depth < structLogs[idx-1].Depth {
189 | callSt.Pop()
190 | }
191 | }
192 |
193 | top := *callSt.Top()
194 | if b.OpcodeIndices[top] == nil {
195 | b.OpcodeIndices[top] = make(map[uint64]bool)
196 | }
197 | b.OpcodeIndices[top][structLog.Pc] = true
198 | }
199 |
200 | // contract deployment is detected at RETURN opcode:
201 | // swarm hash is searched in memory
202 | if !checkDeployedContract || (structLog.Op != vm.RETURN) {
203 | continue
204 | }
205 | // check if contract was deployed
206 | hash, found := GetSwarmHash(fmt.Sprintf("%x", structLog.Memory))
207 | if !found {
208 | continue
209 | }
210 | name := GetContractNameByHash(hash, b.Metadata)
211 | address := getDeployedContractAddress(tx)
212 | if b.DeployedContracts[name] == nil {
213 | b.DeployedContracts[name] = &Contract{
214 | Addresses: make([]common.Address, 0),
215 | Methods: make([]string, 0),
216 | }
217 | }
218 | // argPool.AddAddress(address)
219 | b.DeployedContracts[name].Addresses = append(b.DeployedContracts[name].Addresses, address)
220 | log.Trace(fmt.Sprintf("Deployed contract: %v with address: %x", name,
221 | address,
222 | ))
223 | }
224 | }
225 |
--------------------------------------------------------------------------------
/utils/snapshots.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package utils
23 |
24 | import (
25 | "fmt"
26 |
27 | "github.com/ethereum/go-ethereum/core/state"
28 | "github.com/ethereum/go-ethereum/log"
29 | )
30 |
31 | var backendSnapshot *state.StateDB
32 |
33 | func SnapshotBackend(backend *Backend) {
34 | backendSnapshot = backend.StateDB.Copy()
35 | log.Trace(fmt.Sprintf("STATE: new snapshot version has been created"))
36 | }
37 |
38 | func RevertBackend(backend *Backend) {
39 | *backend.StateDB = *backendSnapshot
40 | log.Trace(fmt.Sprintf("STATE: state has been reverted"))
41 | }
42 |
--------------------------------------------------------------------------------
/utils/statistics.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package utils
23 |
24 | import "fmt"
25 |
26 | type ContractStatsMap map[string][]int
27 | type StatsMap map[string]ContractStatsMap
28 |
29 | type Stats struct {
30 | statsMap StatsMap
31 | txCntAfterRevert int
32 | }
33 |
34 | func (s *Stats) setIfNil(contract, method string) {
35 | if s.statsMap == nil {
36 | s.statsMap = make(StatsMap)
37 | }
38 | if s.statsMap[contract] == nil {
39 | s.statsMap[contract] = make(ContractStatsMap)
40 | }
41 | if s.statsMap[contract][method] == nil {
42 | s.statsMap[contract][method] = []int{0, 0}
43 | }
44 | }
45 |
46 | func (s *Stats) AddFailedTx(contract, method string) {
47 | s.setIfNil(contract, method)
48 | s.statsMap[contract][method][0] = s.statsMap[contract][method][0] + 1
49 | s.statsMap[contract][method][1] = s.statsMap[contract][method][1] + 1
50 | }
51 |
52 | func (s *Stats) AddSuccessfulTx(contract, method string) {
53 | s.setIfNil(contract, method)
54 | s.statsMap[contract][method][1] = s.statsMap[contract][method][1] + 1
55 | }
56 |
57 | func (s *Stats) AddTx(contract, method string, failed bool) {
58 | s.IncTxCnt()
59 | if failed {
60 | s.AddFailedTx(contract, method)
61 | return
62 | }
63 | s.AddSuccessfulTx(contract, method)
64 | }
65 |
66 | func (s *Stats) IncTxCnt() {
67 | s.txCntAfterRevert = s.txCntAfterRevert + 1
68 | }
69 |
70 | func (s *Stats) ResetCounter() {
71 | s.txCntAfterRevert = 0
72 | }
73 |
74 | func (s *Stats) GetCount() int {
75 | return s.txCntAfterRevert
76 | }
77 |
78 | func (s *Stats) GetTotalOf(contract, method string) int {
79 | s.setIfNil(contract, method)
80 | return s.statsMap[contract][method][1]
81 | }
82 |
83 | func (s *Stats) GetStats() map[string]map[string]string {
84 | res := make(map[string]map[string]string)
85 | for contract, contractStats := range s.statsMap {
86 | res[contract] = make(map[string]string)
87 | for method, pair := range contractStats {
88 | res[contract][method] = fmt.Sprintf("Failed: %v/%v. (failure rate: %.2f%%)",
89 | pair[0], pair[1], 100.0*float64(pair[0])/float64(pair[1]),
90 | )
91 | }
92 | }
93 | return res
94 | }
95 |
--------------------------------------------------------------------------------
/utils/transactions.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package utils
23 |
24 | import (
25 | "bufio"
26 | "encoding/hex"
27 | "encoding/json"
28 | "fmt"
29 | "math/big"
30 | "os"
31 | "strconv"
32 |
33 | "github.com/ethereum/go-ethereum/common"
34 | "github.com/ethereum/go-ethereum/core/types"
35 | )
36 |
37 | const NullAddress = "0000000000000000000000000000000000000000"
38 |
39 | type transaction struct {
40 | Hash string `json:"hash"`
41 | AccountNonce uint64 `json:"nonce"`
42 | BlockHash string `json:"blockHash"`
43 | BlockNumber int `json:"blockNumber"`
44 | TransactionIndex int `json:"transactionIndex"`
45 | From string `json:"from"`
46 | Recipient string `json:"to"`
47 | Amount string `json:"value"`
48 | GasLimit uint64 `json:"gas"`
49 | Price string `json:"gasPrice"`
50 | Payload string `json:"input"`
51 | }
52 |
53 | // removes 0x prefix from hex string and decode payload into bytes
54 | func getPayload(data *string) []byte {
55 | data_str := *data
56 | if data_str[1] == 'x' {
57 | data_str = data_str[2:len(data_str)]
58 | }
59 | payload, err := hex.DecodeString(data_str)
60 | if err != nil {
61 | panic(fmt.Errorf("error decoding payload: %+v\n", err))
62 | }
63 | return payload
64 | }
65 |
66 | func isContractCreation(t *transaction) bool {
67 | if (t.Recipient == "") || (NullAddress == fmt.Sprintf("%x", common.HexToAddress(t.Recipient))) {
68 | return true
69 | }
70 | return false
71 | }
72 |
73 | // converts transaction from format that was written as JSON file
74 | // to types.Transaction structure and signs with respective key
75 | func convertAndSign(t *transaction) *types.Transaction {
76 | // convert amount and gasprice from hex to decimal
77 | amount, err := strconv.ParseInt(t.Amount, 10, 64)
78 | if err != nil {
79 | amount = 0
80 | }
81 | price, err := strconv.ParseInt(t.Price, 10, 64)
82 | if err != nil {
83 | price = 0
84 | }
85 | payload := getPayload(&t.Payload)
86 | var tx *types.Transaction
87 | if t.GasLimit > uint64(*maxGasPool) {
88 | t.GasLimit = uint64(*maxGasPool)
89 | }
90 | if isContractCreation(t) {
91 | tx = types.NewContractCreation(t.AccountNonce, big.NewInt(amount), t.GasLimit, big.NewInt(price), payload)
92 | } else {
93 | tx = types.NewTransaction(t.AccountNonce, common.HexToAddress(t.Recipient), big.NewInt(amount), t.GasLimit, big.NewInt(price), payload)
94 | }
95 | sender := common.HexToAddress(t.From)
96 | // mark account as used in order to delete accounts afterwards that weren't
97 | // used during the deployment
98 | GetAccountFromAddress(sender).Used = true
99 | // sign transaction with the sender's key
100 | signed, err := types.SignTx(tx, types.HomesteadSigner{}, GetKeyFromAddress(sender))
101 | if err != nil {
102 | panic(fmt.Errorf("error signing contract: %v\n", err))
103 | }
104 | return signed
105 | }
106 |
107 | // Reads transactions from json file (that are extracted from Ganache after truffle deploy)
108 | // and returns array of transaction objects
109 | func ReadTransactions(txFile string) []*types.Transaction {
110 | txJSON, err := os.Open(txFile)
111 | if err != nil {
112 | panic(fmt.Errorf("error opening transactions file: %+v\n", err))
113 | }
114 | defer txJSON.Close()
115 |
116 | var txs []*types.Transaction
117 | fileScanner := bufio.NewScanner(txJSON)
118 | for fileScanner.Scan() {
119 | t := transaction{}
120 | err := json.Unmarshal([]byte(fileScanner.Text()), &t)
121 | if err != nil {
122 | panic(fmt.Errorf("error unmarshalling transaction: %+v\n", err))
123 | }
124 | txs = append(txs, convertAndSign(&t))
125 | }
126 | // scanner can't read lines longer than 65536 characters
127 | if err := fileScanner.Err(); err != nil {
128 | panic(err)
129 | }
130 | return txs
131 | }
132 |
--------------------------------------------------------------------------------
/utils/types.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package utils
23 |
24 | import (
25 | "math/big"
26 | "reflect"
27 |
28 | "github.com/ethereum/go-ethereum/common"
29 | )
30 |
31 | var (
32 | Int8Type = reflect.TypeOf(int8(13))
33 | UInt8Type = reflect.TypeOf(uint8(13))
34 | Int16Type = reflect.TypeOf(int16(13))
35 | UInt16Type = reflect.TypeOf(uint16(13))
36 | Int32Type = reflect.TypeOf(int32(13))
37 | UInt32Type = reflect.TypeOf(uint32(13))
38 | Int64Type = reflect.TypeOf(int64(13))
39 | UInt64Type = reflect.TypeOf(uint64(13))
40 | Bytes32Type = reflect.TypeOf([32]byte{})
41 | AddressType = reflect.TypeOf(common.Address{})
42 | BigIntType = reflect.TypeOf((*big.Int)(nil))
43 | BoolType = reflect.TypeOf(true)
44 | StringType = reflect.TypeOf("Expecto Patronum")
45 | )
46 |
--------------------------------------------------------------------------------
/utils/utils.go:
--------------------------------------------------------------------------------
1 | /***
2 | *
3 | * ChainSecurity ChainFuzz - a fast ethereum transaction fuzzer
4 | * Copyright (C) 2019 ChainSecurity AG
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | *
19 | ***/
20 |
21 |
22 | package utils
23 |
24 | import (
25 | "encoding/json"
26 | "fmt"
27 | "io/ioutil"
28 | "path/filepath"
29 | "strings"
30 | )
31 |
32 | type MetadataJSON struct {
33 | TruffleDir string `json:"tuffleProjDir"`
34 | Transactions string `json:"transactions"`
35 | AccountsFile string `json:"accounts"`
36 | ConfigFile string `json:"config"`
37 | }
38 |
39 | var metadataJSONMap map[string]*MetadataJSON
40 |
41 | // var metadataJSON *MetadataJSON
42 |
43 | func getMeta(metadata string) MetadataJSON {
44 | if metadataJSONMap[metadata] != nil {
45 | return *metadataJSONMap[metadata]
46 | }
47 | content, err := ioutil.ReadFile(metadata)
48 | if err != nil {
49 | panic(fmt.Errorf("Error reading metadata: %v\n", metadata))
50 | }
51 | metadataJSON := &MetadataJSON{}
52 | json.Unmarshal([]byte(content), metadataJSON)
53 | metadataJSONMap[metadata] = metadataJSON
54 | return *metadataJSON
55 | }
56 |
57 | // returns transactions file from metadata json
58 | func getTxJSONFile(metadata string) string {
59 | meta := getMeta(metadata)
60 | return meta.Transactions
61 | }
62 |
63 | // returns accounts file from metadata json
64 | func getAccountsJSONFile(metadata string) string {
65 | meta := getMeta(metadata)
66 | return meta.AccountsFile
67 | }
68 |
69 | // reads truffle directory from metadata json
70 | func getTruffleDir(metadata string) string {
71 | meta := getMeta(metadata)
72 | return meta.TruffleDir
73 | }
74 |
75 | type ContractConfig struct {
76 | IgnoreAll bool `json:"ignore_all"`
77 | IgnoredFunctions []string `json:"ignore"`
78 | Timestamps []uint64 `json:"timestamps"`
79 | }
80 |
81 | var fuzzingConfig map[string]ContractConfig
82 |
83 | // returns accounts file from metadata json
84 | func GetConfig(metadata string) map[string]ContractConfig {
85 | if fuzzingConfig != nil {
86 | return fuzzingConfig
87 | }
88 |
89 | meta := getMeta(metadata)
90 |
91 | content, err := ioutil.ReadFile(meta.ConfigFile)
92 | if err != nil {
93 | panic(fmt.Errorf("Error reading config file: %v\n", meta.ConfigFile))
94 | }
95 | fuzzingConfig = make(map[string]ContractConfig)
96 | json.Unmarshal([]byte(content), &fuzzingConfig)
97 | return fuzzingConfig
98 | }
99 |
100 | func PrettyPrint(i interface{}) string {
101 | s, _ := json.MarshalIndent(i, "", "\t")
102 | return string(s)
103 | }
104 |
105 | // returns file name without extension
106 | func getFilename(filename string) string {
107 | return strings.TrimSuffix(filename, filepath.Ext(filename))
108 | }
109 |
110 | func init() {
111 | metadataJSONMap = make(map[string]*MetadataJSON)
112 | }
113 |
--------------------------------------------------------------------------------