Showing preview only (207K chars total). Download the full file or copy to clipboard to get everything.
Repository: palkeo/pakala
Branch: master
Commit: fce61037e511
Files: 42
Total size: 195.2 KB
Directory structure:
gitextract_xfaybpz0/
├── .circleci/
│ └── config.yml
├── .flake8
├── .gitignore
├── LICENSE.txt
├── README.md
├── pakala/
│ ├── __init__.py
│ ├── analyzer.py
│ ├── claripy_sha3.py
│ ├── cli.py
│ ├── env.py
│ ├── memory.py
│ ├── recursive_analyzer.py
│ ├── sm.py
│ ├── state.py
│ ├── summary.py
│ ├── test_analyzer.py
│ ├── test_claripy_sha3.py
│ ├── test_env.py
│ ├── test_memory.py
│ ├── test_recursive_analyzer.py
│ ├── test_sm.py
│ ├── test_state.py
│ └── utils.py
├── requirements.txt
├── setup.py
└── solidity_tests/
├── __init__.py
├── arbitrary_storage_write.sol
├── arbitrary_storage_write2.sol
├── array_write.sol
├── constructor_wrongly_named.sol
├── delegatecall.sol
├── mapping.sol
├── mapping2.sol
├── multiple_write_multiple_tx.sol
├── multiple_write_one_tx.sol
├── recursive_mapping.sol
├── simple_ether_drain.sol
├── simple_suicide.sol
├── string.sol
├── string_unbounded.sol
├── test_solidity.py
└── wrapped_ether.sol
================================================
FILE CONTENTS
================================================
================================================
FILE: .circleci/config.yml
================================================
# Python CircleCI 2.0 configuration file
#
# Check https://circleci.com/docs/2.0/language-python/ for more details
#
version: 2
jobs:
build:
docker:
# specify the version you desire here
# use `-browsers` prefix for selenium tests, e.g. `3.6.1-browsers`
- image: circleci/python:3
# Specify service dependencies here if necessary
# CircleCI maintains a library of pre-built images
# documented at https://circleci.com/docs/2.0/circleci-images/
# - image: circleci/postgres:9.4
working_directory: ~/repo
steps:
- checkout
# Download and cache dependencies
- restore_cache:
keys:
- v1-dependencies-{{ checksum "requirements.txt" }}
# fallback to using the latest cache if no exact match is found
- v1-dependencies-
- run:
name: install dependencies
command: |
python3 -m venv venv
. venv/bin/activate
pip install -r requirements.txt
- save_cache:
paths:
- ./venv
key: v1-dependencies-{{ checksum "requirements.txt" }}
# run tests!
- run:
name: run tests
command: |
. venv/bin/activate
python -m unittest -v
- store_artifacts:
path: test-reports
destination: test-reports
================================================
FILE: .flake8
================================================
[flake8]
max-line-length = 88
================================================
FILE: .gitignore
================================================
*.pyc
__pycache__/
================================================
FILE: LICENSE.txt
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
================================================
FILE: README.md
================================================
Pakala
======
[](https://pypi.python.org/pypi/pakala)
[](https://circleci.com/gh/palkeo/pakala)
<img align="right" src="https://www.palkeo.com/en/_images/pakala-mani-sona.svg.png">
*"ilo Pakala li pakala e mani sona"*
* Pakala is a tool to search for exploitable bugs in Ethereum smart contracts.
* Pakala is a symbolic execution engine for the Ethereum Virtual Machine.
The intended public for the tool are security researchers interested by Ethereum / the EVM.
Installation
------------
```
pip3 install pakala
```
It works only with python 3.
Usage
-----
Let's look at [0xeBE6c7a839A660a0F04BdF6816e2eA182F5d542C](http://eveem.com/code/0xeBE6c7a839A660a0F04BdF6816e2eA182F5d542C):
it has a ``transfer(address _to, uint256 _value)`` function. It is supposedly protected by a ``require(call.value - _value) >= 0``
but that condition always holds because we are substracting two unsigned integers, so the result is also an unsigned integer.
Let's scan it:
```
pakala 0xeBE6c7a839A660a0F04BdF6816e2eA182F5d542C --force-balance="1 ether"
```
The contract balance being 0, we won't be able to have it send us some ethers.
So we override the balance to be 1 ETH: then it has some "virtual" money to send us.
The tool with tell you a bug was found, and dump you a path of "states". Each
state corresponds to a transaction, with constraints that needs to be respected
for that code path to be taken, storage that has been read/written...
Advice: look at ``calldata[0]`` in the constraints to see the function signature for each transaction.
See ``pakala help`` for more complete usage information.
How does it works? What does it do?
-----------------------------------
See the [introductory article](https://www.palkeo.com/projets/ethereum/pakala.html) for more information and a demo.
In a nutshell:
* It's very good at finding simple bugs in simple contracts.
* The false-positive rate is very low. If it flags your contract it's likely people can drain it.
* It can exploit non-trivial bugs requiring to overwrite some storage keys with others (array size underflow...), has a good
modeling of cryptographic hashes, and support chaining multiple transactions.
However, It only implements an "interesting" subset of the EVM. It doesn't handle:
* gas,
* precompiles,
* or a contract interacting with other contracts (DELEGATECALL, STATICCALL...).
This means that CALL support is limited to sending ethers. Other tools like Manticore can do that much better, and the focus for
Pakala was offensive vulnerability scanning of contracts *en masse*.
================================================
FILE: pakala/__init__.py
================================================
================================================
FILE: pakala/analyzer.py
================================================
import logging
import numbers
import claripy
from pakala import utils
from web3 import Web3
# We can load up to this many keys from the contract storage. More than that
# and we won't load them all, and read them lazily instead (which is less precise).
MAX_STORAGE_KEYS = 32
# When we cannot list the keys, we can always try these ones:
STORAGE_KEYS_WHEN_CANNOT_LIST = list(range(10))
logger = logging.getLogger(__name__)
class BaseAnalyzer(object):
"""Base class for an Analyzer.
Child classes need to define `caller` and `address`.
"""
def __init__(self, max_wei_to_send, min_wei_to_receive, block="latest"):
self.web3 = Web3()
self.web3.eth.defaultBlock = block
self.max_wei_to_send = max_wei_to_send
self.min_wei_to_receive = min_wei_to_receive
self.actual_storage = None
# Whether or not actual_storage is guaranteed to contain all the storage,
# or just a subset of it. Will be False for contracts with a lot of keys
# so that we cannot load them all.
# For testing we can replace actual_storage with a dict so it's never
# actually filled. In that case we can assume it's exhaustive.
self.actual_storage_exhaustive = True
@property
def hex_addr(self):
return self.web3.toChecksumAddress(
utils.number_to_address(utils.bvv_to_number(self.address))
)
def _read_storage_key(self, key):
return self.web3.toInt(self.web3.eth.getStorageAt(self.hex_addr, key))
def _fill_actual_storage(self):
try:
storage_keys = [
self.web3.toInt(hexstr=k)
for k in self.web3.parity.listStorageKeys(
self.hex_addr, MAX_STORAGE_KEYS, None, self.web3.eth.defaultBlock
)
]
except Exception as e:
# If we cannot list storage keys, let's read the beginning of the
# space, and below we will mark that it's not exhaustive anyway.
logger.warning(
"Cannot list storage keys (%s). We will lose a bit of accuracy. "
"Try to use a node that supports the parity_listStorageKeys RPC. ",
e.__class__.__name__,
)
storage_keys = STORAGE_KEYS_WHEN_CANNOT_LIST
self.actual_storage_exhaustive = False
else:
assert len(storage_keys) <= MAX_STORAGE_KEYS
self.actual_storage_exhaustive = len(storage_keys) < MAX_STORAGE_KEYS
self.actual_storage = {k: self._read_storage_key(k) for k in storage_keys}
logger.info(
"Loaded %i storage slots from the contract (%s). %i non-zero.",
len(storage_keys),
"exhaustive" if self.actual_storage_exhaustive else "non-exhaustive",
sum(1 for v in self.actual_storage.values() if v != 0),
)
logger.debug("actual_storage: %r", self.actual_storage)
def _read_storage(self, state, key):
logger.debug("Reading storage %r" % key)
if self.actual_storage is None:
self._fill_actual_storage()
# If our storage is not exhaustive, let's try to concretize the key and read the
# corresponding storage directly.
if not self.actual_storage_exhaustive:
try:
concrete_keys = state.solver.eval(key, 2)
except claripy.errors.UnsatError as e:
# We will lose accuracy, and assume that our actual_storage is exhaustive...
logger.debug(
"Encountered an exception when resolving key %r: %r", key, e
)
else:
for concrete_key in concrete_keys:
if concrete_key not in self.actual_storage:
self.actual_storage[concrete_key] = self._read_storage_key(
concrete_key
)
# Warning: Here we used to return the value if there was a single solution,
# however sha3 solver may artificially pin a key temporarily and return a single
# solution where there could be more. So we always use a claripy.If.
symbolic_storage = utils.bvv(0) # When uninitialized: 0
for k, v in self.actual_storage.items():
if v != 0:
symbolic_storage = claripy.If(key == k, v, symbolic_storage)
return symbolic_storage
def check_state(self, state, path=None):
"""Check a reachable state for bugs"""
logger.debug("Check state: %s", state)
logger.debug("Constraints: %s", state.solver.constraints)
solver = state.solver.branch()
if path is None:
path = [state]
# Static read were we never wrote, but we know the key is not symbolic.
# So we go and fetch it.
for key, value in state.storage_read.items():
constraint = state.storage_read[key] == self._read_storage(state, key)
solver.add(constraint)
logger.debug("Add storage constraint: %s", constraint)
for s in path:
solver.add(list(s.env.extra_constraints()))
solver.add(
[
s.env.caller == utils.DEFAULT_CALLER,
s.env.origin == utils.DEFAULT_CALLER,
]
)
# Calls
total_sent = sum(s.env.value for s in path)
sent_constraints = [s.env.value < self.max_wei_to_send for s in path]
total_received_by_me = utils.bvv(0)
total_received = utils.bvv(0)
for call in state.calls:
# TODO: Improve delegatecall support! And make it clearer it's
# delegatecall, not just based on the length.
assert 6 <= len(call) <= 7
value, to, gas = call[-3:] # pylint: disable=unused-variable,invalid-name
delegatecall = len(call) == 6
if delegatecall:
if solver.satisfiable(
extra_constraints=[to[159:0] == self.caller[159:0]]
):
logger.info("Found delegatecall bug.")
solver.add(to[159:0] == self.caller[159:0])
return solver
else:
total_received_by_me += claripy.If(
to[159:0] == self.caller[159:0], value, utils.bvv(0)
)
total_received += value
solver.add(value <= total_sent + path[0].env.balance)
final_balance = path[0].env.balance + total_sent - total_received
# Suicide
if state.selfdestruct_to is not None:
constraints = [
final_balance >= self.min_wei_to_receive,
state.selfdestruct_to[159:0] == self.caller[159:0],
]
logger.debug("Check for selfdestruct bug with constraints %s", constraints)
if solver.satisfiable(extra_constraints=constraints):
logger.info("Found selfdestruct bug.")
solver.add(constraints)
return solver
if total_received_by_me is utils.bvv(0):
return
logger.debug("Found calls back to caller: %s", total_received_by_me)
solver.add(sent_constraints)
solver.add(
[
claripy.SGE(final_balance, 0),
total_received_by_me > total_sent, # I get more than what I sent?
total_received_by_me > self.min_wei_to_receive,
]
)
if solver.satisfiable():
logger.info("Found call bug.")
return solver
class Analyzer(BaseAnalyzer):
"""Simple Analyzer class, where caller and address are given explicitly."""
def __init__(self, address, caller, *args, **kwargs):
super().__init__(*args, **kwargs)
self.caller = caller
self.address = address
================================================
FILE: pakala/claripy_sha3.py
================================================
import logging
import itertools
import operator
from claripy.ast import bv
import claripy
import eth_utils
logger = logging.getLogger(__name__)
# TODO: we could keep the resulting constraints in cache or something, so it's
# very fast when we don't use the solver with non-empty extra_constraint.
def Sha3(x):
return bv.BV("SHA3", [x], length=256)
def _symbolize_hashes(ast, hashes):
if not isinstance(ast, claripy.ast.base.Base):
return ast
# Replace SHA3 with a BVS
if ast.op == "SHA3":
hash_input, = ast.args
hash_input = _symbolize_hashes(hash_input, hashes)
try:
return hashes[hash_input]
except KeyError:
hash_symbol = claripy.BVS("SHA3", 256)
hashes[hash_input] = hash_symbol
logger.debug("Registering new hash: %s(%s)", hash_symbol, hash_input)
return hash_symbol
# Recursively apply to children
args = [_symbolize_hashes(child, hashes) for child in ast.args]
return ast.swap_args(args)
def _no_sha3_symbol(ast):
if not isinstance(ast, claripy.ast.base.Base):
return True
elif isinstance(ast, claripy.ast.base.BV):
try:
return not ast.args[0].startswith("SHA3")
except AttributeError:
return True
else:
return all(_no_sha3_symbol(child) for child in ast.args)
def _this_sha3_symbol(ast, symbol):
if not isinstance(ast, claripy.ast.base.Base):
return False
if ast is symbol:
return True
return any(_this_sha3_symbol(child, symbol) for child in ast.args)
def _no_sha3_symbols(constraints):
return all(_no_sha3_symbol(ast) for ast in constraints)
def _hash_depth(hashes, hash_symbol):
"""Returns how "deep" this hash symbol is, if it's inside another hash."""
depth = 0
for in1, s1 in hashes.items():
if _this_sha3_symbol(in1, hash_symbol):
assert s1 is not hash_symbol # A hash cannot contain itself.
depth = max(depth, 1 + _hash_depth(hashes, s1))
return depth
def get_claripy_solver():
# TODO: What about SolverComposite? Tried, and seems slower.
return claripy.Solver()
class Solver:
__slots__ = ["solver", "hashes"]
def __init__(self, claripy_solver=None, hashes=None):
self.solver = claripy_solver or get_claripy_solver()
self.hashes = hashes or {} # Mapping hash input to the symbol
def branch(self):
return Solver(claripy_solver=self.solver.branch(), hashes=self.hashes.copy())
def add(self, constraints, **kwargs):
if isinstance(constraints, claripy.ast.base.Base):
constraints = [constraints]
logger.debug("Adding constraint: %r", constraints)
assert _no_sha3_symbols(constraints)
constraints = [_symbolize_hashes(c, self.hashes) for c in constraints]
return self.solver.add(constraints, **kwargs)
def satisfiable(self, extra_constraints=(), **kwargs):
assert _no_sha3_symbols(extra_constraints)
try:
extra_constraints = self._hash_constraints(
extra_constraints, hashes=self.hashes.copy()
)
except claripy.errors.UnsatError:
return False
return self.solver.satisfiable(extra_constraints=extra_constraints)
def eval(self, e, n, extra_constraints=(), **kwargs):
assert _no_sha3_symbol(e)
assert _no_sha3_symbols(extra_constraints)
hashes = self.hashes.copy()
e = _symbolize_hashes(e, hashes)
extra_constraints = self._hash_constraints(extra_constraints, hashes=hashes)
return self.solver.eval(e, n, extra_constraints=extra_constraints)
def batch_eval(self, e, n, extra_constraints=(), **kwargs):
raise NotImplementedError()
def max(self, e, extra_constraints=(), **kwargs):
assert _no_sha3_symbol(e)
assert _no_sha3_symbols(extra_constraints)
hashes = self.hashes.copy()
e = _symbolize_hashes(e, hashes)
extra_constraints = self._hash_constraints(extra_constraints, hashes=hashes)
return self.solver.max(e, extra_constraints=extra_constraints)
def min(self, e, extra_constraints=(), **kwargs):
assert _no_sha3_symbol(e)
assert _no_sha3_symbols(extra_constraints)
hashes = self.hashes.copy()
e = _symbolize_hashes(e, hashes)
extra_constraints = self._hash_constraints(extra_constraints, hashes=hashes)
return self.solver.min(e, extra_constraints=extra_constraints)
def solution(self, e, v, extra_constraints=(), **kwargs):
assert _no_sha3_symbol(e)
assert _no_sha3_symbols(extra_constraints)
hashes = self.hashes.copy()
e = _symbolize_hashes(e, hashes)
extra_constraints = self._hash_constraints(extra_constraints, hashes=hashes)
return self.solver.solution(e, v, extra_constraints=extra_constraints)
def _hash_constraints(self, extra_constraints, hashes, pairs_done=None):
extra_constraints = [_symbolize_hashes(c, hashes) for c in extra_constraints]
# Fast-path if no hashes, or if not satisfiable.
if not hashes or not self.solver.satisfiable(
extra_constraints=extra_constraints
):
return tuple(extra_constraints)
if pairs_done is None:
pairs_done = set()
constraint_added = False
for (in1, s1), (in2, s2) in itertools.combinations(hashes.items(), 2):
if (s1, s2) in pairs_done:
continue
# Do s1 needs to be equal to s2 ? Then in1 needs to be equal to in2
if not self.solver.satisfiable(
extra_constraints=extra_constraints + [s1 != s2]
):
logger.debug("Adding input constraint: %s == %s", in1, in2)
if in1.size() == in2.size():
extra_constraints.append(in1 == in2)
else:
logger.debug("Size are different!")
extra_constraints.append(False)
pairs_done.add((s1, s2))
pairs_done.add((s2, s1))
constraint_added = True
# Do s1 needs to be != to s2 ? Then in1 needs to be != to in2
elif not self.solver.satisfiable(
extra_constraints=extra_constraints + [s1 == s2]
):
logger.debug("Adding input constraint: %s != %s", in1, in2)
if in1.size() == in2.size():
extra_constraints.append(in1 != in2)
constraint_added = True
else:
logger.debug("Size are different!")
pairs_done.add((s1, s2))
pairs_done.add((s2, s1))
if constraint_added:
return self._hash_constraints(extra_constraints, hashes, pairs_done)
assert self.solver.satisfiable(extra_constraints=extra_constraints)
# We need to first concretize the hashes that are the "deepest", i.e. that
# are serving as input for other hashes.
hash_depth = {symbol: _hash_depth(hashes, symbol) for symbol in hashes.values()}
for in1, s1 in sorted(
hashes.items(), key=lambda i: hash_depth[i[1]], reverse=True
):
# Next line can raise UnsatError. Handled in the caller if needed.
sol1, = self.solver.eval(in1, 1, extra_constraints=extra_constraints)
extra_constraints.append(in1 == sol1)
# lstrip() is needed if the length is 0.
sol1_bytes = (
eth_utils.conversions.to_bytes(sol1)
.lstrip(b"\0")
.rjust(in1.length // 8, b"\0")
)
assert len(sol1_bytes) * 8 == in1.length
extra_constraints.append(s1 == eth_utils.crypto.keccak(sol1_bytes))
logger.debug(
"Added concrete constraint on hash: %s and on input: %s",
extra_constraints[-1],
extra_constraints[-2],
)
return tuple(extra_constraints)
def replace(self, r):
# First replacement: apply r() everywhere.
new_constraints = [r(i) for i in self.solver.constraints]
self.hashes = {r(k): r(v) for k, v in self.hashes.items()}
# We need to rebuild the solver because we cannot just modify the constraints.
self.solver = get_claripy_solver()
self.solver.add(new_constraints)
def regenerate_hash_symbols(self):
# We can copy such a solver, and replace symbols in a new environment,
# and want to combine() it again with the parent solver, or one derived
# from it. In that case the hashes symbols need to be different! So we
# can use that function and call replace() on all the symbols to use
# new hash symbols everywhere.
new_hashes = {k: claripy.BVS("SHA3", 256) for k, v in self.hashes.items()}
def r(ast):
for in_ in self.hashes:
ast = ast.replace(self.hashes[in_], new_hashes[in_])
return ast
return r
def combine(self, others):
other_claripy_solvers = [i.solver for i in others]
combined = Solver(
claripy_solver=self.solver.combine(other_claripy_solvers),
hashes=self.hashes,
)
for other in others:
for k, v in self.hashes.items():
# Make sure the hash symbols are distinct
if any(v is v2 for v2 in other.hashes.values()):
# Call regenerate_hash_symbols() on one of them first?
raise ValueError("Cannot combine with equivalent hashes.")
# TODO: If some hash input are equal, we should merge the hash
# symols here, it would be more efficient.
combined.hashes.update(other.hashes)
return combined
def downsize(self):
return self.solver.downsize()
def simplify(self):
return self.solver.simplify()
def __repr__(self):
return "ClaripySha3(constraints=%s, hashes=%s)" % (
self.solver.constraints,
self.hashes,
)
def as_dict(self):
return {"constraints": self.solver.constraints, "hashes": self.hashes}
@property
def constraints(self):
return self.solver.constraints
================================================
FILE: pakala/cli.py
================================================
"""
pakala: EVM symbolic execution tool and vulnerability scanner.
Copyright (C) 2018 Korantin Auguste
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import argparse
import codecs
import logging
import sys
import re
from pakala import sm
from pakala import recursive_analyzer
from pakala import env
from pakala import utils
from pakala import summary
from web3.auto import w3
from web3 import Web3
import web3
import coloredlogs
def err_exit(message):
print(message, file=sys.stderr)
exit(-1)
def ethWeiAmount(arg):
m = re.match(r"^([0-9.]+) ?(\w+)$", arg)
if m is None:
raise argparse.ArgumentError(
"The argument must be in the form '1 ether' for example."
)
return Web3.toWei(float(m.group(1)), m.group(2))
def addressOrStdin(s):
if s == "-":
return s
if not re.match(r"^0x([0-9a-fA-F]){40}$", s):
raise argparse.ArgumentError("Invalid address.")
return Web3.toChecksumAddress(s)
parser = argparse.ArgumentParser(
description="Find exploitable Ethereum smart contracts."
)
parser.add_argument(
"contract_addr",
type=addressOrStdin,
help="Address of the contract to analyze. "
"Use '-' for reading runtime bytecode from stdin instead.",
)
parser.add_argument(
"-v",
default=str(utils.INFO_INTERACTIVE),
help="log level (INFO, DEBUG...)",
metavar="LOG_LEVEL",
)
parser.add_argument(
"-s", "--summarize", action="store_true", help="enable summarizer (EXPERIMENTAL)"
)
limits = parser.add_argument_group("time/depth limits")
limits.add_argument(
"--exec-timeout",
help=(
"Timeout in seconds for the symbolic execution stage. Use 0 for a "
"system that will stop when the last coverage increase was too long ago."
),
type=int,
default=0,
metavar="SECONDS",
)
limits.add_argument(
"--analysis-timeout",
help=(
"Timeout in seconds for the analysis stage (that will stack the executions "
"and find bugs). Use 0 to disable timeout and use only depth limit."
),
type=int,
default=0,
metavar="SECONDS",
)
limits.add_argument(
"--max-transaction-depth",
help=(
"Maximum number of outcomes that can be fused "
"together during the analysis step."
),
type=int,
default=4,
)
environment = parser.add_argument_group("environment")
environment.add_argument(
"-b",
"--force-balance",
type=ethWeiAmount,
help="Don't use the current contract balance, instead force it to a value.",
metavar="BALANCE",
)
environment.add_argument(
"-B",
"--block",
default="latest",
type=lambda block_number: hex(int(block_number))
if block_number.isnumeric()
else block_number,
help="Use the code/balance/storage at that block instead of latest.",
)
symbolic = parser.add_argument_group("symbolic execution tweaks")
symbolic.add_argument(
"-z",
"--disable-fuzzing",
action="store_true",
help="Disable forced concretization of symbols where we need a concrete value.",
)
analyzer = parser.add_argument_group("analyzer tweaks")
analyzer.add_argument(
"-m",
"--min-to-receive",
type=ethWeiAmount,
default="1 milliether",
help="Minimum amount to receive from the contract to consider it a bug.",
metavar="BALANCE",
)
analyzer.add_argument(
"-M",
"--max-to-send",
type=ethWeiAmount,
default="10 ether",
help=(
"Maximum amount allowed to send to the contract "
"(even if we would receive more)."
),
metavar="BALANCE",
)
def main():
args = parser.parse_args()
if args.v.isnumeric():
coloredlogs.install(level=int(args.v))
elif hasattr(logging, args.v.upper()):
coloredlogs.install(level=getattr(logging, args.v.upper()))
else:
err_exit("Logging should be DEBUG/INFO/WARNING/ERROR.")
try:
logging.debug("Node working. Block %i ", w3.eth.blockNumber)
except web3.exceptions.CannotHandleRequest:
err_exit(
"Seems like Web3.py can't auto-connect to your Ethereum node.\n"
"Please have a local node running or set the environment variable WEB3_PROVIDER_URI to the URL of your node."
)
if args.contract_addr == "-":
# Let's read the runtime bytecode from stdin
code = sys.stdin.read().strip("\n")
if not code.isalnum():
err_exit("Runtime bytecode read from stdin needs to be hexadecimal.")
code = codecs.decode(code, "hex")
# Dummy address, dummy balance
args.contract_addr = "0xDEADBEEF00000000000000000000000000000000"
if not args.force_balance:
args.force_balance = Web3.toWei(1.337, "ether")
else:
code = w3.eth.getCode(args.contract_addr, block_identifier=args.block)
balance = args.force_balance or w3.eth.getBalance(
args.contract_addr, block_identifier=args.block
)
print(
"Analyzing contract at %s with balance %f ether."
% (args.contract_addr, Web3.fromWei(balance, "ether"))
)
if balance < args.min_to_receive:
err_exit(
"Balance is smaller than --min-to-receive: "
"the analyzer will never find anything."
)
if args.summarize:
logging.info(
"Summarizer enabled, we won't constrain the caller/origin "
"so more of the contract can get explored. "
"It may be slower."
)
e = env.Env(
code,
address=utils.bvv(int(args.contract_addr, 16)),
balance=utils.bvv(balance),
)
else:
e = env.Env(
code,
address=utils.bvv(int(args.contract_addr, 16)),
caller=utils.DEFAULT_CALLER,
origin=utils.DEFAULT_CALLER,
balance=utils.bvv(balance),
)
print("Starting symbolic execution step...")
s = sm.SymbolicMachine(e, fuzz=not args.disable_fuzzing)
s.execute(timeout_sec=args.exec_timeout)
print(
"Symbolic execution finished with coverage %i%%." % int(s.get_coverage() * 100)
)
print(
"Outcomes: %i interesting. %i total and %i unfinished paths."
% (
sum(int(o.is_interesting()) for o in s.outcomes),
len(s.outcomes),
len(s.partial_outcomes),
)
)
if args.summarize:
print()
print("Methods from the summarizer:")
summary.HumanSummarizer(s).print_methods()
print()
print("Starting analysis step...")
ra = recursive_analyzer.RecursiveAnalyzer(
max_wei_to_send=args.max_to_send,
min_wei_to_receive=args.min_to_receive,
block=args.block,
)
bug = ra.check_states(
s.outcomes, timeout=args.analysis_timeout, max_depth=args.max_transaction_depth
)
if bug:
solver = bug[2]
if logging.getLogger().isEnabledFor(logging.DEBUG):
print("Composite state:")
print(bug[0].debug_string())
print()
print()
print("Path:")
for i, state in enumerate(bug[1]):
print()
print("Transaction %i, symbolic state:" % (i + 1))
print(state.debug_string())
print()
print("Transaction %i, example solution:" % (i + 1))
print(state.env.solution_string(solver))
print()
print()
print("======> Bug found! Need %i transactions. <======" % len(bug[1]))
else:
print("Nothing to report.")
if __name__ == "__main__":
main()
================================================
FILE: pakala/env.py
================================================
import pprint
import time
import claripy
from eth.vm import code_stream
from web3 import Web3
from pakala import memory
ENV_VARS = (
("caller", None, None),
("origin", None, None),
("value", None, Web3.toWei(10 ** 6, "ether")),
("address", None, None),
("balance", None, Web3.toWei(10 ** 9, "ether")),
("gas", None, None),
("block_timestamp", int(time.time()), int(time.time() + 86400 * 365)),
("block_number", 6000000, 10 ** 9),
("calldata_size", None, 2 ** 20),
("coinbase", None, None),
("difficulty", None, None),
("chainid", None, None),
)
class Env(object):
def __init__(self, code, **kwargs):
if isinstance(code, code_stream.CodeStream):
self.code = code
else:
self.code = code_stream.CodeStream(code)
self.calldata = memory.CalldataMemory()
self.block_hashes = {}
for name, _, _ in ENV_VARS:
default = claripy.BVS(name, 256)
setattr(self, name, kwargs.get(name, default))
def __repr__(self):
return "Env(balance=%s, caller=%s, value=%s)" % (
self.balance,
self.caller,
self.value,
)
def as_dict(self):
return {"balance": self.balance, "caller": self.caller, "value": self.value}
def clean_copy(self):
"""Create a new env, which is a copy of the current one but with
new symbolic variables (with the same name)"""
new_env = Env(self.code)
for name, _, _ in ENV_VARS:
value = getattr(self, name)
if value.symbolic:
setattr(new_env, name, claripy.BVS(name, 256))
else:
setattr(new_env, name, value)
new_env.calldata = self.calldata.copy()
for addr, value in self.calldata._mem.items():
new_env.calldata._mem[addr] = claripy.BVS(
"calldata[%i]" % addr, value.size()
)
# Block hashes are always the same (but the current number can change)
new_env.block_hashes = self.block_hashes.copy()
return new_env
def extra_constraints(self):
for name, min_, max_ in ENV_VARS:
if min_ is not None:
yield getattr(self, name) >= min_
if max_ is not None:
yield getattr(self, name) <= max_
def solution_string(self, solver):
calldata_size = max(solver.min(self.calldata_size), self.calldata.size())
solution = {
"data": "{0:0{1}x}".format(
solver.min(self.calldata.read(0, calldata_size)), calldata_size * 2
),
"value": solver.min(self.value),
"caller": "{0:#042x}".format(solver.eval(self.caller, 1)[0]),
}
return pprint.pformat(solution, width=90)
def replace(old_env, new_env, var):
"""Replace all the references of old_env to references to new_env, in the
claripy AST var."""
for name, _, _ in ENV_VARS:
var = var.replace(getattr(old_env, name), getattr(new_env, name))
for addr in old_env.calldata._mem.keys():
var = var.replace(old_env.calldata._mem[addr], new_env.calldata._mem[addr])
return var
================================================
FILE: pakala/memory.py
================================================
import logging
import claripy
from pakala import utils
logger = logging.getLogger(__name__)
# Maximum size the memory is allowed to have.
# Can be None if we want it to be unbounded.
MEMORY_SIZE = None
def _slice(v, start, end):
start = v.size() - start * 8 - 1
end = 0 if end is None else (v.size() - end * 8)
assert end >= 0 and start >= 0 and end <= start
return v[start:end]
class Memory(object):
"""Base class for memory. Uninitialized memory is zero initially."""
def __init__(self):
self._mem = {}
def __str__(self):
return str(self._mem)
def __hash__(self):
return hash(tuple(hash(k) ^ hash(v) for k, v in self._mem.items()))
def _default(self, addr, size):
return claripy.BVV(0, size * 8)
def read(self, addr, size):
assert size >= 0
if MEMORY_SIZE and addr + size >= MEMORY_SIZE:
raise utils.CodeError("Memory.read: memory would exceed MEMORY_SIZE")
logger.debug("%s.read(%i, %i)" % (self.__class__.__name__, addr, size))
if size == 0:
return claripy.BVV(0, 0)
for iaddr, ivalue in self._mem.items():
isize = ivalue.size() // 8
raddr = iaddr - addr
rend = iaddr + isize - addr
# completely overlaps (or equals)
if raddr <= 0 and rend >= size:
return _slice(ivalue, -raddr, -raddr + size)
# completely inside (strictly)
elif raddr > 0 and rend < size:
return self.read(addr, raddr).concat(
self.read(addr + raddr, size - raddr)
)
# end inside
elif 0 < rend < size:
return _slice(ivalue, isize - rend, None).concat(
self.read(addr + rend, size - rend)
)
# start inside
elif 0 < raddr < size:
return self.read(addr, raddr).concat(_slice(ivalue, 0, size - raddr))
assert addr not in self._mem
self._mem[addr] = self._default(addr, size)
return self._mem[addr]
def write(self, addr, size, value):
assert size >= 0
assert value.size() // 8 == size, "BVV size doesn't match size in Memory.write"
if MEMORY_SIZE and addr + size >= MEMORY_SIZE:
raise utils.CodeError("Memory.write: memory would exceed MEMORY_SIZE")
logger.debug(
"%s.write(%i, %i, %r)" % (self.__class__.__name__, addr, size, value)
)
if size == 0:
return
for iaddr, ivalue in list(self._mem.items()):
isize = ivalue.size() // 8
raddr = iaddr - addr
rend = raddr + isize
# equal
if raddr == 0 and rend == size:
break
# completely overlaps
elif raddr <= 0 and rend >= size:
if raddr < 0:
self._mem[iaddr] = _slice(ivalue, 0, -raddr)
if rend > size:
self._mem[addr + size] = _slice(ivalue, -raddr + size, None)
# completely inside (not strictly)
elif raddr >= 0 and rend <= size:
del self._mem[iaddr]
# end inside
elif 0 < rend < size:
self._mem[iaddr] = _slice(ivalue, 0, -raddr)
# start inside
elif 0 < raddr < size:
del self._mem[iaddr]
self._mem[addr + size] = _slice(ivalue, size - raddr, None)
self._mem[addr] = value
def copy_from(self, other, start_self, start_other, size):
assert size >= 0
if MEMORY_SIZE and (
start_self + size >= MEMORY_SIZE or start_other + size >= MEMORY_SIZE
):
raise utils.CodeError("Memory.copy_from: memory would exceed MEMORY_SIZE")
if size == 0:
return
self.write(start_self, size, CalldataMemoryView(other, start_other, size))
def size(self):
if not self._mem:
return 0
max_addr = max(self._mem.keys())
return max_addr + self._mem[max_addr].size() // 8
def copy(self):
"""Not to be confused with copy_from. This is to copy the object, not
do any memory operation.
"""
new_memory = self.__class__()
new_memory._mem = self._mem.copy()
return new_memory
class CalldataMemory(Memory):
"""Same as Memory, except that uninitialized memory is set to a BVS."""
def _default(self, addr, size):
return claripy.BVS("calldata[%i]" % addr, size * 8)
def write(self, *args, **kwargs):
assert False, "CalldataMemory is read-only."
def copy_from(self, *args, **kwargs):
assert False, "CalldataMemory is read-only."
class CalldataMemoryView(object):
"""Element to be put in memory like a Claripy BV, but is a view to a part
of another memory."""
def __init__(self, mem, addr, size):
self._mem = mem
self._addr = addr
self._size = size
def __hash__(self):
# TODO: The hash may change even if the part in the view don't...
return hash(self._mem)
def size(self):
return self._size * 8
def __getitem__(self, item):
# If I read the whole view, the thing will crash.
assert isinstance(item, slice)
assert (item.start + 1) % 8 == 0 and item.stop % 8 == 0 and not item.step
start = self._size - (item.start + 1) // 8
stop = self._size - item.stop // 8
size = stop - start
assert size <= self._size and start >= 0
return self._mem.read(self._addr + start, size)
================================================
FILE: pakala/recursive_analyzer.py
================================================
"""
pakala: EVM symbolic execution tool and vulnerability scanner.
Copyright (C) 2018 Korantin Auguste
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import collections
import logging
import functools
import time
import itertools
import claripy
from pakala import analyzer
from pakala import env
from pakala import utils
from pakala.state import State
logger = logging.getLogger(__name__)
DEBUG_MARK_PATH = []
def is_function(state, function):
return state.solver.satisfiable([state.env.calldata.read(0, 4) == function])
def with_new_env(state):
"""Return a new identical state, rooted in a new, independent environment."""
assert state.solver.satisfiable()
old_env = state.env
new_env = old_env.clean_copy()
state = state.copy()
state.env = new_env
state.replace(functools.partial(env.replace, old_env, new_env))
state.replace(state.solver.regenerate_hash_symbols())
for read_k, read_v in state.storage_read.items():
new_v = claripy.BVS("storage[%s]" % read_k, 256)
state.replace(lambda ast: ast.replace(read_v, new_v))
assert state.solver.satisfiable()
return state
class RecursiveAnalyzer(analyzer.BaseAnalyzer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Each element in the queue is a couple:
# 0) State, a state made of the successive applications of all the state
# of the path, except the last one.
# 1) list, path of states we applied.
self.path_queue = collections.deque()
# The dict in the queue before
self.state_done = set()
self.reference_states = []
@property
def address(self):
return self.reference_states[0][0].env.address
@property
def caller(self):
return self.reference_states[0][0].env.caller
def _search_path(self, composite_state, path):
logger.debug("Search path: %s", path)
logger.debug("Composite state: %s", composite_state)
# If we already encountered the same composite state with some other
# path...
if hash(composite_state) in self.state_done:
return
self.state_done.add(hash(composite_state))
logger.debug("Check for bugs in composite state...")
solver_bug = self.check_state(composite_state, path=path)
if solver_bug is not None:
return solver_bug
# If we kill the contract, we can't make any more call!
if path[-1].selfdestruct_to is not None:
return
# We have to downsize the used solver to free memory in z3, otherwise
# they will collectively end up eating all the memory.
composite_state.solver.downsize()
# For each reference state, find the right one (with an unused env)
# and add it to the queue.
for reference_states in self.reference_states:
for reference_state in reference_states:
if all(s is not reference_state for s in path):
self.path_queue.append(
(composite_state.copy(), path + [reference_state])
)
break
def _append_state(self, composite_state, state):
# TODO: Simplify/split that function. A bit too complex.
logger.debug(
"_append_state: appending state %s\nto composite state %s",
state.debug_string(),
composite_state.debug_string(),
)
assert composite_state.selfdestruct_to is None
composite_state.solver = composite_state.solver.combine([state.solver])
# TODO: Is that better to include even if not strictly needed?
# composite_state.storage_read.update(state.storage_read)
if not composite_state.solver.satisfiable():
return []
assert state.solver.satisfiable()
for call in state.calls:
composite_state.calls.append(call)
if state.selfdestruct_to is not None:
composite_state.selfdestruct_to = state.selfdestruct_to
# Resolve read/write
def apply_read(r_key, r_val, composite_state):
"""Apply a read operation with (key, value) to the state."""
composite_states_next = []
# Here we consider the cases where it's possible to read something
# we previously wrote to.
not_overwritten_c = []
for w_key, w_val in composite_state.storage_written.items():
read_written = [r_key == w_key, r_val == w_val]
not_overwritten_c.append(r_key != w_key)
cs = composite_state.copy()
cs.solver.add(read_written)
if cs.solver.satisfiable():
composite_states_next.append(cs)
logger.debug(
"Found key read %s, corresponding to key written %s",
r_key,
w_key,
)
# Is it not something we previously wrote to?
composite_state.solver.add(not_overwritten_c)
composite_state.solver.add(
state.storage_read[r_key] == self._read_storage(state, r_key)
)
if composite_state.solver.satisfiable():
composite_states_next.append(composite_state)
return composite_states_next
composite_states = [composite_state]
for r_key, r_val in state.storage_read.items():
composite_states = list(
itertools.chain.from_iterable(
apply_read(r_key, r_val, composite_state)
for composite_state in composite_states
)
)
for composite_state in composite_states:
# Delete any storage_written at the same key in the composite
# state.
for c_key in list(composite_state.storage_written.keys()):
for key in state.storage_written.keys():
if not composite_state.solver.satisfiable(
extra_constraints=[key != c_key]
):
del composite_state.storage_written[c_key]
break
for key, val in state.storage_written.items():
composite_state.storage_written[key] = val
logger.debug("_append_state: found states:")
for composite_state in composite_states:
logger.debug(composite_state.debug_string())
return composite_states
def check_states(self, states, timeout, max_depth):
states = [state for state in states if state.is_interesting()]
if not states:
return
# Each state must have its own independent environment
assert not self.reference_states
# For each state, a list of equivalent state, but each in a different
# env so that they can be stacked together.
self.reference_states = []
for state in states:
self.reference_states.append(
[with_new_env(state) for _ in range(max_depth)]
)
# Add it to the paths to explore
self.path_queue.append((State(), [self.reference_states[-1][0]]))
# Recursive exploration
last_path_len = 0
time_start = time.process_time()
while self.path_queue:
initial_composite_state, path = self.path_queue.popleft()
if len(path) > last_path_len:
logger.log(
utils.INFO_INTERACTIVE,
"Now scanning paths of length %i.",
len(path),
)
last_path_len = len(path)
if len(path) > max_depth:
logger.debug("Over the max allowed depth, stopping.")
return
if DEBUG_MARK_PATH and all(
is_function(s, f) for s, f in zip(path, DEBUG_MARK_PATH)
):
logger.warning("DEBUG_MARK_PATH len %i", len(path))
logger.warning("path: %s", path)
breakpoint()
new_composite_states = self._append_state(initial_composite_state, path[-1])
for composite_state in new_composite_states:
solver = self._search_path(composite_state, path)
if solver is not None:
return composite_state, path, solver
if timeout and time.process_time() - time_start > timeout:
logger.debug("Timeout at depth %i, stopping.", len(path))
return
================================================
FILE: pakala/sm.py
================================================
"""
pakala: EVM symbolic execution tool and vulnerability scanner.
Copyright (C) 2018 Korantin Auguste
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import collections
import heapq
import logging
import math
import numbers
import time
import traceback
import claripy
from eth.vm import opcode_values
from pakala import utils
from pakala.state import State
from pakala.claripy_sha3 import Sha3
logger = logging.getLogger(__name__) # pylint:disable=invalid-name
bvv = utils.bvv # pylint:disable=invalid-name
BVV_0 = bvv(0)
BVV_1 = bvv(1)
# interesting values aligned to classic parameters.
CALLDATALOAD_INDEX_FUZZ = set(range(0, 32 * 3, 32)) | set(range(4, 32 * 5, 32))
CALLDATACOPY_SIZE_FUZZ = set(range(9)) | {0, 32} | {4, 34, 4 + 32 * 16}
RETURNDATACOPY_SIZE_FUZZ = {0, 32}
EXP_EXPONENT_FUZZ = {min, max}
class MultipleSolutionsError(ValueError):
pass
def bool_to_bv(b):
return claripy.If(b, BVV_1, BVV_0)
class SymbolicMachine:
"""Class to represent a state of a EVM program, and execute it symbolically.
"""
def __init__(self, env, fuzz=True):
self.code = env.code
logger.debug("Initializing symbolic machine with source code: %s", self.code)
# For use by heapq only. Contains couples (score, state).
self.branch_queue = []
self.states_seen = set()
self.coverage = [0] * len(self.code)
# List of all normal/good terminations of the contract
self.outcomes = []
# List of all the place where we didn't know how to continue execution
self.partial_outcomes = []
# Do we want to enable fuzzing? (see add_for_fuzzing below)
self.fuzz = fuzz
# Did fuzzing got used?
self.fuzzed = False
# Errors that happened during execution. These are normal.
self.code_errors = collections.Counter()
# Errors of the interpreter / symbolic execution engine. Not cool :(
self.interpreter_errors = collections.Counter()
self.add_branch(State(env))
def add_branch(self, state):
"""Add a state corresponding to a branch to be executed."""
if not state.solver.satisfiable():
logger.debug("Avoided adding unsatisfiable state.")
return
if hash(state) in self.states_seen:
logger.debug("Avoided adding visited state.")
self.code_errors["Avoided adding visited state"] += 1
return
# We have to downsize the used solver to free memory in z3, otherwise
# they will collectively end up eating all the memory.
state.solver.downsize()
state.solver.simplify()
logger.debug(
"Adding branch to %i with depth %i (visited %i times)",
state.pc,
state.depth,
self.coverage[state.pc] if state.pc < len(self.coverage) else 0,
)
heapq.heappush(self.branch_queue, (state.depth, state))
self.states_seen.add(hash(state))
def add_for_fuzzing(self, state, variable, tries):
"""
Will try to fuzz the variable, setting it to different values.
The tries parameter must be an array of :
- min: if you want to add the minimum value possible
- max: if you want to add the maximum value possible
- a number: to try that number
- None: a random number that works, you can repeat it.
"""
# TODO: If the fuzzer is used, then I will generate tons of branches
# that are equivalent... There should be a way to deduplicate them,
# but it's not trivial.
if not self.fuzz:
raise utils.InterpreterError(state, "Fuzzer is disabled")
if not self.fuzzed:
self.fuzzed = True
logger.warning(
"Fuzzer got used (forced concretization). "
"We will lose accuracy and risk state explosion."
)
to_try = set()
nb_random = 0
for t in tries: # pylint:disable=invalid-name
if isinstance(t, numbers.Number) and state.solver.solution(variable, t):
to_try.add(t)
elif t is min:
to_try.add(state.solver.min(variable))
elif t is max:
to_try.add(state.solver.max(variable))
elif t is None:
nb_random += 1
if nb_random:
to_try |= set(state.solver.eval(variable, nb_random))
logger.debug("Fuzzing will try %s in %s.", variable, to_try)
state.depth += (
1 if len(to_try) == 1 else 10
) # Lower the priority of what we got by fuzzing.
for value in to_try:
new_state = state.copy()
new_state.solver.add(variable == value)
self.add_branch(new_state)
def exec_branch(self, state): # pylint:disable=invalid-name
"""Execute forward from a state, queuing new states if needed."""
logger.debug("Constraints: %s", state.solver.constraints)
def solution(variable):
"""Returns the solution. There must be one or we fail."""
solutions = state.solver.eval(variable, 2)
if len(solutions) > 1:
raise MultipleSolutionsError(
"Multiple solutions for %s (%#x)" % (variable, self.code[state.pc])
)
solution = solutions[0]
return solution if isinstance(solution, numbers.Number) else solution.value
while True:
if state.pc >= len(self.code):
return True
op = self.code[state.pc]
self.coverage[state.pc] += 1
logger.debug("NEW STEP")
logger.debug("Memory: %s", state.memory)
logger.debug("Stack: %s", state.stack)
logger.debug("PC: %i, %#x", state.pc, op)
assert isinstance(op, numbers.Number)
assert all(
isinstance(i, claripy.ast.base.BV) for i in state.stack
), "The stack musty only contains claripy BV's"
# Trivial operations first
if not self.code.is_valid_opcode(state.pc):
raise utils.CodeError("Trying to execute PUSH data")
elif op == 254: # INVALID opcode
raise utils.CodeError("designed INVALID opcode")
elif op == opcode_values.JUMPDEST:
pass
elif op == opcode_values.ADD:
s0, s1 = (
state.stack_pop(),
state.stack_pop(),
) # pylint:disable=invalid-name
state.stack_push(s0 + s1)
elif op == opcode_values.SUB:
s0, s1 = (
state.stack_pop(),
state.stack_pop(),
) # pylint:disable=invalid-name
state.stack_push(s0 - s1)
elif op == opcode_values.MUL:
s0, s1 = (
state.stack_pop(),
state.stack_pop(),
) # pylint:disable=invalid-name
state.stack_push(s0 * s1)
elif op == opcode_values.DIV:
# We need to use claripy.LShR instead of a division if possible,
# because the solver is bad dealing with divisions, better
# with shifts. And we need shifts to handle the solidity ABI
# for function selection.
s0, s1 = (
state.stack_pop(),
state.stack_pop(),
) # pylint:disable=invalid-name
try:
s1 = solution(s1) # pylint:disable=invalid-name
except MultipleSolutionsError:
state.stack_push(claripy.If(s1 == 0, BVV_0, s0 / s1))
else:
if s1 == 0:
state.stack_push(BVV_0)
elif s1 == 1:
state.stack_push(s0)
elif s1 & (s1 - 1) == 0:
exp = int(math.log(s1, 2))
state.stack_push(s0.LShR(exp))
else:
state.stack_push(s0 / s1)
elif op == opcode_values.SDIV:
s0, s1 = (
state.stack_pop(),
state.stack_pop(),
) # pylint:disable=invalid-name
try:
s1 = solution(s1)
except MultipleSolutionsError:
state.stack_push(claripy.If(s1 == 0, BVV_0, s0.SDiv(s1)))
else:
state.stack_push(BVV_0 if s1 == 0 else s0.SDiv(s1))
elif op == opcode_values.MOD:
s0, s1 = (
state.stack_pop(),
state.stack_pop(),
) # pylint:disable=invalid-name
try:
s1 = solution(s1)
except MultipleSolutionsError:
state.stack_push(claripy.If(s1 == 0, BVV_0, s0 % s1))
else:
state.stack_push(BVV_0 if s1 == 0 else s0 % s1)
elif op == opcode_values.SMOD:
s0, s1 = (
state.stack_pop(),
state.stack_pop(),
) # pylint:disable=invalid-name
try:
s1 = solution(s1)
except MultipleSolutionsError:
state.stack_push(claripy.If(s1 == 0, BVV_0, s0.SMod(s1)))
else:
state.stack_push(BVV_0 if s1 == 0 else s0.SMod(s1))
elif op == opcode_values.ADDMOD:
s0, s1, s2 = state.stack_pop(), state.stack_pop(), state.stack_pop()
try:
s2 = solution(s2)
except MultipleSolutionsError:
state.stack_push(claripy.If(s2 == 0, BVV_0, (s0 + s1) % s2))
else:
state.stack_push(BVV_0 if s2 == 0 else (s0 + s1) % s2)
elif op == opcode_values.MULMOD:
s0, s1, s2 = state.stack_pop(), state.stack_pop(), state.stack_pop()
try:
s2 = solution(s2)
except MultipleSolutionsError:
state.stack_push(claripy.If(s2 == 0, BVV_0, (s0 * s1) % s2))
else:
state.stack_push(BVV_0 if s2 == 0 else (s0 * s1) % s2)
elif op == opcode_values.SHL:
shift, value = state.stack_pop(), state.stack_pop()
state.stack_push(value << shift)
elif op == opcode_values.SHR:
shift, value = state.stack_pop(), state.stack_pop()
state.stack_push(value.LShR(shift))
elif op == opcode_values.SAR:
shift, value = state.stack_pop(), state.stack_pop()
state.stack_push(claripy.RotateRight(value, shift))
elif op == opcode_values.EXP:
base, exponent = state.stack_pop(), state.stack_pop()
base_sol = solution(base)
if base_sol == 2:
state.stack_push(1 << exponent)
else:
try:
exponent_sol = solution(exponent)
except MultipleSolutionsError:
state.stack_push(exponent) # restore stack
state.stack_push(base)
self.add_for_fuzzing(state, exponent, EXP_EXPONENT_FUZZ)
return False
else:
state.stack_push(claripy.BVV(base_sol ** exponent_sol, 256))
elif op == opcode_values.LT:
s0, s1 = (
state.stack_pop(),
state.stack_pop(),
) # pylint:disable=invalid-name
state.stack_push(bool_to_bv(claripy.ULT(s0, s1)))
elif op == opcode_values.GT:
s0, s1 = (
state.stack_pop(),
state.stack_pop(),
) # pylint:disable=invalid-name
state.stack_push(bool_to_bv(claripy.UGT(s0, s1)))
elif op == opcode_values.SLT:
s0, s1 = (
state.stack_pop(),
state.stack_pop(),
) # pylint:disable=invalid-name
state.stack_push(bool_to_bv(claripy.SLT(s0, s1)))
elif op == opcode_values.SGT:
s0, s1 = (
state.stack_pop(),
state.stack_pop(),
) # pylint:disable=invalid-name
state.stack_push(bool_to_bv(claripy.SGT(s0, s1)))
elif op == opcode_values.SIGNEXTEND:
# TODO: Use Claripy's SignExt that should do exactly that.
s0, s1 = (
state.stack_pop(),
state.stack_pop(),
) # pylint:disable=invalid-name
# s0 is the number of bits. s1 the number we want to extend.
s0 = solution(s0)
if s0 <= 31:
sign_bit = 1 << (s0 * 8 + 7)
state.stack_push(
claripy.If(
s1 & sign_bit == 0,
s1 & (sign_bit - 1),
s1 | ((1 << 256) - sign_bit),
)
)
else:
state.stack_push(s1)
elif op == opcode_values.EQ:
s0, s1 = state.stack_pop(), state.stack_pop()
state.stack_push(bool_to_bv(s0 == s1))
elif op == opcode_values.ISZERO:
state.stack_push(bool_to_bv(state.stack_pop() == BVV_0))
elif op == opcode_values.AND:
s0, s1 = state.stack_pop(), state.stack_pop()
state.stack_push(s0 & s1)
elif op == opcode_values.OR:
s0, s1 = state.stack_pop(), state.stack_pop()
state.stack_push(s0 | s1)
elif op == opcode_values.XOR:
s0, s1 = state.stack_pop(), state.stack_pop()
state.stack_push(s0 ^ s1)
elif op == opcode_values.NOT:
state.stack_push(~state.stack_pop())
elif op == opcode_values.BYTE:
s0, s1 = (
state.stack_pop(),
state.stack_pop(),
) # pylint:disable=invalid-name
state.stack_push(s1.LShR(claripy.If(s0 > 31, 32, 31 - s0) * 8) & 0xFF)
elif op == opcode_values.PC:
state.stack_push(bvv(state.pc))
elif op == opcode_values.GAS:
state.stack_push(state.env.gas)
elif op == opcode_values.ADDRESS:
state.stack_push(state.env.address)
elif op == opcode_values.CHAINID:
state.stack_push(state.env.chainid)
elif op == opcode_values.SELFBALANCE:
state.stack_push(state.env.balance)
elif op == opcode_values.BALANCE:
addr = solution(state.stack_pop())
if addr != solution(state.env.address):
raise utils.InterpreterError(
state, "Can only query balance of the current contract for now"
)
state.stack_push(state.env.balance)
elif op == opcode_values.ORIGIN:
state.stack_push(state.env.origin)
elif op == opcode_values.CALLER:
state.stack_push(state.env.caller)
elif op == opcode_values.CALLVALUE:
state.stack_push(state.env.value)
elif op == opcode_values.BLOCKHASH:
block_num = state.stack_pop()
if block_num not in state.env.block_hashes:
state.env.block_hashes[block_num] = claripy.BVS(
"blockhash[%s]" % block_num, 256
)
state.stack_push(state.env.block_hashes[block_num])
elif op == opcode_values.TIMESTAMP:
state.stack_push(state.env.block_timestamp)
elif op == opcode_values.NUMBER:
state.stack_push(state.env.block_number)
elif op == opcode_values.COINBASE:
state.stack_push(state.env.coinbase)
elif op == opcode_values.DIFFICULTY:
state.stack_push(state.env.difficulty)
elif op == opcode_values.POP:
state.stack_pop()
elif op == opcode_values.JUMP:
addr = solution(state.stack_pop())
if addr >= len(self.code) or self.code[addr] != opcode_values.JUMPDEST:
raise utils.CodeError("Invalid jump (%i)" % addr)
state.pc = addr
self.add_branch(state)
return False
elif op == opcode_values.JUMPI:
addr, condition = solution(state.stack_pop()), state.stack_pop()
state_false = state.copy()
state.solver.add(condition != BVV_0)
state_false.solver.add(condition == BVV_0)
state_false.pc += 1
self.add_branch(state_false)
state.pc = addr
if (
state.pc >= len(self.code)
or self.code[state.pc] != opcode_values.JUMPDEST
):
raise utils.CodeError("Invalid jump (%i)" % (state.pc - 1))
self.add_branch(state)
return False
elif opcode_values.PUSH1 <= op <= opcode_values.PUSH32:
pushnum = op - opcode_values.PUSH1 + 1
self.code.program_counter = state.pc + 1
raw_value = self.code.read(pushnum)
state.pc += pushnum
state.stack_push(bvv(int.from_bytes(raw_value, byteorder="big")))
elif opcode_values.DUP1 <= op <= opcode_values.DUP16:
depth = op - opcode_values.DUP1 + 1
state.stack_push(state.stack[-depth])
elif opcode_values.SWAP1 <= op <= opcode_values.SWAP16:
depth = op - opcode_values.SWAP1 + 1
temp = state.stack[-depth - 1]
state.stack[-depth - 1] = state.stack[-1]
state.stack[-1] = temp
elif opcode_values.LOG0 <= op <= opcode_values.LOG4:
depth = op - opcode_values.LOG0
mstart, msz = (state.stack_pop(), state.stack_pop())
topics = [state.stack_pop() for x in range(depth)]
elif op == opcode_values.SHA3:
start, length = solution(state.stack_pop()), solution(state.stack_pop())
memory = state.memory.read(start, length)
state.stack_push(Sha3(memory))
elif op == opcode_values.STOP:
return True
elif op == opcode_values.RETURN:
return True
elif op == opcode_values.CALLDATALOAD:
index = state.stack_pop()
try:
index_sol = solution(index)
except MultipleSolutionsError:
state.stack_push(index) # restore the stack
self.add_for_fuzzing(state, index, CALLDATALOAD_INDEX_FUZZ)
return False
state.stack_push(state.env.calldata.read(index_sol, 32))
elif op == opcode_values.CALLDATASIZE:
state.stack_push(state.env.calldata_size)
elif op == opcode_values.CALLDATACOPY:
old_state = state.copy()
mstart, dstart, size = (
state.stack_pop(),
state.stack_pop(),
state.stack_pop(),
)
mstart, dstart = solution(mstart), solution(dstart)
try:
size = solution(size)
except MultipleSolutionsError:
self.add_for_fuzzing(old_state, size, CALLDATACOPY_SIZE_FUZZ)
return False
state.memory.copy_from(state.env.calldata, mstart, dstart, size)
elif op == opcode_values.CODESIZE:
state.stack_push(bvv(len(self.code)))
elif op == opcode_values.EXTCODESIZE:
addr = state.stack_pop()
if (addr == state.env.address).is_true():
state.stack_push(bvv(len(self.code)))
else:
# TODO: Improve that... It's clearly not constraining enough.
state.stack_push(claripy.BVS("EXTCODESIZE[%s]" % addr, 256))
elif op == opcode_values.EXTCODECOPY:
old_state = state.copy()
addr = state.stack_pop()
mem_start = solution(state.stack_pop())
code_start = solution(state.stack_pop())
size = state.stack_pop()
try:
size = solution(size)
except MultipleSolutionsError:
# TODO: Fuzz.
# self.add_for_fuzzing(old_state, size, [])
# return False
raise
state.memory.write(
mem_start,
size,
claripy.BVS("EXTCODE[%s from %s]" % (addr, code_start), size * 8),
)
elif op == opcode_values.CODECOPY:
mem_start, code_start, size = [
solution(state.stack_pop()) for _ in range(3)
]
for i in range(size):
if code_start + i < len(state.env.code):
state.memory.write(
mem_start + i,
1,
claripy.BVV(state.env.code[code_start + i], 8),
)
else:
state.memory.write(mem_start + i, 1, claripy.BVV(0, 8))
elif op == opcode_values.MLOAD:
index = solution(state.stack_pop())
state.stack_push(state.memory.read(index, 32))
elif op == opcode_values.MSTORE:
index, value = solution(state.stack_pop()), state.stack_pop()
state.memory.write(index, 32, value)
elif op == opcode_values.MSTORE8:
index, value = solution(state.stack_pop()), state.stack_pop()
state.memory.write(index, 1, value[7:0])
elif op == opcode_values.MSIZE:
state.stack_push(bvv(state.memory.size()))
elif op == opcode_values.SLOAD:
state.pc += 1
key = state.stack_pop()
for w_key, w_value in state.storage_written.items():
read_written = [w_key == key]
if state.solver.satisfiable(extra_constraints=read_written):
new_state = state.copy()
new_state.solver.add(read_written)
new_state.stack_push(w_value)
self.add_branch(new_state)
state.solver.add(w_key != key)
if state.solver.satisfiable():
assert key not in state.storage_written
if key not in state.storage_read:
state.storage_read[key] = claripy.BVS("storage[%s]" % key, 256)
state.stack_push(state.storage_read[key])
self.add_branch(state)
return
elif op == opcode_values.SSTORE:
state.pc += 1
key = state.stack_pop()
value = state.stack_pop()
for w_key, w_value in state.storage_written.items():
read_written = [w_key == key]
if state.solver.satisfiable(extra_constraints=read_written):
new_state = state.copy()
new_state.solver.add(read_written)
new_state.storage_written[w_key] = value
self.add_branch(new_state)
state.solver.add(w_key != key)
if state.solver.satisfiable():
assert key not in state.storage_written
state.storage_written[key] = value
self.add_branch(state)
return
elif op == opcode_values.CALL:
state.pc += 1
# pylint:disable=unused-variable
gas, to_, value, meminstart, meminsz, memoutstart, memoutsz = (
state.stack_pop() for _ in range(7)
)
# First possibility: the call fails
# (always possible with a call stack big enough)
state_fail = state.copy()
state_fail.stack_push(BVV_0)
self.add_branch(state_fail)
# Second possibility: success.
state.calls.append(
(memoutsz, memoutstart, meminsz, meminstart, value, to_, gas)
)
memoutsz = solution(memoutsz)
if memoutsz != 0:
# If we expect some output, let's constraint the call to
# be to a contract that we do control. Otherwise it could
# return anything...
state.solver.add(to_[159:0] == utils.DEFAULT_CALLER[159:0])
memoutstart = solution(memoutstart)
state.memory.write(
memoutstart,
memoutsz,
claripy.BVS("CALL_RETURN[%s]" % to_, memoutsz * 8),
)
state.stack_push(BVV_1)
self.add_branch(state)
return False
elif op == opcode_values.DELEGATECALL:
state.pc += 1
# pylint:disable=unused-variable
gas, to_, meminstart, meminsz, memoutstart, memoutsz = (
state.stack_pop() for _ in range(6)
)
# First possibility: the call fails
# (always possible with a call stack big enough)
state_fail = state.copy()
state_fail.stack_push(BVV_0)
self.add_branch(state_fail)
# If the call is to a specific contract we don't control,
# don't assume it could return anything, or even be successful.
# So we say we need to be able to call an arbitrary contract.
state.solver.add(to_[159:0] == utils.DEFAULT_CALLER[159:0])
# Second possibility: success.
state.calls.append(
(memoutsz, memoutstart, meminsz, meminstart, to_, gas)
)
memoutsz = solution(memoutsz)
if memoutsz != 0:
memoutstart = solution(memoutstart)
state.memory.write(
memoutstart,
memoutsz,
claripy.BVS("DELEGATECALL_RETURN[%s]" % to_, memoutsz * 8),
)
state.stack_push(BVV_1)
self.add_branch(state)
return False
elif op == opcode_values.RETURNDATASIZE:
state.stack_push(claripy.BVS("RETURNDATASIZE", 256))
elif op == opcode_values.RETURNDATACOPY:
old_state = state.copy()
mem_start_position = solution(state.stack_pop())
returndata_start_position = solution(state.stack_pop())
size = state.stack_pop()
try:
size = solution(size)
except MultipleSolutionsError:
self.add_for_fuzzing(old_state, size, RETURNDATACOPY_SIZE_FUZZ)
return False
state.memory.write(
mem_start_position, size, claripy.BVS("RETURNDATACOPY", size * 8)
)
elif op == opcode_values.SELFDESTRUCT:
state.selfdestruct_to = state.stack[-1]
return True
elif op == opcode_values.REVERT:
return False
else:
raise utils.InterpreterError(state, "Unknown opcode %#x" % op)
state.pc += 1
def execute(self, timeout_sec):
"""Run the code, searching for all the interesting outcomes.
Returns the process time it took to execute.
"""
if self.outcomes:
raise RuntimeError("Already executed.")
time_start = time.process_time()
time_last_coverage_increase = time_start
last_coverage = 0
while self.branch_queue:
coverage = sum(bool(c) for c in self.coverage)
if coverage > last_coverage:
if time.process_time() - time_last_coverage_increase > 1:
logger.log(
utils.INFO_INTERACTIVE,
"Coverage now %i%%. Queue size %i. Got %i outcomes.",
int(self.get_coverage() * 100),
len(self.branch_queue),
len(self.outcomes),
)
time_last_coverage_increase = time.process_time()
last_coverage = coverage
if (
not timeout_sec
and time.process_time() - time_last_coverage_increase
> max(120, time_last_coverage_increase - time_start)
) or (timeout_sec and time.process_time() - time_start > timeout_sec):
logger.debug("Timeout.")
self.interpreter_errors["execute timeout"] += 1
break
depth, state = heapq.heappop(self.branch_queue)
state.depth += 1
logger.debug("Executing branch at %i with depth %i.", state.pc, depth)
try:
success = self.exec_branch(state)
except KeyboardInterrupt:
self.interpreter_errors["KeyboardInterrupt"] += 1
break
except (utils.CodeError, claripy.errors.UnsatError) as error:
logger.debug("Code error: %s", error)
self.code_errors[repr(error)] += 1
except (
utils.InterpreterError,
claripy.errors.ClaripyError,
MultipleSolutionsError,
ZeroDivisionError,
) as error:
logger.debug("Interpreter error: %s", error)
logger.debug(traceback.format_exc())
self.interpreter_errors[repr(error)] += 1
if isinstance(error, utils.InterpreterError):
self.add_partial_outcome(error.state)
else:
if success:
self.add_outcome(state)
logger.debug("Branch done.")
# In case of timeouts, we still have unfinished branches in the queue!
# Add them as partial outcomes.
while self.branch_queue:
depth, state = heapq.heappop(self.branch_queue)
self.add_partial_outcome(state)
logger.info(
"Analysis finished with %i outcomes (%i interesting, %i unfinished), "
"coverage is %i%%",
len(self.outcomes),
sum(int(o.is_interesting()) for o in self.outcomes),
len(self.partial_outcomes),
int(self.get_coverage() * 100),
)
if self.code_errors:
logger.info("Code errors encountered: %s", self.code_errors.most_common())
if self.interpreter_errors:
logger.info(
"Interpreter errors encountered: %s",
self.interpreter_errors.most_common(),
)
logger.debug("List of outcomes:")
for outcome in self.outcomes:
logger.debug(outcome.debug_string())
def add_outcome(self, state):
"""Add an outcome to the list."""
state.clean()
logger.debug("Adding outcome: %s", state.debug_string())
self.outcomes.append(state)
def add_partial_outcome(self, state):
"""Add an outcome to the list of partial outcomes."""
state.clean()
logger.debug("Adding partial outcome: %s", state.debug_string())
self.partial_outcomes.append(state)
def get_coverage(self):
"""Return the ratio of instructions that were executed by the total
number of instructions."""
logger.debug("Coverage analysis:")
total_lines = 0
covered_lines = 0
self.code.program_counter = 0
for pc, instruction in enumerate(self.code): # pylint:disable=invalid-name
if pc == len(self.code):
break
if not self.code.is_valid_opcode(pc):
continue
if instruction == opcode_values.JUMPDEST:
logger.debug(
" {:04x}: {}".format(
pc, "covered" if self.coverage[pc] else "not covered"
)
)
total_lines += 1
covered_lines += bool(self.coverage[pc])
return covered_lines / float(total_lines or 1)
================================================
FILE: pakala/state.py
================================================
import logging
import pprint
import json
from pakala import memory
from pakala import utils
logger = logging.getLogger(__name__)
class State(object):
"""Represents a state during the execution of a contract.
It also contains the interactions with the world.
"""
def __init__(self, env=None):
self.env = env
self.pc = 0 # pylint:disable=invalid-name
self.stack = []
# The "depth" we needed to reach that state. Basically how many branches
# we executed to reach it (can be increased more if we got there by fuzzing).
self.depth = 0
self.memory = memory.Memory()
# That's an override to the storage in the blockchain.
# It's the storage that has been written at the end of the execution of
# the contract.
self.storage_written = {}
# Storage read while executing the contract.
self.storage_read = {}
self.calls = []
self.selfdestruct_to = None
self.solver = utils.get_solver()
def __repr__(self):
return (
"State(selfdestruct_to=%s, calls=%s, storage_written=%s, "
"storage_read=%s, env=%s, solver=%s)"
) % (
self.selfdestruct_to,
self.calls,
self.storage_written,
self.storage_read,
self.env,
self.solver,
)
def _as_dict(self):
return {
"selfdestruct_to": self.selfdestruct_to,
"calls": self.calls,
"storage_written": self.storage_written,
"storage_read": self.storage_read,
"env": None if self.env is None else self.env.as_dict(),
"solver": self.solver.as_dict(),
}
def debug_string(self):
WIDTH = 90 # Arbitrary choice.
try:
return pprint.pformat(self._as_dict(), width=WIDTH)
except Exception:
# This can happen when pprint is trying to evaluate a claripy
# object for pretty-printing (during sorted()) and there is no
# simple way to avoid it.
# Let's try to pprint what we can. Otherwise fallback to repr().
s = "{\n"
for k, v in self._as_dict().items():
s += '"%s": ' % k
try:
s += pprint.pformat(v, width=WIDTH)
except Exception:
s += repr(v)
s += ",\n"
s += "}"
return s
def clean(self):
"""Clean the state, when it won't be executed anymore and we are only
interested by the calls, selfdestructs..."""
self.stack = []
self.memory = memory.Memory()
self.solver.downsize()
def replace(self, r):
"""Call r() repeatedly, with every single AST that's present in the
state:
- in storage, read and written
- calls
- in selfdestruct data
- in solver constraints
r() can replace symbols in the AST by other symbols. Generally, r() is
derived from Env.replace(), to substitute an environment with another.
"""
logger.debug("State.replace %s", r)
self.storage_written = {r(k): r(v) for k, v in self.storage_written.items()}
self.storage_read = {r(k): r(v) for k, v in self.storage_read.items()}
self.calls = [[r(i) for i in call] for call in self.calls]
self.selfdestruct_to = (
None if self.selfdestruct_to is None else r(self.selfdestruct_to)
)
self.solver.replace(r)
def __hash__(self):
l = [
hash(self.env),
hash(self.pc),
hash(self.memory),
hash(self.selfdestruct_to),
]
for i in self.stack:
l.append(hash(i))
for call in self.calls:
for arg in call:
l.append(hash(arg))
# The following is because the ordering shouldn't matter:
x = 0
for k, v in self.storage_written.items():
x ^= hash((k, v))
l.append(x)
for k, v in self.storage_read.items():
x ^= hash((k, v))
l.append(x)
for constraint in self.solver.constraints:
x ^= hash(constraint)
l.append(x)
return hash(tuple(l))
def stack_push(self, x):
if len(self.stack) >= 1024:
raise utils.CodeError("Stack overflow")
self.stack.append(x)
def stack_pop(self):
if not self.stack:
raise utils.CodeError("Stack underflow")
return self.stack.pop()
def is_interesting(self):
return bool(
self.storage_written or self.calls or self.selfdestruct_to is not None
)
def copy(self):
"""Make a shallow copy of the current environment. Needs to be fast."""
new_state = State(self.env)
new_state.pc = self.pc
new_state.stack = self.stack[:]
new_state.memory = self.memory.copy()
new_state.storage_written = self.storage_written.copy()
new_state.storage_read = self.storage_read.copy()
new_state.solver = self.solver.branch()
new_state.calls = self.calls[:]
new_state.selfdestruct_to = self.selfdestruct_to
new_state.depth = self.depth
return new_state
# TODO(palkeo): Get rid of that. Needed because of heapq in sm.py...
def __eq__(self, other):
return 1
def __ne__(self, other):
return 0
__lt__ = __ne__
__gt__ = __ne__
__ge__ = __eq__
__le__ = __eq__
================================================
FILE: pakala/summary.py
================================================
"""Experimental module to print basic information about a contract.
For now it gives a list of its methods (and try to resolve the name from their
signatures), and interesting properties inferred on them (onlyOwner? can we send
money to that method?...).
"""
import collections
import json
import lzma
# TODO: Don't hardcode it...
SIGNATURE_FILE = "../signatures.json.xz"
class HumanSummarizer:
def __init__(self, symbolic_machine):
self.signatures = json.load(lzma.open(SIGNATURE_FILE))
self.signatures["0x00000000"] = "fallback"
for magic, signature in self.signatures.items():
assert isinstance(signature, str)
assert isinstance(magic, str)
assert magic.startswith("0x"), magic
assert len(magic) == 10, magic
assert int(magic, 16) is not None # Should not raise any exception
self.sm = symbolic_machine
def states_by_method(self):
states = self.sm.outcomes + self.sm.partial_outcomes
m = collections.defaultdict(list)
for state in states:
signature = 0
solutions = state.solver.eval(state.env.calldata.read(0, 4), 2)
assert solutions, "All states should be reachable"
if len(solutions) == 1:
signature = solutions[0]
# If there are multiple solutions, signature stays null, which will be
# the default method.
m["{0:#010x}".format(signature)].append(state)
return m
def print_methods(self):
for method, states in sorted(self.states_by_method().items()):
signature = self.signatures.get(method, "")
flags = set()
all_not_payable = True
all_only_payable = True
for state in states:
if state.calls:
flags.add("call")
if state.selfdestruct_to is not None:
flags.add("selfdestruct")
for s in self.sm.partial_outcomes:
if state is s:
flags.add("errored")
for s in self.sm.outcomes:
if state is s and state.is_interesting():
flags.add("interesting")
if state.solver.satisfiable(extra_constraints=[state.env.value > 0]):
all_not_payable = False
if state.solver.satisfiable(extra_constraints=[state.env.value == 0]):
all_only_payable = False
# TODO: actually read the storage...
read_constraints = [v == 1 for v in state.storage_read.values()]
try:
callers = state.solver.eval(
state.env.caller[159:0], 2, extra_constraints=read_constraints
)
if len(callers) == 1:
flags.add("onlyOwner")
except Exception:
pass
state.solver.downsize()
if all_not_payable:
flags.add("notPayable")
if all_only_payable:
flags.add("onlyPayable")
print("%s %s %s" % (method, signature.ljust(40), " ".join(sorted(flags))))
================================================
FILE: pakala/test_analyzer.py
================================================
import claripy
import unittest
from unittest.mock import patch
import logging
from pakala.analyzer import Analyzer
from pakala.env import Env
from pakala.state import State
from pakala import utils
from web3 import Web3
logging.basicConfig(level=logging.DEBUG)
class TestCheckState(unittest.TestCase):
def setUp(self):
self.env = Env(b"", caller=utils.DEFAULT_CALLER, address=utils.DEFAULT_ADDRESS)
self.state = State(self.env)
self.analyzer = Analyzer(
address=self.env.address,
caller=self.env.caller,
max_wei_to_send=Web3.toWei(10, "ether"),
min_wei_to_receive=Web3.toWei(1, "milliether"),
)
def check_state(self, state):
return self.analyzer.check_state(state)
def get_call(self, value, to=None):
if to is None:
to = self.env.caller
return [
utils.bvv(0),
utils.bvv(0),
utils.bvv(0),
utils.bvv(0),
value,
to,
utils.bvv(0),
]
def get_delegatecall(self, to=None):
if to is None:
to = self.env.caller
return [
utils.bvv(0),
utils.bvv(0),
utils.bvv(0),
utils.bvv(0),
to,
utils.bvv(0),
]
def test_nothing(self):
self.assertFalse(self.check_state(self.state))
def test_selfdestruct(self):
self.state.selfdestruct_to = self.env.caller
self.assertTrue(self.check_state(self.state))
def test_send_back(self):
self.state.calls.append(self.get_call(self.env.value))
self.assertFalse(self.check_state(self.state))
def test_delegatecall(self):
self.state.calls.append(self.get_delegatecall())
self.assertTrue(self.check_state(self.state))
def test_delegatecall_to_other(self):
self.state.calls.append(self.get_delegatecall(to=utils.bvv(0)))
self.assertFalse(self.check_state(self.state))
def test_send_back_more(self):
self.state.calls.append(self.get_call(self.env.value + Web3.toWei(1, "ether")))
self.assertTrue(self.check_state(self.state))
def test_send_back_if_impossible_block(self):
self.state.calls.append(
self.get_call(
claripy.If(
self.env.block_number > 100000000000,
self.env.value + Web3.toWei(1, "ether"),
0,
)
)
)
self.assertFalse(self.check_state(self.state))
def test_send_back_if_possible_block(self):
self.state.calls.append(
self.get_call(
claripy.If(
self.env.block_number < 100000000000,
self.env.value + Web3.toWei(1, "ether"),
0,
)
)
)
self.assertTrue(self.check_state(self.state))
def test_send_back_nothing(self):
self.state.calls.append(self.get_call(utils.bvv(0)))
self.assertFalse(self.check_state(self.state))
def test_send_back_twice(self):
self.state.calls.append(self.get_call(self.env.value))
self.state.calls.append(self.get_call(self.env.value / 8))
self.assertTrue(self.check_state(self.state))
def test_send_back_fixed_amount(self):
self.state.calls.append(self.get_call(Web3.toWei(1, "ether")))
self.assertTrue(self.check_state(self.state))
def test_send_back_to_someone_else(self):
self.state.calls.append(
self.get_call(Web3.toWei(1, "ether"), to=self.env.caller + 1)
)
self.assertFalse(self.check_state(self.state))
def test_send_all(self):
self.state.calls.append(self.get_call(self.env.balance))
self.assertTrue(self.check_state(self.state))
def test_send_back_calldata(self):
self.state.calls.append(self.get_call(self.env.calldata.read(0, 32)))
self.state.solver.add(claripy.UGT(self.env.calldata.read(0, 32), 0))
self.assertTrue(self.check_state(self.state))
def test_send_back_negative_signed(self):
self.state.calls.append(self.get_call(self.env.calldata.read(0, 32)))
self.state.solver.add(claripy.SLT(self.env.calldata.read(0, 32), 0))
self.assertFalse(self.check_state(self.state))
def test_send_back_negative_unsigned(self):
self.state.calls.append(self.get_call(self.env.calldata.read(0, 32)))
self.state.solver.add(claripy.ULT(self.env.calldata.read(0, 32), 0))
self.assertFalse(self.check_state(self.state))
# TODO: Fix it!
@unittest.skip(
"Known issue: we are sending back env.balance, "
"that doesn't contain env.value, and it should!"
)
def test_send_all_and_selfdestruct(self):
self.state.calls.append(self.get_call(self.env.balance, to=self.env.caller + 1))
self.state.selfdestruct_to = self.env.caller
self.assertFalse(self.check_state(self.state))
def test_read_concrete(self):
self.analyzer.actual_storage = {0: 0xBAD1DEA}
self.state.storage_read[utils.bvv(0)] = claripy.BVS("storage[0]", 256)
self.state.selfdestruct_to = self.state.storage_read[utils.bvv(0)]
self.assertFalse(self.check_state(self.state))
self.state.calls.append(
self.get_call(
Web3.toWei(1, "ether") * self.state.storage_read[utils.bvv(0)]
)
)
self.assertTrue(self.check_state(self.state))
def test_non_exhaustive_storage(self):
self.analyzer.actual_storage = {1: 0xBAD1DEA}
self.analyzer.actual_storage_exhaustive = False
self.state.storage_read[utils.bvv(0)] = claripy.BVS("storage[0]", 256)
self.state.selfdestruct_to = self.state.storage_read[utils.bvv(0)]
# Suicide to storage[0] that contains our address (state.env.caller)
with patch.object(self.analyzer, "_read_storage_key") as mock_read_storage_key:
mock_read_storage_key.return_value = utils.bvv_to_number(
self.state.env.caller
)
self.assertTrue(self.check_state(self.state))
mock_read_storage_key.assert_called_with(0)
def test_non_exhaustive_storage2(self):
"""Same as the previous test, but we suicide to 0 so it doesn't work."""
self.analyzer.actual_storage = {1: 0xBAD1DEA}
self.analyzer.actual_storage_exhaustive = False
self.state.storage_read[utils.bvv(0)] = claripy.BVS("storage[0]", 256)
self.state.selfdestruct_to = self.state.storage_read[utils.bvv(0)]
# Same as above, but we suicide to 0 instead of caller.
with patch.object(self.analyzer, "_read_storage_key") as mock_read_storage_key:
mock_read_storage_key.return_value = 0
self.assertFalse(self.check_state(self.state))
mock_read_storage_key.assert_called_with(0)
def test_exhaustive_storage(self):
self.analyzer.actual_storage = {1: 0xBAD1DEA}
self.analyzer.actual_storage_exhaustive = True
self.state.storage_read[utils.bvv(0)] = claripy.BVS("storage[0]", 256)
self.state.selfdestruct_to = self.state.storage_read[utils.bvv(0)]
# Same as above, but we suicide to 0 instead of caller.
with patch.object(self.analyzer, "_read_storage_key") as mock_read_storage_key:
self.assertFalse(self.check_state(self.state))
mock_read_storage_key.assert_not_called()
================================================
FILE: pakala/test_claripy_sha3.py
================================================
import unittest
import functools
import logging
import claripy
from pakala.claripy_sha3 import Sha3
from pakala.utils import get_solver, bvv
from pakala import env
from pakala.state import State
class TestSha3Support(unittest.TestCase):
def test_sha3_equality(self):
a = claripy.BVV(1, 256)
s = get_solver()
s.add(Sha3(a) == Sha3(claripy.BVV(1, 256)))
self.assertTrue(s.satisfiable())
def test_sha3_unequality(self):
a = claripy.BVV(1, 256)
s = get_solver()
s.add(Sha3(a) != Sha3(claripy.BVV(1, 256)))
self.assertFalse(s.satisfiable())
def test_sha3_equality_different_length(self):
a = claripy.BVV(1, 8)
s = get_solver()
s.add(Sha3(a) == Sha3(claripy.BVV(1, 256)))
self.assertFalse(s.satisfiable())
def test_solver_basic(self):
s = get_solver()
in1 = claripy.BVS("in1", 256)
in2 = claripy.BVS("in2", 256)
self.assertTrue(s.satisfiable(extra_constraints=[Sha3(in1) == Sha3(in2)]))
self.assertTrue(s.satisfiable(extra_constraints=[Sha3(in1) != Sha3(in2)]))
# These next two always hold anyway.
self.assertTrue(s.satisfiable(extra_constraints=[Sha3(in1) + 1 != Sha3(in2)]))
self.assertFalse(s.satisfiable(extra_constraints=[Sha3(in1) + 1 == Sha3(in2)]))
s.add(in1 == in2)
self.assertTrue(s.satisfiable(extra_constraints=[Sha3(in1) == Sha3(in2)]))
self.assertFalse(s.satisfiable(extra_constraints=[Sha3(in1) != Sha3(in2)]))
# These next two always hold anyway.
self.assertTrue(s.satisfiable(extra_constraints=[Sha3(in1) + 1 != Sha3(in2)]))
self.assertFalse(s.satisfiable(extra_constraints=[Sha3(in1) + 1 == Sha3(in2)]))
s = get_solver()
s.add(in1 != in2)
self.assertFalse(s.satisfiable(extra_constraints=[Sha3(in1) == Sha3(in2)]))
self.assertTrue(s.satisfiable(extra_constraints=[Sha3(in1) != Sha3(in2)]))
# These next two always hold anyway.
self.assertTrue(s.satisfiable(extra_constraints=[Sha3(in1) + 1 != Sha3(in2)]))
self.assertFalse(s.satisfiable(extra_constraints=[Sha3(in1) + 1 == Sha3(in2)]))
def test_solver_arithmetics(self):
s = get_solver()
in1 = claripy.BVS("in1", 256)
in2 = claripy.BVS("in2", 256)
self.assertTrue(
s.satisfiable(extra_constraints=[Sha3(in1) + 1 == Sha3(in2) + 1])
)
self.assertFalse(
s.satisfiable(extra_constraints=[Sha3(in1) + 1 == Sha3(in2) + 2])
)
self.assertFalse(
s.satisfiable(extra_constraints=[Sha3(in1) + 1 == Sha3(in2) + 2])
)
self.assertTrue(
s.satisfiable(extra_constraints=[Sha3(in1 + 1) == Sha3(in2 + 1)])
)
self.assertTrue(
s.satisfiable(extra_constraints=[Sha3(in1 + 1) == Sha3(in2 - 1)])
)
self.assertFalse(
s.satisfiable(extra_constraints=[Sha3(in1 + 1) + 42 == Sha3(in2 - 1)])
)
def test_solver_one_var(self):
s = get_solver()
in1 = claripy.BVS("in1", 256)
self.assertFalse(s.satisfiable(extra_constraints=[Sha3(in1) == 42]))
self.assertFalse(s.satisfiable(extra_constraints=[Sha3(in1) == 0]))
self.assertTrue(s.satisfiable(extra_constraints=[Sha3(in1) == Sha3(bvv(42))]))
self.assertTrue(s.satisfiable(extra_constraints=[Sha3(in1) == Sha3(bvv(0))]))
self.assertTrue(
s.satisfiable(extra_constraints=[Sha3(in1 + 1) + 2 == Sha3(bvv(0)) + 2])
)
def test_solver_recursive(self):
s = get_solver()
in1 = claripy.BVS("in1", 256)
in2 = claripy.BVS("in2", 256)
self.assertFalse(s.satisfiable(extra_constraints=[Sha3(Sha3(in1)) == 0]))
self.assertTrue(
s.satisfiable(extra_constraints=[Sha3(Sha3(in1)) == Sha3(Sha3(bvv(0)))])
)
s.add(Sha3(in1) == Sha3(in2))
self.assertTrue(s.satisfiable())
self.assertTrue(
s.satisfiable(
extra_constraints=[Sha3(Sha3(in1) + 1) == Sha3(Sha3(in2) + 1)]
)
)
s.add(Sha3(Sha3(in1) + 1) == Sha3(Sha3(in2) + 1))
self.assertTrue(s.satisfiable())
self.assertFalse(
s.satisfiable(
extra_constraints=[Sha3(Sha3(in1) + 2) == Sha3(Sha3(in2) + 1)]
)
)
self.assertFalse(
s.satisfiable(
extra_constraints=[Sha3(Sha3(in1)) + 1 == Sha3(Sha3(in2) + 1)]
)
)
s.add(Sha3(Sha3(in1)) + 3 == Sha3(Sha3(in2)) + 1)
self.assertFalse(s.satisfiable())
s_copy = s.branch()
self.assertFalse(s_copy.satisfiable())
def test_solver_recursive_unbalanced(self):
s = get_solver()
in1 = claripy.BVS("in1", 256)
in2 = claripy.BVS("in2", 256)
self.assertFalse(
s.satisfiable(extra_constraints=[Sha3(Sha3(in1)) == Sha3(bvv(0))])
)
self.assertTrue(s.satisfiable(extra_constraints=[Sha3(Sha3(in1)) == Sha3(in2)]))
logging.debug("here")
self.assertTrue(s.satisfiable(extra_constraints=[Sha3(in1) == Sha3(Sha3(in2))]))
self.assertTrue(
s.satisfiable(extra_constraints=[Sha3(Sha3(Sha3(in1))) == Sha3(in2)])
)
self.assertTrue(
s.satisfiable(extra_constraints=[Sha3(in1) == Sha3(Sha3(Sha3(in2)))])
)
def test_solver_three_symbols(self):
s = get_solver()
in1 = claripy.BVS("in1", 256)
in2 = claripy.BVS("in2", 256)
in3 = claripy.BVS("in2", 256)
self.assertFalse(
s.satisfiable(
extra_constraints=[Sha3(in1) == Sha3(Sha3(in3)) + Sha3(Sha3(Sha3(in2)))]
)
)
self.assertTrue(
s.satisfiable(
extra_constraints=[in1 == Sha3(Sha3(in3)) + Sha3(Sha3(Sha3(in2)))]
)
)
def test_solver_copy(self):
s = get_solver()
in1 = claripy.BVS("in1", 256)
s.add(Sha3(in1) == 0)
self.assertFalse(s.satisfiable())
s2 = s.branch()
self.assertFalse(s2.satisfiable())
def test_env_replace_merge(self):
old_env = env.Env(b"")
new_env = old_env.clean_copy()
old_state = State(old_env)
old_state.solver.add(Sha3(old_env.caller) == old_env.value)
self.assertTrue(old_state.solver.satisfiable())
self.assertFalse(
old_state.solver.satisfiable(extra_constraints=[old_env.value == 5])
)
new_state = old_state.copy()
new_state.replace(functools.partial(env.replace, old_env, new_env))
new_state.replace(new_state.solver.regenerate_hash_symbols())
self.assertTrue(new_state.solver.satisfiable())
self.assertFalse(
new_state.solver.satisfiable(extra_constraints=[new_env.value == 5])
)
self.assertTrue(
new_state.solver.satisfiable(extra_constraints=[old_env.value == 5])
)
new_state.solver.add(old_env.value == new_env.value)
self.assertTrue(new_state.solver.satisfiable())
self.assertFalse(
new_state.solver.satisfiable(extra_constraints=[new_env.value == 5])
)
self.assertFalse(
new_state.solver.satisfiable(extra_constraints=[old_env.value == 5])
)
old_state.solver = old_state.solver.combine([new_state.solver])
self.assertTrue(new_state.solver.satisfiable())
self.assertEqual(len(old_state.solver.constraints), 3)
self.assertEqual(len(old_state.solver.hashes), 2)
def test_env_replace_merge_with_recursive_hash(self):
old_env = env.Env(b"")
new_env = old_env.clean_copy()
old_state = State(old_env)
old_state.solver.add(Sha3(Sha3(old_env.caller)) == Sha3(old_env.value))
self.assertTrue(old_state.solver.satisfiable())
self.assertFalse(
old_state.solver.satisfiable(extra_constraints=[old_env.value == 5])
)
new_state = old_state.copy()
new_state.replace(functools.partial(env.replace, old_env, new_env))
new_state.replace(new_state.solver.regenerate_hash_symbols())
self.assertTrue(new_state.solver.satisfiable())
self.assertFalse(
new_state.solver.satisfiable(extra_constraints=[new_env.value == 5])
)
self.assertTrue(
new_state.solver.satisfiable(extra_constraints=[old_env.value == 5])
)
new_state.solver.add(old_env.value == new_env.value)
self.assertTrue(new_state.solver.satisfiable())
self.assertFalse(
new_state.solver.satisfiable(extra_constraints=[new_env.value == 5])
)
self.assertFalse(
new_state.solver.satisfiable(extra_constraints=[old_env.value == 5])
)
old_state.solver = old_state.solver.combine([new_state.solver])
self.assertTrue(new_state.solver.satisfiable())
self.assertEqual(len(old_state.solver.constraints), 3)
self.assertEqual(len(old_state.solver.hashes), len(new_state.solver.hashes) * 2)
def test_cannot_combine(self):
"""If we didn't do a replace(), we cannot combine the same thing."""
s = get_solver()
a = claripy.BVS("a", 256)
s.add(Sha3(a) == 8)
s2 = s.branch()
with self.assertRaises(ValueError):
s.combine([s2])
if __name__ == "__main__":
unittest.main()
================================================
FILE: pakala/test_env.py
================================================
import unittest
import claripy
from pakala import env
class TestEnv(unittest.TestCase):
def testReplace(self):
a = env.Env(b"")
calldata_a = a.calldata.read(0, 32)
b = a.clean_copy()
self.assertIs(env.replace(a, b, a.value), b.value)
self.assertIs(env.replace(a, b, calldata_a), b.calldata.read(0, 32))
def testReplace2(self):
a = env.Env(b"")
sa = a.value + a.caller + a.origin
b = a.clean_copy()
sb = b.value + b.caller + b.origin
self.assertIsNot(sa, sb)
self.assertIs(env.replace(a, b, sa), sb)
================================================
FILE: pakala/test_memory.py
================================================
import claripy
import unittest
import logging
from pakala.memory import Memory, CalldataMemory
from pakala import utils
logging.basicConfig(level=logging.DEBUG)
class TestMemory(unittest.TestCase):
def setUp(self):
self.mem = Memory()
def assertBEqual(self, a, b):
self.assertTrue((a == b).is_true(), msg="%s != %s" % (a, b))
def assertBNotEqual(self, a, b):
self.assertTrue((a == b).is_false(), msg="%s == %s" % (a, b))
def test_read_default(self):
self.assertBEqual(self.mem.read(1, 1), 0)
def overwrite(self, a, b):
self.mem.write(a[0], a[1], claripy.BVV(0x42, a[1] * 8))
self.assertBEqual(self.mem.read(a[0], a[1]), 0x42)
self.mem.write(b[0], b[1], claripy.BVV(0x01020304, b[1] * 8))
self.assertBEqual(self.mem.read(b[0], b[1]), 0x01020304)
self.assertBNotEqual(self.mem.read(a[0], a[1]), 0x42)
def test_overwrite_same(self):
self.overwrite((0, 4), (0, 4))
def test_overwrite_simple(self):
self.overwrite((1, 1), (0, 4))
def test_overwrite_left(self):
self.overwrite((0, 1), (0, 4))
def test_overwrite_right(self):
self.overwrite((3, 1), (0, 4))
def test_partial_overwrite_left(self):
self.mem.write(0, 4, claripy.BVV(0x50515253, 32))
self.mem.write(2, 4, claripy.BVV(0x60616263, 32))
self.assertBEqual(self.mem.read(0, 2), 0x5051)
self.assertBEqual(self.mem.read(2, 4), 0x60616263)
self.assertBEqual(self.mem.read(0, 6), 0x505160616263)
self.assertBEqual(self.mem.read(1, 1), 0x51)
self.assertBEqual(self.mem.read(5, 1), 0x63)
def test_partial_overwrite_right(self):
self.mem.write(2, 4, claripy.BVV(0x60616263, 32))
self.mem.write(0, 4, claripy.BVV(0x50515253, 32))
self.assertBEqual(self.mem.read(0, 2), 0x5051)
self.assertBEqual(self.mem.read(2, 4), 0x52536263)
self.assertBEqual(self.mem.read(0, 6), 0x505152536263)
self.assertBEqual(self.mem.read(1, 1), 0x51)
self.assertBEqual(self.mem.read(5, 1), 0x63)
def test_overwrite_inside(self):
self.mem.write(10, 6, claripy.BVV(0x112233445566, 8 * 6))
self.mem.write(12, 2, claripy.BVV(0x3040, 16))
self.assertBEqual(self.mem.read(10, 6), 0x112230405566)
def test_successive_left(self):
self.mem.write(0, 4, claripy.BVV(0x01020304, 32))
self.mem.write(4, 4, claripy.BVV(0x05060708, 32))
self.assertBEqual(self.mem.read(0, 8), 0x0102030405060708)
def test_successive_right(self):
self.mem.write(4, 4, claripy.BVV(0x05060708, 32))
self.mem.write(0, 4, claripy.BVV(0x01020304, 32))
self.assertBEqual(self.mem.read(0, 8), 0x0102030405060708)
def test_successive(self):
self.mem.write(0, 4, claripy.BVV(0x11223344, 32))
self.mem.write(6, 4, claripy.BVV(0x55667788, 32))
self.assertBEqual(self.mem.read(0, 11), 0x1122334400005566778800)
def test_read(self):
self.mem.write(10, 4, claripy.BVV(0xAABBCCDD, 32))
self.assertBEqual(self.mem.read(8, 4), 0x0000AABB)
self.assertBEqual(self.mem.read(12, 4), 0xCCDD0000)
self.assertBEqual(self.mem.read(11, 2), 0xBBCC)
self.assertBEqual(self.mem.read(9, 1), 0)
self.assertBEqual(self.mem.read(14, 1), 0)
def test_read_write_size_0(self):
self.mem.write(0, 0, claripy.BVV(0, 0))
self.assertBEqual(self.mem.read(0, 0), claripy.BVV(0, 0))
self.assertBEqual(self.mem.read(0, 1), claripy.BVV(0, 8))
self.mem.write(0, 1, claripy.BVV(1, 8))
self.mem.write(0, 0, claripy.BVV(0, 0))
self.assertBEqual(self.mem.read(0, 1), claripy.BVV(1, 8))
with self.assertRaises(AssertionError):
self.mem.write(0, 0, claripy.BVV(1, 8))
def test_size(self):
self.assertEqual(self.mem.size(), 0)
self.mem.write(10, 4, claripy.BVV(42, 4 * 8))
self.assertEqual(self.mem.size(), 14)
def test_copy(self):
self.mem.write(1, 1, claripy.BVV(42, 8))
new_mem = self.mem.copy()
new_mem.write(1, 1, claripy.BVV(43, 8))
self.assertBEqual(self.mem.read(1, 1), 42)
self.assertBEqual(new_mem.read(1, 1), 43)
def test_hash(self):
self.mem.write(0, 1, claripy.BVV(42, 8))
self.mem.write(10, 1, claripy.BVV(43, 8))
mem_copy = self.mem.copy()
self.assertEqual(hash(self.mem), hash(mem_copy))
self.mem.write(5, 1, claripy.BVV(44, 8))
self.assertNotEqual(hash(self.mem), hash(mem_copy))
mem_copy.write(5, 1, claripy.BVV(44, 8))
self.assertEqual(hash(self.mem), hash(mem_copy))
self.mem.write(0, 10, claripy.BVV(46, 80))
self.assertNotEqual(hash(self.mem), hash(mem_copy))
mem_copy.write(0, 10, claripy.BVV(46, 80))
self.assertEqual(hash(self.mem), hash(mem_copy))
def test_copy_from(self):
calldata = CalldataMemory()
calldata.read(28, 4)
calldata_24 = calldata.read(24, 4)
# self.mem[10 to 20] contains calldata[20 to 30]
self.mem.copy_from(calldata, 10, 20, 10)
self.assertIs(self.mem.read(14, 4), calldata_24)
mem_10 = self.mem.read(10, 4)
self.assertIs(calldata.read(20, 4), mem_10)
self.assertBEqual(self.mem.read(18, 2), calldata.read(28, 2))
# Test writing
self.mem.write(14, 4, claripy.BVV(0x40414243, 32))
self.assertBEqual(self.mem.read(14, 4), 0x40414243)
self.assertBEqual(self.mem.read(18, 2), calldata.read(28, 2))
def test_overwrite_0(self):
self.mem.write(0, 64, claripy.BVV(1, 512))
self.assertBEqual(self.mem.read(0, 64), 1)
self.mem.write(64, 32, claripy.BVV(1, 256))
self.assertBEqual(self.mem.read(0, 64), 1)
self.mem.write(32, 32, claripy.BVV(1, 256))
self.assertBEqual(self.mem.read(0, 64), claripy.BVV(1, 512))
self.mem.write(0, 32, claripy.BVV(1, 256))
self.assertBEqual(
self.mem.read(0, 64),
claripy.Concat(claripy.BVV(1, 256), claripy.BVV(1, 256)),
)
class TestCalldataMemory(unittest.TestCase):
def setUp(self):
self.mem = CalldataMemory()
def test_readonly(self):
with self.assertRaises(AssertionError):
self.mem.write(0, 1, None)
with self.assertRaises(AssertionError):
self.mem.copy_from(0, 1, None)
def test_read_default(self):
r = self.mem.read(0, 1)
self.assertTrue(r.symbolic)
================================================
FILE: pakala/test_recursive_analyzer.py
================================================
import claripy
import unittest
import logging
import random
import itertools
from pakala.recursive_analyzer import RecursiveAnalyzer, with_new_env
from pakala.env import Env
from pakala.state import State
from pakala import utils
from pakala.claripy_sha3 import Sha3
from web3 import Web3
logging.basicConfig(level=logging.DEBUG)
logging.getLogger("claripy").setLevel(logging.ERROR)
class TestWithNewEnv(unittest.TestCase):
def test_with_new_env(self):
env = Env(b"")
state = State(env)
storage_0 = claripy.BVS("storage[0]", 256)
storage_1 = claripy.BVS("storage[0]", 256)
storage_2 = claripy.BVS("storage[0]", 256)
state.storage_read[utils.bvv(0)] = storage_0
state.storage_read[utils.bvv(1)] = storage_1
state.storage_read[utils.bvv(2)] = storage_2
state.storage_written[utils.bvv(0)] = utils.bvv(0)
state.storage_written[utils.bvv(1)] = utils.bvv(0)
state.storage_written[utils.bvv(2)] = utils.bvv(0)
state.calls.append(
[
utils.bvv(1),
storage_0 + storage_1 + storage_2,
utils.bvv(2),
5 * (storage_0 + storage_1 + storage_2),
]
)
state.solver.add(storage_0 == 42)
state.solver.add(storage_1 == 0)
state.solver.add(storage_2 == 0)
self.assertEqual(state.solver.eval(state.calls[0][1], 2), (42,))
for i in range(3):
new_state = with_new_env(state)
self.assertIsNot(state.env.value, new_state.env.value)
self.assertIsNot(
state.storage_read[utils.bvv(0)], new_state.storage_read[utils.bvv(0)]
)
self.assertIsNot(
state.storage_read[utils.bvv(1)], new_state.storage_read[utils.bvv(1)]
)
self.assertIsNot(
state.storage_read[utils.bvv(2)], new_state.storage_read[utils.bvv(2)]
)
self.assertNotEqual(new_state.solver.eval(state.calls[0][1], 2), (42,))
self.assertEqual(new_state.solver.eval(new_state.calls[0][1], 2), (42,))
class TestCheckStates(unittest.TestCase):
"""The interesting tests.
Inventing various classic scenarios and making sure that we find the bug
if there is one. And that we don't if we are not supposed to find one.
"""
def setUp(self):
self.env = Env(b"", caller=utils.DEFAULT_CALLER, address=utils.DEFAULT_ADDRESS)
def check_states(self, states, mock_storage=None):
self.analyzer = RecursiveAnalyzer(
max_wei_to_send=Web3.toWei(10, "ether"),
min_wei_to_receive=Web3.toWei(1, "milliether"),
)
if mock_storage is not None:
self.analyzer.actual_storage = mock_storage
return self.analyzer.check_states(states, timeout=0, max_depth=4)
def get_call(self, value, to=None):
if to is None:
to = self.env.caller
return [
utils.bvv(0),
utils.bvv(0),
utils.bvv(0),
utils.bvv(0),
value,
to,
utils.bvv(0),
]
def test_nothing(self):
self.assertFalse(self.check_states([]))
def test_simple(self):
state = State(self.env)
self.assertFalse(self.check_states([state]))
def test_selfdestruct_simple(self):
state = State(self.env)
state.selfdestruct_to = self.env.caller
self.assertTrue(self.check_states([state]))
def test_call_simple(self):
state = State(self.env)
state.calls.append(self.get_call(self.env.balance))
self.assertTrue(self.check_states([state]))
def test_write_and_selfdestruct(self):
state = State(self.env)
state_write = state.copy()
state_write.storage_written = {utils.bvv(0): self.env.calldata.read(4, 32)}
state_selfdestruct = state.copy()
state_selfdestruct.selfdestruct_to = self.env.calldata.read(4, 32)
storage_0 = claripy.BVS("storage[0]", 256)
state_selfdestruct.storage_read = {utils.bvv(0): storage_0}
state_selfdestruct.solver.add(storage_0 == 0xDEADBEEF0101)
storage = {0: 0xBAD1DEA}
self.assertTrue(
self.check_states([state_write, state_selfdestruct], mock_storage=storage)
)
self.assertFalse(self.check_states([state_selfdestruct], mock_storage=storage))
self.assertFalse(self.check_states([state_write]))
def test_sha3_key(self):
"""Exercise solidity-like mappings, with the key being a sha3."""
state = State(self.env)
state_write = state.copy()
# Arbitrary write input[1], at SHA3(input[0])
state_write.storage_written = {
Sha3(self.env.calldata.read(4, 32)): self.env.calldata.read(36, 32)
}
# Needs that: storage[SHA3(input[0])] == 43, made possible by the previous call
state_selfdestruct = state.copy()
state_selfdestruct.selfdestruct_to = self.env.calldata.read(36, 32)
storage_input = claripy.BVS("storage[SHA3(input)]", 256)
state_selfdestruct.storage_read = {
Sha3(self.env.calldata.read(4, 32)): storage_input
}
state_selfdestruct.solver.add(storage_input == 0xDEADBEEF101010)
storage = {
55186156870478567193644641351382124067713781048612400765092754877653207859685: 0
}
self.assertTrue(
self.check_states([state_write, state_selfdestruct], mock_storage=storage)
)
self.assertFalse(self.check_states([state_selfdestruct], mock_storage=storage))
self.assertFalse(self.check_states([state_write]))
def test_sha3_value1(self):
"""Exercise comparison of two SHA3 (as values)."""
state = State(self.env)
state_write = state.copy()
state_write.storage_written = {
utils.bvv(0): Sha3(self.env.calldata.read(4, 32))
}
state_selfdestruct = state.copy()
state_selfdestruct.selfdestruct_to = self.env.calldata.read(36, 32)
storage_input = claripy.BVS("storage[0]", 256)
state_selfdestruct.storage_read = {utils.bvv(0): storage_input}
state_selfdestruct.solver.add(
storage_input == Sha3(self.env.calldata.read(4, 32))
)
storage = {0: 0}
self.assertTrue(
self.check_states([state_write, state_selfdestruct], mock_storage=storage)
)
self.assertFalse(self.check_states([state_selfdestruct], mock_storage=storage))
self.assertFalse(self.check_states([state_write], mock_storage=storage))
def test_sha3_value2(self):
"""Same as above, but we need to pass the computed SHA3."""
state = State(self.env)
state_write = state.copy()
state_write.storage_written = {
utils.bvv(0): Sha3(self.env.calldata.read(4, 32))
}
state_selfdestruct = state.copy()
state_selfdestruct.selfdestruct_to = self.env.calldata.read(36, 32)
storage_input = claripy.BVS("storage[0]", 256)
state_selfdestruct.storage_read = {utils.bvv(0): storage_input}
state_selfdestruct.solver.add(storage_input == self.env.calldata.read(4, 32))
state_selfdestruct.solver.add(storage_input != 0)
storage = {0: 0}
self.assertTrue(
self.check_states([state_write, state_selfdestruct], mock_storage=storage)
)
self.assertFalse(self.check_states([state_selfdestruct], mock_storage=storage))
self.assertFalse(self.check_states([state_write], mock_storage=storage))
def test_write_write_and_selfdestruct(self):
state = State(self.env)
# Anybody can set owner
state_write1 = state.copy()
state_write1.storage_written = {utils.bvv(0): self.env.calldata.read(4, 32)}
# Onlyowner: set a magic constant allowing the selfdestruct bug, at an
# user-controlled storage key.
state_write2 = state.copy()
read_0 = claripy.BVS("storage[0]", 256)
state_write2.storage_read = {utils.bvv(0): read_0}
state_write2.storage_written = {
self.env.calldata.read(36, 32): self.env.calldata.read(4, 32)
}
state_write2.solver.add(read_0 == self.env.caller)
# Suicide, when owner and magic constant set
state_selfdestruct = state.copy()
read_0 = claripy.BVS("storage[0]", 256)
read_40 = claripy.BVS("storage[4]", 256)
state_selfdestruct.storage_read = {utils.bvv(0): read_0, utils.bvv(40): read_40}
state_selfdestruct.solver.add(self.env.caller == read_0)
state_selfdestruct.solver.add(read_40 == 1337)
state_selfdestruct.selfdestruct_to = self.env.caller
states = [state_write1, state_write2, state_selfdestruct]
random.shuffle(states)
storage = {0: 123456789, 40: 387642}
for s in itertools.combinations(states, 2):
self.assertFalse(self.check_states(s, mock_storage=storage))
self.assertTrue(self.check_states(states, mock_storage=storage))
def test_send_after_write(self):
state = State(self.env)
# We send storage[0]
state_send = state.copy()
storage_0 = claripy.BVS("storage[0]", 256)
state_send.storage_read = {utils.bvv(0): storage_0}
state_send.calls.append(self.get_call(storage_0))
# storage[0] is 0.5 ETH
storage = {0: Web3.toWei(0.5, "ether")}
self.assertTrue(self.check_states([state_send], mock_storage=storage))
# storage[0] is 0 ETH
storage = {0: 0}
self.assertFalse(self.check_states([state_send], mock_storage=storage))
# storage[0] is still 0 ETH initially, but we have an arbitrary write now
state_write = state.copy()
state_write.storage_written = {utils.bvv(0): self.env.calldata.read(4, 32)}
state_write.solver.add(self.env.calldata.read(0, 4) == 0x1337)
state_write.solver.add(self.env.calldata.read(4, 32) < Web3.toWei(1, "ether"))
self.assertFalse(self.check_states([state_write], mock_storage=storage))
self.assertTrue(
self.check_states([state_send, state_write], mock_storage=storage)
)
self.assertTrue(
self.check_states([state_write, state_send], mock_storage=storage)
)
# ...arbitrary write of 1 wei only, which is too little
state_write_0 = state_write.copy()
state_write_0.solver.add(self.env.calldata.read(4, 32) == 1)
self.assertFalse(
self.check_states([state_write_0, state_send], mock_storage=storage)
)
# ...arbitrary write only if the block timestamp is <10, which is impossible.
state_write_ts = state_write.copy()
state_write_ts.solver.add(self.env.block_timestamp < 10)
self.assertFalse(
self.check_states([state_write_ts, state_send], mock_storage=storage)
)
self.assertFalse(
self.check_states(
[state_write_0, state_send, state_write_ts], mock_storage=storage
)
)
# now we put all these state_write* together, so there is a solution.
self.assertTrue(
self.check_states(
[state_write_0, state_send, state_write, state_write_ts],
mock_storage=storage,
)
)
self.assertTrue(
self.check_states(
[state_write_0, state_write, state_write_ts, state_send],
mock_storage=storage,
)
)
def test_symbolic_storage(self):
"""Specific test for using a storage key that cannot be symbolized."""
state = State(self.env)
storage = {10: 1}
# We write to an arbitrary address
state_write = state.copy()
state_write.storage_written[
state_write.env.calldata.read(4, 32)
] = state_write.env.calldata.read(36, 32)
# We send twice what we receive, but only if we have 1 at two arbitrary
# keys.
state_send = state.copy()
storage_a = claripy.BVS("storage[a]", 256)
storage_b = claripy.BVS("storage[b]", 256)
k_a = state_send.env.calldata.read(4, 32)
k_b = state_send.env.calldata.read(36, 32)
state_send.storage_read[k_a] = storage_a
state_send.storage_read[k_b] = storage_b
state_send.solver.add(storage_a == 1)
state_send.solver.add(storage_b == 1)
state_send.calls.append(self.get_call((state.env.value * 128) / 64))
# If k_a == 10 and k_b == 10, it works!
self.assertTrue(self.check_states([state_send], mock_storage=storage))
state_send.solver.add(k_a != k_b)
self.assertFalse(self.check_states([state_send], mock_storage=storage))
self.assertFalse(self.check_states([state_write], mock_storage=storage))
# Now we have to first write, then send.
bug = self.check_states([state_send, state_write], mock_storage=storage)
self.assertTrue(bug)
self.assertEqual(len(bug[1]), 2)
# If we force k_a to be != 10, we can use k_b == 10 instead.
state_send.solver.add(k_a != 10)
bug = self.check_states([state_send, state_write], mock_storage=storage)
self.assertTrue(bug)
self.assertEqual(len(bug[1]), 2)
# If we force both, it's impossible and we have to do two writes.
state_send.solver.add(k_b != 10)
bug = self.check_states([state_send, state_write], mock_storage=storage)
self.assertTrue(bug)
self.assertEqual(len(bug[1]), 3)
================================================
FILE: pakala/test_sm.py
================================================
import unittest
from unittest import mock
import random
import numbers
import codecs
import claripy
from pakala.env import Env
from pakala import sm
from pakala import utils
# pylint: disable=undefined-variable
# flake8: noqa
from eth.vm.opcode_values import *
BVV_0 = utils.bvv(0)
BVV_1 = utils.bvv(1)
class TestSymbolicMachine(unittest.TestCase):
"""Basic tests for the members of the symbolic machine."""
def setUp(self):
code = codecs.decode(
"6003600302600f56601b60006000a15b6101a5600060"
"00a160019003801515600f57600660006000a1",
"hex",
)
env = Env(code)
self.sm = sm.SymbolicMachine(env)
def test_add_branch(self):
state = self.sm.branch_queue[0][1]
state.pc += 1
self.sm.add_branch(state)
self.assertEqual(len(self.sm.branch_queue), 2)
# Add duplicate branch
self.sm.add_branch(state)
self.assertEqual(len(self.sm.branch_queue), 2)
self.assertEqual(len(self.sm.code_errors), 1)
# Add unsatisfiable state
state.solver.add(claripy.BVS("lol", 8) == 5)
self.sm.add_branch(state)
self.assertEqual(len(self.sm.branch_queue), 3)
state.solver.add(claripy.BVV(1, 8) == claripy.BVV(0, 8))
self.sm.add_branch(state)
self.assertEqual(len(self.sm.branch_queue), 3)
self.assertEqual(len(self.sm.code_errors), 1)
def test_add_for_fuzzing(self):
state = self.sm.branch_queue[0][1]
variable = claripy.BVS("test", 8)
state.solver.add(variable < 50)
self.sm.add_for_fuzzing(
state, variable, [min, max, None, None, None, None, 42, 1337]
)
self.assertTrue(
any(s.solver.eval(variable, 2) == (0,) for _, s in self.sm.branch_queue)
)
self.assertTrue(
any(s.solver.eval(variable, 2) == (49,) for _, s in self.sm.branch_queue)
)
self.assertTrue(
any(s.solver.eval(variable, 2) == (42,) for _, s in self.sm.branch_queue)
)
self.assertGreater(len(self.sm.branch_queue), 3)
def test_execute(self):
self.sm.execute(timeout_sec=10)
def test_get_coverage(self):
# Just test that it seems to work
self.assertEqual(self.sm.get_coverage(), 0)
class TestInstructions(unittest.TestCase):
def assertBEqual(self, a, b):
self.assertTrue((a == b).is_true(), msg="%s != %s" % (a, b))
def run_code(self, code, env={}):
code = bytes(code)
self.sm = sm.SymbolicMachine(Env(code, **env))
self.state = self.sm.branch_queue[0][1]
return self.sm.exec_branch(self.state)
def assert_stack(self, stack):
self.assertEqual(len(stack), len(self.state.stack))
for reference, observed in zip(stack, self.state.stack):
self.assertBEqual(reference, observed)
def test_jumpdest(self):
self.assertTrue(self.run_code([JUMPDEST]))
def test_add(self):
self.run_code([PUSH1, 1, PUSH1, 2, ADD])
self.assert_stack([3])
self.run_code([PUSH1, 1, PUSH32] + [255] * 32 + [ADD])
self.assert_stack([0])
def test_sub(self):
self.run_code([PUSH1, 2, PUSH1, 1, SUB])
self.assert_stack([claripy.BVV(2 ** 256 - 1, 256)])
def test_mul(self):
self.run_code([PUSH1, 2, PUSH1, 4, MUL])
self.assert_stack([8])
def test_div(self):
self.run_code([PUSH1, 2, PUSH1, 8, DIV])
self.assert_stack([4])
self.run_code([PUSH1, 3, PUSH1, 8, DIV])
self.assert_stack([2])
self.run_code([PUSH1, 10, PUSH1, 8, DIV])
self.assert_stack([0])
self.run_code([PUSH32] + [255] * 32 + [PUSH1, 1, DIV])
self.assert_stack([0])
self.run_code([PUSH1, 0, PUSH1, 1, DIV])
self.assert_stack([0])
def test_sdiv(self):
self.run_code([PUSH32] + [255] * 32 + [PUSH1, 1, SDIV])
self.assert_stack([2 ** 256 - 1])
self.run_code([PUSH1, 0, PUSH1, 1, SMOD])
self.assert_stack([0])
def test_mod(self):
self.run_code([PUSH1, 3, PUSH1, 7, MOD])
self.assert_stack([1])
self.run_code([PUSH1, 3, PUSH32] + [255] * 32 + [MOD])
self.assert_stack([0])
self.run_code([PUSH1, 0, PUSH1, 1, MOD])
self.assert_stack([0])
def test_smod(self):
self.run_code([PUSH1, 3, PUSH32] + [255] * 32 + [SMOD])
self.assert_stack([2 ** 256 - 1])
self.run_code([PUSH1, 3, PUSH32] + [255] * 31 + [252, SMOD])
self.assert_stack([2 ** 256 - 1])
self.run_code([PUSH1, 3, PUSH1, 4, SMOD])
self.assert_stack([1])
self.run_code([PUSH1, 0, PUSH1, 1, SMOD])
self.assert_stack([0])
def test_addmod(self):
self.run_code([PUSH1, 2, PUSH1, 1, PUSH1, 1, ADDMOD])
self.assert_stack([0])
self.run_code([PUSH1, 2, PUSH1, 2, PUSH1, 1, ADDMOD])
self.assert_stack([1])
self.run_code([PUSH1, 2, PUSH1, 2, PUSH1, 2, ADDMOD])
self.assert_stack([0])
self.run_code([PUSH1, 0, PUSH1, 2, PUSH1, 1, ADDMOD])
self.assert_stack([0])
def test_mulmod(self):
self.run_code([PUSH1, 2, PUSH1, 1, PUSH1, 1, MULMOD])
self.assert_stack([1])
self.run_code([PUSH1, 2, PUSH1, 2, PUSH1, 1, MULMOD])
self.assert_stack([0])
self.run_code([PUSH1, 2, PUSH1, 2, PUSH1, 2, MULMOD])
self.assert_stack([0])
self.run_code([PUSH1, 0, PUSH1, 1, PUSH1, 1, MULMOD])
self.assert_stack([0])
def test_exp(self):
self.run_code([PUSH1, 3, PUSH1, 7, EXP])
self.assert_stack([343])
def test_shl(self):
self.run_code([PUSH1, 1, PUSH1, 1, SHL])
self.assert_stack([2])
self.run_code([PUSH1, 1, PUSH1, 0, SHL])
self.assert_stack([1])
self.run_code([PUSH1, 1, PUSH1, 2, SHL])
self.assert_stack([4])
self.run_code([PUSH1, 1, PUSH2, 1, 0, SHL])
self.assert_stack([0])
def test_shr(self):
self.run_code([PUSH1, 2, PUSH1, 1, SHR])
self.assert_stack([1])
self.run_code([PUSH1, 2, PUSH1, 0, SHR])
self.assert_stack([2])
self.run_code([PUSH1, 2, PUSH1, 2, SHR])
self.assert_stack([0])
self.run_code([PUSH1, 2, PUSH2, 1, 0, SHR])
self.assert_stack([0])
def test_sar(self):
self.run_code([PUSH1, 2, PUSH1, 1, SAR])
self.assert_stack([1])
self.run_code([PUSH1, 2, PUSH1, 0, SAR])
self.assert_stack([2])
self.run_code([PUSH1, 2, PUSH1, 2, SAR])
self.assert_stack([2 ** 255])
self.run_code([PUSH1, 2, PUSH2, 1, 0, SAR])
self.assert_stack([2])
def test_signextend(self):
self.run_code([PUSH1, 0xFF, PUSH1, 0x0, SIGNEXTEND])
self.assert_stack([2 ** 256 - 1])
self.run_code([PUSH1, 0x3, PUSH1, 0x0, SIGNEXTEND])
self.assert_stack([3])
self.run_code([PUSH1, 0x0, PUSH1, 0x0, SIGNEXTEND])
self.assert_stack([0])
self.run_code([PUSH2, 0xFF, 0xFE, PUSH1, 0x1, SIGNEXTEND])
self.assert_stack([2 ** 256 - 2])
self.run_code([PUSH2, 0xFF, 0xFE, PUSH1, 0x2, SIGNEXTEND])
self.assert_stack([0xFFFE])
def test_lt(self):
self.run_code([PUSH1, 7, PUSH1, 6, LT])
self.assert_stack([BVV_1])
self.run_code([PUSH1, 7, PUSH1, 7, LT])
self.assert_stack([BVV_0])
self.run_code([PUSH32] + [0xFF] * 31 + [250, PUSH32] + [0xFF] * 31 + [251, LT])
self.assert_stack([BVV_0])
self.run_code([PUSH32] + [0xFF] * 31 + [250, PUSH32] + [0x00] * 31 + [251, LT])
self.assert_stack([BVV_1])
def test_gt(self):
self.run_code([PUSH1, 7, PUSH1, 6, GT])
self.assert_stack([BVV_0])
self.run_code([PUSH1, 7, PUSH1, 7, GT])
self.assert_stack([BVV_0])
self.run_code([PUSH32] + [0xFF] * 31 + [250, PUSH32] + [0xFF] * 31 + [251, GT])
self.assert_stack([BVV_1])
self.run_code([PUSH32] + [0xFF] * 31 + [250, PUSH32] + [0x00] * 31 + [251, GT])
self.assert_stack([BVV_0])
def test_slt(self):
self.run_code([PUSH1, 7, PUSH1, 6, SLT])
self.assert_stack([BVV_1])
self.run_code([PUSH1, 7, PUSH1, 7, SLT])
self.assert_stack([BVV_0])
self.run_code([PUSH32] + [0xFF] * 31 + [250, PUSH32] + [0xFF] * 31 + [251, SLT])
self.assert_stack([BVV_0])
self.run_code([PUSH32] + [0xFF] * 31 + [250, PUSH32] + [0x00] * 31 + [251, SLT])
self.assert_stack([BVV_0])
def test_sgt(self):
self.run_code([PUSH1, 7, PUSH1, 6, SGT])
self.assert_stack([BVV_0])
self.run_code([PUSH1, 7, PUSH1, 7, SGT])
self.assert_stack([BVV_0])
self.run_code([PUSH32] + [0xFF] * 31 + [250, PUSH32] + [0xFF] * 31 + [251, SGT])
self.assert_stack([BVV_1])
self.run_code([PUSH32] + [0xFF] * 31 + [250, PUSH32] + [0x00] * 31 + [251, SGT])
self.assert_stack([BVV_1])
def test_eq(self):
self.run_code([PUSH1, 1, PUSH1, 1, EQ])
self.assert_stack([BVV_1])
self.run_code([PUSH1, 1, PUSH1, 2, EQ])
self.assert_stack([BVV_0])
def test_iszero(self):
self.run_code([PUSH1, 1, ISZERO])
self.assert_stack([BVV_0])
self.run_code([PUSH1, 1, PUSH32] + 32 * [0xFF] + [ADD, ISZERO])
self.assert_stack([BVV_1])
def test_and(self):
self.run_code([PUSH1, 3, PUSH1, 2, AND])
self.assert_stack([2])
def test_or(self):
self.run_code([PUSH1, 3, PUSH1, 2, OR])
self.assert_stack([3])
self.run_code([PUSH1, 1, PUSH1, 2, OR])
self.assert_stack([3])
def test_xor(self):
self.run_code([PUSH1, 3, PUSH1, 2, XOR])
self.assert_stack([1])
a = random.randint(0, 255)
b = random.randint(0, 255)
self.run_code([PUSH1, a, PUSH1, b, DUP1, XOR, XOR])
self.assert_stack([a])
def test_not(self):
self.run_code([PUSH1, 0x43, NOT])
self.assert_stack([(2 ** 256 - 1) ^ 0x43])
self.run_code([PUSH1, 0, NOT])
self.assert_stack([2 ** 256 - 1])
self.run_code([PUSH32] + 32 * [0xFF] + [NOT])
self.assert_stack([0])
a = random.randint(0, 255)
self.run_code([PUSH1, a, NOT, NOT])
self.assert_stack([a])
def test_byte(self):
self.run_code([PUSH2, 0x42, 0x43, PUSH1, 0, BYTE])
self.assert_stack([0])
self.run_code([PUSH2, 0x42, 0x43, PUSH1, 29, BYTE])
self.assert_stack([0])
self.run_code([PUSH2, 0x42, 0x43, PUSH1, 30, BYTE])
self.assert_stack([0x42])
self.run_code([PUSH2, 0x42, 0x43, PUSH1, 31, BYTE])
self.assert_stack([0x43])
self.run_code([PUSH2, 0x42, 0x43, PUSH1, 32, BYTE])
self.assert_stack([0])
self.run_code([PUSH2, 0x42, 0x43, PUSH1, 50, BYTE])
self.assert_stack([0])
self.run_code([PUSH3, 0x41, 0x42, 0x43, PUSH1, 29, BYTE])
self.assert_stack([0x41])
def test_pc(self):
self.run_code([PUSH1, 1, PC])
self.assert_stack([1, 2])
def test_gas(self):
self.run_code([GAS])
self.assert_stack([self.state.env.gas])
def test_address(self):
self.run_code([ADDRESS])
self.assert_stack([self.state.env.address])
def test_balance(self):
self.run_code([ADDRESS, BALANCE], env={"address": claripy.BVV(789, 256)})
self.assert_stack([self.state.env.balance])
with self.assertRaises(ValueError):
self.run_code([PUSH1, 1, BALANCE])
def test_origin(self):
self.run_code([ORIGIN])
self.assert_stack([self.state.env.origin])
def test_caller(self):
self.run_code([CALLER])
self.assert_stack([self.state.env.caller])
def test_callvalue(self):
self.run_code([CALLVALUE])
self.assert_stack([self.state.env.value])
def test_blockhash(self):
self.run_code([NUMBER, BLOCKHASH])
self.assert_stack([self.state.env.block_hashes[self.state.env.block_number]])
def test_timestamp(self):
self.run_code([TIMESTAMP])
self.assert_stack([self.state.env.block_timestamp])
def test_number(self):
self.run_code([NUMBER])
self.assert_stack([self.state.env.block_number])
def test_coinbase(self):
self.run_code([COINBASE])
self.assert_stack([self.state.env.coinbase])
def test_difficulty(self):
self.run_code([DIFFICULTY])
self.assert_stack([self.state.env.difficulty])
def test_pop(self):
self.run_code([PUSH1, 1, POP])
self.assert_stack([])
with self.assertRaises(utils.CodeError):
self.run_code([POP])
def test_jump(self):
r = self.run_code([PUSH1, 4, JUMP, PC, JUMPDEST])
self.assertFalse(r)
self.assert_stack([])
self.assertEqual(len(self.sm.branch_queue), 2)
self.sm.exec_branch(self.sm.branch_queue[1][1])
self.assert_stack([])
with self.assertRaises(utils.CodeError):
self.run_code([PUSH1, 4, JUMP, POP, PC])
def test_jumpi(self):
r = self.run_code([PUSH1, 42, CALLVALUE, EQ, PUSH1, 8, JUMPI, PC, JUMPDEST])
self.assertFalse(r)
def true_state(state):
self.state = state
self.sm.exec_branch(self.state)
try:
self.assert_stack([7])
self.assertEqual(self.state.solver.min(self.state.env.value), 0)
except AssertionError:
return False
return True
def false_state(state):
self.state = state
self.sm.exec_branch(self.state)
try:
self.assert_stack([])
self.assertEqual(self.state.solver.min(self.state.env.value), 1337)
except AssertionError:
return False
return True
# We don't know which state is first (it changes). So we do that
# to avoid flakiness.
self.assertTrue(any(true_state(bq[1])) for bq in self.sm.branch_queue)
self.assertTrue(any(false_state(bq[1])) for bq in self.sm.branch_queue)
with self.assertRaises(utils.CodeError):
self.run_code([PUSH1, 0, PUSH1, 0, JUMPI])
def test_push(self):
self.run_code([PUSH1, 2])
self.assert_stack([2])
self.run_code([PUSH3, 2, 0, 0, PUSH2, 0, 2])
self.assert_stack([2 * 65536, 2])
def test_dup(self):
self.run_code([PUSH1, 1, PUSH1, 2, PUSH1, 3, DUP3])
self.assert_stack([1, 2, 3, 1])
self.run_code([PUSH1, 1, PUSH1, 2, PUSH1, 3, DUP1])
self.assert_stack([1, 2, 3, 3])
def test_swap(self):
self.run_code([PUSH1, 1, PUSH1, 2, PUSH1, 3, SWAP2])
self.assert_stack([3, 2, 1])
self.run_code([PUSH1, 1, PUSH1, 2, PUSH1, 3, SWAP1])
self.assert_stack([1, 3, 2])
def test_log(self):
self.run_code([PUSH1, 0, PUSH1, 0, PUSH1, 0, LOG1])
def test_sha3_empty(self):
self.run_code([PUSH1, 0, PUSH1, 0, SHA3])
self.assertEqual(1, len(self.state.stack))
sha3, = self.state.solver.eval(self.state.stack[0], 1)
self.assertEqual(
hex(sha3),
hex(0xC5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470),
)
def test_sha3_zeros(self):
self.run_code([PUSH1, 32, PUSH1, 0, SHA3])
self.assertEqual(1, len(self.state.stack))
sha3, = self.state.solver.eval(self.state.stack[0], 1)
self.assertEqual(
hex(sha3),
hex(0x290DECD9548B62A8D60345A988386FC84BA6BC95484008F6362F93160EF3E563),
)
def test_sha3_a_mstore8(self):
self.run_code([PUSH1, 0x61, PUSH1, 0, MSTORE8, PUSH1, 1, PUSH1, 0, SHA3])
self.assertEqual(1, len(self.state.stack))
sha3, = self.state.solver.eval(self.state.stack[0], 1)
self.assertEqual(
hex(sha3),
# sha3('a')
hex(0x3AC225168DF54212A25C1C01FD35BEBFEA408FDAC2E31DDD6F80A4BBF9A5F1CB),
)
def test_sha3_a_mstore(self):
self.run_code([PUSH1, 0x61, PUSH1, 0, MSTORE, PUSH1, 1, PUSH1, 31, SHA3])
self.assertEqual(1, len(self.state.stack))
sha3, = self.state.solver.eval(self.state.stack[0], 1)
self.assertEqual(
hex(sha3),
# sha3('a')
hex(0x3AC225168DF54212A25C1C01FD35BEBFEA408FDAC2E31DDD6F80A4BBF9A5F1CB),
)
def test_stop(self):
r = self.run_code([STOP])
self.assertTrue(r)
def test_return(self):
r = self.run_code([RETURN])
self.assertTrue(r)
def test_calldataload(self):
self.run_code([PUSH1, 0, CALLDATALOAD, PUSH1, 0, CALLDATALOAD])
self.assertTrue(self.state.stack[0] is self.state.stack[1])
self.run_code([PUSH1, 0, CALLDATALOAD, PUSH1, 32, CALLDATALOAD])
self.assertTrue(self.state.stack[0] is not self.state.stack[1])
def test_calldatasize(self):
self.run_code([CALLDATASIZE])
def test_calldatacopy(self):
# size, dstart, mstart
self.run_code(
[
PUSH1,
64,
PUSH1,
20,
PUSH1,
10,
CALLDATACOPY,
PUSH1,
10,
MLOAD,
PUSH1,
42,
MLOAD,
]
)
self.assert_stack(
[self.state.env.calldata.read(20, 32), self.state.env.calldata.read(52, 32)]
)
def test_codesize(self):
self.run_code([PUSH1, 0, POP, CODESIZE])
self.assert_stack([4])
def test_extcodesize_self(self):
self.run_code([ADDRESS, EXTCODESIZE])
self.assert_stack([2])
def test_extcodesize_other(self):
self.run_code([PUSH1, 42, EXTCODESIZE])
self.assertTrue(len(self.state.stack), 1)
self.assertTrue(
self.state.solver.satisfiable(extra_constraints=[self.state.stack[0] == 0])
)
self.assertTrue(
self.state.solver.satisfiable(
extra_constraints=[self.state.stack[0] == 1337]
)
)
def test_codecopy(self):
code = [CODESIZE, PUSH1, 0, DUP1, CODECOPY, PUSH1, 0, MLOAD]
self.run_code(code)
self.assert_stack([bytes(code).ljust(32, b"\0")])
def test_mload(self):
self.run_code([PUSH1, 0, MLOAD, PUSH1, 0, MLOAD])
self.assertTrue(self.state.stack[0] is self.state.stack[1])
def test_mstore(self):
self.run_code([PUSH1, 42, PUSH1, 1, MSTORE, PUSH1, 1, MLOAD])
self.assert_stack([42])
self.run_code([PUSH1, 42, PUSH1, 0, MSTORE, PUSH1, 0, MLOAD])
self.assert_stack([42])
self.run_code(
[
PUSH2,
0xCA,
0xFE,
PUSH1,
64,
MSTORE,
PUSH2,
0xDE,
0xAD,
PUSH1,
62,
MSTORE,
PUSH1,
66,
MLOAD,
]
)
self.assert_stack([0xDEADCAFE0000])
def test_mstore8(self):
self.run_code([PUSH2, 0x13, 0x37, PUSH1, 30, MSTORE8, PUSH1, 0, MLOAD])
self.assert_stack([0x3700])
def test_msize(self):
self.run_code([PUSH1, 1, PUSH1, 0, MSTORE8, MSIZE])
self.assert_stack([1])
self.run_code([PUSH1, 1, PUSH1, 32, MSTORE, MSIZE])
self.assert_stack([64])
def test_invalid_opcode(self):
with self.assertRaises(utils.CodeError):
self.run_code([0x01, 0x02, 0x03, 0xFE, 0xFF])
class TestOutcomes(unittest.TestCase):
def assertBEqual(self, a, b):
self.assertTrue((a == b).is_true(), msg="%s != %s" % (a, b))
def outcomes(self, code, env={}):
code = bytes(code)
self.sm = sm.SymbolicMachine(Env(code, **env))
self.sm.execute(timeout_sec=10)
return self.sm.outcomes
def test_sload_symbolic(self):
outcome1, outcome2 = self.outcomes(
[PUSH1, 42, CALLVALUE, SSTORE, PUSH1, 0, SLOAD]
)
self.assertEqual(len(outcome1.storage_read), 0)
self.assertEqual(len(outcome1.storage_written), 1)
self.assertTrue(utils.bvv(0) in outcome2.storage_read)
self.assertEqual(len(outcome2.storage_read), 1)
def test_sstore_symbolic(self):
outcome1, outcome2 = self.outcomes(
[
PUSH1,
42,
PUSH1,
0,
SSTORE,
PUSH1,
0,
SLOAD,
PUSH1,
43,
CALLVALUE,
SSTORE,
PUSH1,
0,
SLOAD,
]
)
self.assertEqual(len(outcome1.storage_read), 0)
self.assertEqual(len(outcome1.storage_written), 1)
self.assertBEqual(outcome1.storage_written[utils.bvv(0)], utils.bvv(43))
self.assertEqual(len(outcome2.storage_read), 0)
self.assertEqual(len(outcome2.storage_written), 2)
self.assertBEqual(outcome2.storage_written[utils.bvv(0)], utils.bvv(42))
self.assertBEqual(outcome2.storage_written[outcome2.env.value], utils.bvv(43))
def test_sload(self):
outcome, = self.outcomes([PUSH1, 0, SLOAD, PUSH1, 0, SLOAD])
self.assertTrue(utils.bvv(0) in outcome.storage_read)
self.assertEqual(len(outcome.storage_read), 1)
def test_sstore(self):
outcome, = self.outcomes(
[
PUSH1,
42,
PUSH1,
0,
SSTORE,
PUSH1,
0,
SLOAD,
PUSH1,
43,
PUSH1,
0,
SSTORE,
PUSH1,
0,
SLOAD,
]
)
self.assertEqual(len(outcome.storage_read), 0)
self.assertEqual(len(outcome.storage_written), 1)
self.assertBEqual(outcome.storage_written[utils.bvv(0)], utils.bvv(43))
# TODO: test_call, test_callcode, test_selfdestruct
if __name__ == "__main__":
unittest.main()
================================================
FILE: pakala/test_state.py
================================================
import claripy
import unittest
import functools
from pakala.state import State
from pakala import env
class TestState(unittest.TestCase):
def testHashWorks(self):
state = State(env.Env(b""))
state.pc = 5
state.memory.write(0, 1, claripy.BVV(42, 8))
state.memory.write(10, 1, claripy.BVV(43, 8))
state.memory.write(20, 1, claripy.BVV(44, 8))
state_copy = state.copy()
self.assertEqual(hash(state), hash(state_copy))
state.pc = 6
self.assertNotEqual(hash(state), hash(state_copy))
state_copy.pc = 6
self.assertEqual(hash(state), hash(state_copy))
state.memory.write(10, 1, claripy.BVV(45, 8))
self.assertNotEqual(hash(state), hash(state_copy))
state_copy.memory.write(10, 1, claripy.BVV(45, 8))
self.assertEqual(hash(state), hash(state_copy))
state.stack_push(state.env.calldata.read(0, 1))
self.assertNotEqual(hash(state), hash(state_copy))
state_copy.stack_push(state_copy.env.calldata.read(0, 1))
self.assertEqual(hash(state), hash(state_copy))
def testSameHashIfDifferentOrder(self):
a = State()
b = State()
self.assertEqual(hash(a), hash(b))
e = env.Env(b"")
a.solver.add(e.value == 1)
a.solver.add(e.block_timestamp == 2)
# Same thing, different order
b.solver.add(e.block_timestamp == 2)
b.solver.add(e.value == 1)
self.assertEqual(hash(a), hash(b))
def testReplace(self):
old_env = env.Env(b"")
new_env = old_env.clean_copy()
state = State(new_env)
state.storage_written[old_env.caller] = old_env.value
state.replace(functools.partial(env.replace, old_env, state.env))
self.assertIs(state.storage_written[new_env.caller], new_env.value)
================================================
FILE: pakala/utils.py
================================================
import numbers
import logging
import claripy
from pakala import claripy_sha3
# Custom logging levels:
INFO_INTERACTIVE = 19
logging.addLevelName(INFO_INTERACTIVE, "INFO_INTERACTIVE")
ADDR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
DEFAULT_ADDRESS = claripy.BVV(0xCAFEBABEFFFFFFFFFFFFFFFFFFFFFF7CFF7247C9, 256)
DEFAULT_CALLER = claripy.BVV(0xCAFEBABEFFFFFFFFF0202FFFFFFFFF7CFF7247C9, 256)
class CodeError(Exception):
pass
class InterpreterError(Exception):
def __init__(self, state, message):
self.state = state
super().__init__(message)
def bvv(v):
return claripy.BVV(v, 256)
def get_solver():
return claripy_sha3.Solver()
def bvv_to_number(bvv):
if bvv.symbolic:
raise ValueError("Passed a BVS in bvv_to_number")
assert isinstance(bvv.args[0], numbers.Number)
return bvv.args[0]
def number_to_address(number):
return "{:#042x}".format(number)
================================================
FILE: requirements.txt
================================================
py-evm==0.3.0a12
claripy==8.19.7.25
mock
web3==5.3.0
coloredlogs==10.0
eth-utils==1.8.1
================================================
FILE: setup.py
================================================
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, "README.md"), encoding="utf-8") as f:
long_description = f.read()
with open(path.join(here, "requirements.txt")) as f:
requirements = f.read().splitlines()
setup(
name="pakala",
version="1.1.10",
description="An EVM symbolic execution tool and vulnerability scanner",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/palkeo/pakala",
author="palkeo",
author_email="ethereum@palkeo.com",
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
"Development Status :: 4 - Beta",
# Indicate who your project is intended for
"Intended Audience :: Developers",
# Pick your license as you wish
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Programming Language :: Python :: 3",
],
keywords="ethereum evm symbolic execution vulnerability scanner",
packages=find_packages(exclude=["contrib", "docs", "tests"]),
install_requires=requirements,
entry_points={"console_scripts": ["pakala=pakala.cli:main"]},
)
================================================
FILE: solidity_tests/__init__.py
================================================
================================================
FILE: solidity_tests/arbitrary_storage_write.sol
================================================
// See:
// https://github.com/Arachnid/uscc/tree/master/submissions-2017/doughoyte
// for inspiration.
contract ArbitraryStorageWrite {
uint256[] private people;
uint256 private magic;
function addPeople(uint256 key, uint256 value) public {
people[key] = value;
}
function removePeople() public {
people.length--;
}
function () external payable {
require(magic == 42);
selfdestruct(msg.sender);
}
}
================================================
FILE: solidity_tests/arbitrary_storage_write2.sol
================================================
contract ArbitraryStorageWrite {
uint256[] private people;
mapping (address => bool) owners;
modifier onlyOwners() {
require(owners[msg.sender]);
_;
}
function addPeople(uint256 key, uint256 value) public {
people[key] = value;
}
function removePeople() public {
people.length--;
}
function withdraw() public onlyOwners {
selfdestruct(msg.sender);
}
}
================================================
FILE: solidity_tests/array_write.sol
================================================
//This code is derived from the Capture the Ether https://capturetheether.com/challenges/math/mapping/
contract Map {
address public owner;
uint256[] map;
function set(uint256 key, uint256 value) public {
if (map.length <= key) {
map.length = key + 1;
}
map[key] = value;
}
function get(uint256 key) public view returns (uint256) {
return map[key];
}
function withdraw() public{
require(msg.sender == owner);
msg.sender.transfer(address(this).balance);
}
}
================================================
FILE: solidity_tests/constructor_wrongly_named.sol
================================================
contract Crowdfunding {
mapping(address => uint) public balances;
address public owner;
uint256 INVEST_MIN = 1 ether;
uint256 INVEST_MAX = 10 ether;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function crowdfunding() public {
owner = msg.sender;
}
function withdrawfunds() public onlyOwner {
msg.sender.transfer(address(this).balance);
}
function invest() public payable {
require(msg.value > INVEST_MIN && msg.value < INVEST_MAX);
balances[msg.sender] += msg.value;
}
function getBalance() public view returns (uint) {
return balances[msg.sender];
}
}
================================================
FILE: solidity_tests/delegatecall.sol
================================================
contract Proxy {
function forward(address callee, bytes memory _data) public {
bool status;
bytes memory result;
(status, result) = callee.delegatecall(_data);
require(status);
}
}
================================================
FILE: solidity_tests/mapping.sol
================================================
contract Mapping {
struct Participant {
uint total_paid;
uint payout;
}
mapping(address => Participant) participants;
function deposit() public payable {
require(msg.value > 0.1 ether);
Participant storage p = participants[msg.sender];
p.total_paid += msg.value;
p.payout += msg.value;
}
function transfer(uint amount, address beneficiary) public {
Participant storage p = participants[msg.sender];
// The following require will always hold because we are substracting
// two uint...
require(p.payout - amount > 0);
// This would be better:
//require((int)(p.payout) - (int)(amount) > 0 && (int)(amount) > 0);
p.payout -= amount;
Participant storage b = participants[beneficiary];
b.payout += amount;
}
function withdraw() public returns (int) {
Participant storage p = participants[msg.sender];
require(p.payout > 0.1 ether && p.total_paid > 0);
msg.sender.transfer(p.payout);
p.payout = 0;
return 42;
}
}
================================================
FILE: solidity_tests/mapping2.sol
================================================
contract Mapping {
struct Participant {
uint total_paid;
uint payout;
}
mapping(address => Participant) participants;
function deposit(address beneficiary) public payable {
Participant storage b = participants[beneficiary];
b.total_paid += msg.value;
b.payout += msg.value / 2;
}
function remove(uint amount, address beneficiary) public {
Participant storage b = participants[beneficiary];
require(b.payout > 0);
require(b.total_paid > 0);
b.payout -= amount;
}
function withdraw() public {
Participant storage p = participants[msg.sender];
require(p.payout > 1 ether);
msg.sender.transfer(p.payout);
p.payout = 0;
}
}
================================================
FILE: solidity_tests/multiple_write_multiple_tx.sol
================================================
contract MultipleWriteMultipleTx {
uint256 public count = 0;
function increment() public {
count++;
}
function run(uint256 input) public {
if (count < 2) {
return;
}
selfdestruct(msg.sender);
}
}
================================================
FILE: solidity_tests/multiple_write_one_tx.sol
================================================
contract MultipleWriteOneTx {
uint256 private initialized = 0;
uint256 public count = 0;
function increment() public {
require(initialized == 0);
count++;
initialized = 1;
count++;
}
function run(uint256 input) public {
require(count == 2);
selfdestruct(msg.sender);
}
}
================================================
FILE: solidity_tests/recursive_mapping.sol
================================================
contract RecursiveMapping {
struct Participant {
uint total_paid;
mapping(address => uint) balances;
}
mapping(address => Participant) participants;
function deposit(address deposit_to) public payable {
Participant storage p = participants[msg.sender];
p.total_paid += msg.value;
p.balances[deposit_to] += msg.value;
}
function transfer(uint amount, address take_from, address deposit_to) public {
Participant storage p = participants[msg.sender];
p.balances[take_from] -= amount;
p.balances[deposit_to] += amount;
}
function withdraw(address withdraw_from) public returns (int) {
Participant storage p = participants[withdraw_from];
msg.sender.transfer(p.balances[msg.sender]);
p.balances[msg.sender] = 0;
return 42;
}
}
================================================
FILE: solidity_tests/simple_ether_drain.sol
================================================
contract SimpleEtherDrain {
function withdrawAllAnyone() public {
msg.sender.transfer(address(this).balance);
}
function () external payable {
}
}
================================================
FILE: solidity_tests/simple_suicide.sol
================================================
contract SimpleSuicide {
function sudicideAnyone() public {
selfdestruct(msg.sender);
}
}
================================================
FILE: solidity_tests/string.sol
================================================
contract String {
function passwordSend(bytes32 s) public payable {
require(s == "12345678901234567890magic");
msg.sender.send(address(this).balance / 5 - (0.1 ether));
}
}
================================================
FILE: solidity_tests/string_unbounded.sol
=====
gitextract_xfaybpz0/
├── .circleci/
│ └── config.yml
├── .flake8
├── .gitignore
├── LICENSE.txt
├── README.md
├── pakala/
│ ├── __init__.py
│ ├── analyzer.py
│ ├── claripy_sha3.py
│ ├── cli.py
│ ├── env.py
│ ├── memory.py
│ ├── recursive_analyzer.py
│ ├── sm.py
│ ├── state.py
│ ├── summary.py
│ ├── test_analyzer.py
│ ├── test_claripy_sha3.py
│ ├── test_env.py
│ ├── test_memory.py
│ ├── test_recursive_analyzer.py
│ ├── test_sm.py
│ ├── test_state.py
│ └── utils.py
├── requirements.txt
├── setup.py
└── solidity_tests/
├── __init__.py
├── arbitrary_storage_write.sol
├── arbitrary_storage_write2.sol
├── array_write.sol
├── constructor_wrongly_named.sol
├── delegatecall.sol
├── mapping.sol
├── mapping2.sol
├── multiple_write_multiple_tx.sol
├── multiple_write_one_tx.sol
├── recursive_mapping.sol
├── simple_ether_drain.sol
├── simple_suicide.sol
├── string.sol
├── string_unbounded.sol
├── test_solidity.py
└── wrapped_ether.sol
SYMBOL INDEX (288 symbols across 18 files)
FILE: pakala/analyzer.py
class BaseAnalyzer (line 22) | class BaseAnalyzer(object):
method __init__ (line 28) | def __init__(self, max_wei_to_send, min_wei_to_receive, block="latest"):
method hex_addr (line 44) | def hex_addr(self):
method _read_storage_key (line 49) | def _read_storage_key(self, key):
method _fill_actual_storage (line 52) | def _fill_actual_storage(self):
method _read_storage (line 84) | def _read_storage(self, state, key):
method check_state (line 117) | def check_state(self, state, path=None):
class Analyzer (line 204) | class Analyzer(BaseAnalyzer):
method __init__ (line 207) | def __init__(self, address, caller, *args, **kwargs):
FILE: pakala/claripy_sha3.py
function Sha3 (line 16) | def Sha3(x):
function _symbolize_hashes (line 20) | def _symbolize_hashes(ast, hashes):
function _no_sha3_symbol (line 41) | def _no_sha3_symbol(ast):
function _this_sha3_symbol (line 53) | def _this_sha3_symbol(ast, symbol):
function _no_sha3_symbols (line 61) | def _no_sha3_symbols(constraints):
function _hash_depth (line 65) | def _hash_depth(hashes, hash_symbol):
function get_claripy_solver (line 75) | def get_claripy_solver():
class Solver (line 80) | class Solver:
method __init__ (line 83) | def __init__(self, claripy_solver=None, hashes=None):
method branch (line 87) | def branch(self):
method add (line 90) | def add(self, constraints, **kwargs):
method satisfiable (line 98) | def satisfiable(self, extra_constraints=(), **kwargs):
method eval (line 108) | def eval(self, e, n, extra_constraints=(), **kwargs):
method batch_eval (line 116) | def batch_eval(self, e, n, extra_constraints=(), **kwargs):
method max (line 119) | def max(self, e, extra_constraints=(), **kwargs):
method min (line 127) | def min(self, e, extra_constraints=(), **kwargs):
method solution (line 135) | def solution(self, e, v, extra_constraints=(), **kwargs):
method _hash_constraints (line 143) | def _hash_constraints(self, extra_constraints, hashes, pairs_done=None):
method replace (line 215) | def replace(self, r):
method regenerate_hash_symbols (line 224) | def regenerate_hash_symbols(self):
method combine (line 239) | def combine(self, others):
method downsize (line 259) | def downsize(self):
method simplify (line 262) | def simplify(self):
method __repr__ (line 265) | def __repr__(self):
method as_dict (line 271) | def as_dict(self):
method constraints (line 275) | def constraints(self):
FILE: pakala/cli.py
function err_exit (line 36) | def err_exit(message):
function ethWeiAmount (line 41) | def ethWeiAmount(arg):
function addressOrStdin (line 50) | def addressOrStdin(s):
function main (line 158) | def main():
FILE: pakala/env.py
class Env (line 27) | class Env(object):
method __init__ (line 28) | def __init__(self, code, **kwargs):
method __repr__ (line 41) | def __repr__(self):
method as_dict (line 48) | def as_dict(self):
method clean_copy (line 51) | def clean_copy(self):
method extra_constraints (line 73) | def extra_constraints(self):
method solution_string (line 80) | def solution_string(self, solver):
function replace (line 92) | def replace(old_env, new_env, var):
FILE: pakala/memory.py
function _slice (line 14) | def _slice(v, start, end):
class Memory (line 21) | class Memory(object):
method __init__ (line 24) | def __init__(self):
method __str__ (line 27) | def __str__(self):
method __hash__ (line 30) | def __hash__(self):
method _default (line 33) | def _default(self, addr, size):
method read (line 36) | def read(self, addr, size):
method write (line 70) | def write(self, addr, size, value):
method copy_from (line 109) | def copy_from(self, other, start_self, start_other, size):
method size (line 119) | def size(self):
method copy (line 125) | def copy(self):
class CalldataMemory (line 134) | class CalldataMemory(Memory):
method _default (line 137) | def _default(self, addr, size):
method write (line 140) | def write(self, *args, **kwargs):
method copy_from (line 143) | def copy_from(self, *args, **kwargs):
class CalldataMemoryView (line 147) | class CalldataMemoryView(object):
method __init__ (line 151) | def __init__(self, mem, addr, size):
method __hash__ (line 156) | def __hash__(self):
method size (line 160) | def size(self):
method __getitem__ (line 163) | def __getitem__(self, item):
FILE: pakala/recursive_analyzer.py
function is_function (line 37) | def is_function(state, function):
function with_new_env (line 41) | def with_new_env(state):
class RecursiveAnalyzer (line 59) | class RecursiveAnalyzer(analyzer.BaseAnalyzer):
method __init__ (line 60) | def __init__(self, *args, **kwargs):
method address (line 75) | def address(self):
method caller (line 79) | def caller(self):
method _search_path (line 82) | def _search_path(self, composite_state, path):
method _append_state (line 115) | def _append_state(self, composite_state, state):
method check_states (line 201) | def check_states(self, states, timeout, max_depth):
FILE: pakala/sm.py
class MultipleSolutionsError (line 49) | class MultipleSolutionsError(ValueError):
function bool_to_bv (line 53) | def bool_to_bv(b):
class SymbolicMachine (line 57) | class SymbolicMachine:
method __init__ (line 61) | def __init__(self, env, fuzz=True):
method add_branch (line 82) | def add_branch(self, state):
method add_for_fuzzing (line 108) | def add_for_fuzzing(self, state, variable, tries):
method exec_branch (line 153) | def exec_branch(self, state): # pylint:disable=invalid-name
method execute (line 683) | def execute(self, timeout_sec):
method add_outcome (line 776) | def add_outcome(self, state):
method add_partial_outcome (line 782) | def add_partial_outcome(self, state):
method get_coverage (line 788) | def get_coverage(self):
FILE: pakala/state.py
class State (line 11) | class State(object):
method __init__ (line 16) | def __init__(self, env=None):
method __repr__ (line 40) | def __repr__(self):
method _as_dict (line 53) | def _as_dict(self):
method debug_string (line 63) | def debug_string(self):
method clean (line 83) | def clean(self):
method replace (line 90) | def replace(self, r):
method __hash__ (line 109) | def __hash__(self):
method stack_push (line 134) | def stack_push(self, x):
method stack_pop (line 139) | def stack_pop(self):
method is_interesting (line 144) | def is_interesting(self):
method copy (line 149) | def copy(self):
method __eq__ (line 164) | def __eq__(self, other):
method __ne__ (line 167) | def __ne__(self, other):
FILE: pakala/summary.py
class HumanSummarizer (line 17) | class HumanSummarizer:
method __init__ (line 18) | def __init__(self, symbolic_machine):
method states_by_method (line 30) | def states_by_method(self):
method print_methods (line 44) | def print_methods(self):
FILE: pakala/test_analyzer.py
class TestCheckState (line 16) | class TestCheckState(unittest.TestCase):
method setUp (line 17) | def setUp(self):
method check_state (line 28) | def check_state(self, state):
method get_call (line 31) | def get_call(self, value, to=None):
method get_delegatecall (line 44) | def get_delegatecall(self, to=None):
method test_nothing (line 56) | def test_nothing(self):
method test_selfdestruct (line 59) | def test_selfdestruct(self):
method test_send_back (line 63) | def test_send_back(self):
method test_delegatecall (line 67) | def test_delegatecall(self):
method test_delegatecall_to_other (line 71) | def test_delegatecall_to_other(self):
method test_send_back_more (line 75) | def test_send_back_more(self):
method test_send_back_if_impossible_block (line 79) | def test_send_back_if_impossible_block(self):
method test_send_back_if_possible_block (line 91) | def test_send_back_if_possible_block(self):
method test_send_back_nothing (line 103) | def test_send_back_nothing(self):
method test_send_back_twice (line 107) | def test_send_back_twice(self):
method test_send_back_fixed_amount (line 112) | def test_send_back_fixed_amount(self):
method test_send_back_to_someone_else (line 116) | def test_send_back_to_someone_else(self):
method test_send_all (line 122) | def test_send_all(self):
method test_send_back_calldata (line 126) | def test_send_back_calldata(self):
method test_send_back_negative_signed (line 131) | def test_send_back_negative_signed(self):
method test_send_back_negative_unsigned (line 136) | def test_send_back_negative_unsigned(self):
method test_send_all_and_selfdestruct (line 146) | def test_send_all_and_selfdestruct(self):
method test_read_concrete (line 151) | def test_read_concrete(self):
method test_non_exhaustive_storage (line 165) | def test_non_exhaustive_storage(self):
method test_non_exhaustive_storage2 (line 180) | def test_non_exhaustive_storage2(self):
method test_exhaustive_storage (line 194) | def test_exhaustive_storage(self):
FILE: pakala/test_claripy_sha3.py
class TestSha3Support (line 13) | class TestSha3Support(unittest.TestCase):
method test_sha3_equality (line 14) | def test_sha3_equality(self):
method test_sha3_unequality (line 20) | def test_sha3_unequality(self):
method test_sha3_equality_different_length (line 26) | def test_sha3_equality_different_length(self):
method test_solver_basic (line 32) | def test_solver_basic(self):
method test_solver_arithmetics (line 58) | def test_solver_arithmetics(self):
method test_solver_one_var (line 83) | def test_solver_one_var(self):
method test_solver_recursive (line 95) | def test_solver_recursive(self):
method test_solver_recursive_unbalanced (line 134) | def test_solver_recursive_unbalanced(self):
method test_solver_three_symbols (line 153) | def test_solver_three_symbols(self):
method test_solver_copy (line 170) | def test_solver_copy(self):
method test_env_replace_merge (line 178) | def test_env_replace_merge(self):
method test_env_replace_merge_with_recursive_hash (line 216) | def test_env_replace_merge_with_recursive_hash(self):
method test_cannot_combine (line 254) | def test_cannot_combine(self):
FILE: pakala/test_env.py
class TestEnv (line 7) | class TestEnv(unittest.TestCase):
method testReplace (line 8) | def testReplace(self):
method testReplace2 (line 15) | def testReplace2(self):
FILE: pakala/test_memory.py
class TestMemory (line 11) | class TestMemory(unittest.TestCase):
method setUp (line 12) | def setUp(self):
method assertBEqual (line 15) | def assertBEqual(self, a, b):
method assertBNotEqual (line 18) | def assertBNotEqual(self, a, b):
method test_read_default (line 21) | def test_read_default(self):
method overwrite (line 24) | def overwrite(self, a, b):
method test_overwrite_same (line 31) | def test_overwrite_same(self):
method test_overwrite_simple (line 34) | def test_overwrite_simple(self):
method test_overwrite_left (line 37) | def test_overwrite_left(self):
method test_overwrite_right (line 40) | def test_overwrite_right(self):
method test_partial_overwrite_left (line 43) | def test_partial_overwrite_left(self):
method test_partial_overwrite_right (line 52) | def test_partial_overwrite_right(self):
method test_overwrite_inside (line 61) | def test_overwrite_inside(self):
method test_successive_left (line 66) | def test_successive_left(self):
method test_successive_right (line 71) | def test_successive_right(self):
method test_successive (line 76) | def test_successive(self):
method test_read (line 81) | def test_read(self):
method test_read_write_size_0 (line 89) | def test_read_write_size_0(self):
method test_size (line 100) | def test_size(self):
method test_copy (line 105) | def test_copy(self):
method test_hash (line 112) | def test_hash(self):
method test_copy_from (line 128) | def test_copy_from(self):
method test_overwrite_0 (line 147) | def test_overwrite_0(self):
class TestCalldataMemory (line 161) | class TestCalldataMemory(unittest.TestCase):
method setUp (line 162) | def setUp(self):
method test_readonly (line 165) | def test_readonly(self):
method test_read_default (line 171) | def test_read_default(self):
FILE: pakala/test_recursive_analyzer.py
class TestWithNewEnv (line 20) | class TestWithNewEnv(unittest.TestCase):
method test_with_new_env (line 21) | def test_with_new_env(self):
class TestCheckStates (line 67) | class TestCheckStates(unittest.TestCase):
method setUp (line 74) | def setUp(self):
method check_states (line 77) | def check_states(self, states, mock_storage=None):
method get_call (line 86) | def get_call(self, value, to=None):
method test_nothing (line 99) | def test_nothing(self):
method test_simple (line 102) | def test_simple(self):
method test_selfdestruct_simple (line 106) | def test_selfdestruct_simple(self):
method test_call_simple (line 111) | def test_call_simple(self):
method test_write_and_selfdestruct (line 116) | def test_write_and_selfdestruct(self):
method test_sha3_key (line 135) | def test_sha3_key(self):
method test_sha3_value1 (line 163) | def test_sha3_value1(self):
method test_sha3_value2 (line 187) | def test_sha3_value2(self):
method test_write_write_and_selfdestruct (line 210) | def test_write_write_and_selfdestruct(self):
method test_send_after_write (line 243) | def test_send_after_write(self):
method test_symbolic_storage (line 308) | def test_symbolic_storage(self):
FILE: pakala/test_sm.py
class TestSymbolicMachine (line 23) | class TestSymbolicMachine(unittest.TestCase):
method setUp (line 26) | def setUp(self):
method test_add_branch (line 36) | def test_add_branch(self):
method test_add_for_fuzzing (line 57) | def test_add_for_fuzzing(self):
method test_execute (line 75) | def test_execute(self):
method test_get_coverage (line 78) | def test_get_coverage(self):
class TestInstructions (line 83) | class TestInstructions(unittest.TestCase):
method assertBEqual (line 84) | def assertBEqual(self, a, b):
method run_code (line 87) | def run_code(self, code, env={}):
method assert_stack (line 93) | def assert_stack(self, stack):
method test_jumpdest (line 98) | def test_jumpdest(self):
method test_add (line 101) | def test_add(self):
method test_sub (line 107) | def test_sub(self):
method test_mul (line 111) | def test_mul(self):
method test_div (line 115) | def test_div(self):
method test_sdiv (line 127) | def test_sdiv(self):
method test_mod (line 133) | def test_mod(self):
method test_smod (line 141) | def test_smod(self):
method test_addmod (line 151) | def test_addmod(self):
method test_mulmod (line 161) | def test_mulmod(self):
method test_exp (line 171) | def test_exp(self):
method test_shl (line 175) | def test_shl(self):
method test_shr (line 185) | def test_shr(self):
method test_sar (line 195) | def test_sar(self):
method test_signextend (line 205) | def test_signextend(self):
method test_lt (line 217) | def test_lt(self):
method test_gt (line 227) | def test_gt(self):
method test_slt (line 237) | def test_slt(self):
method test_sgt (line 247) | def test_sgt(self):
method test_eq (line 257) | def test_eq(self):
method test_iszero (line 263) | def test_iszero(self):
method test_and (line 269) | def test_and(self):
method test_or (line 273) | def test_or(self):
method test_xor (line 279) | def test_xor(self):
method test_not (line 288) | def test_not(self):
method test_byte (line 300) | def test_byte(self):
method test_pc (line 316) | def test_pc(self):
method test_gas (line 320) | def test_gas(self):
method test_address (line 324) | def test_address(self):
method test_balance (line 328) | def test_balance(self):
method test_origin (line 335) | def test_origin(self):
method test_caller (line 339) | def test_caller(self):
method test_callvalue (line 343) | def test_callvalue(self):
method test_blockhash (line 347) | def test_blockhash(self):
method test_timestamp (line 351) | def test_timestamp(self):
method test_number (line 355) | def test_number(self):
method test_coinbase (line 359) | def test_coinbase(self):
method test_difficulty (line 363) | def test_difficulty(self):
method test_pop (line 367) | def test_pop(self):
method test_jump (line 373) | def test_jump(self):
method test_jumpi (line 384) | def test_jumpi(self):
method test_push (line 416) | def test_push(self):
method test_dup (line 422) | def test_dup(self):
method test_swap (line 428) | def test_swap(self):
method test_log (line 434) | def test_log(self):
method test_sha3_empty (line 437) | def test_sha3_empty(self):
method test_sha3_zeros (line 446) | def test_sha3_zeros(self):
method test_sha3_a_mstore8 (line 455) | def test_sha3_a_mstore8(self):
method test_sha3_a_mstore (line 465) | def test_sha3_a_mstore(self):
method test_stop (line 475) | def test_stop(self):
method test_return (line 479) | def test_return(self):
method test_calldataload (line 483) | def test_calldataload(self):
method test_calldatasize (line 489) | def test_calldatasize(self):
method test_calldatacopy (line 492) | def test_calldatacopy(self):
method test_codesize (line 515) | def test_codesize(self):
method test_extcodesize_self (line 519) | def test_extcodesize_self(self):
method test_extcodesize_other (line 523) | def test_extcodesize_other(self):
method test_codecopy (line 535) | def test_codecopy(self):
method test_mload (line 540) | def test_mload(self):
method test_mstore (line 544) | def test_mstore(self):
method test_mstore8 (line 570) | def test_mstore8(self):
method test_msize (line 574) | def test_msize(self):
method test_invalid_opcode (line 580) | def test_invalid_opcode(self):
class TestOutcomes (line 585) | class TestOutcomes(unittest.TestCase):
method assertBEqual (line 586) | def assertBEqual(self, a, b):
method outcomes (line 589) | def outcomes(self, code, env={}):
method test_sload_symbolic (line 595) | def test_sload_symbolic(self):
method test_sstore_symbolic (line 605) | def test_sstore_symbolic(self):
method test_sload (line 635) | def test_sload(self):
method test_sstore (line 640) | def test_sstore(self):
FILE: pakala/test_state.py
class TestState (line 9) | class TestState(unittest.TestCase):
method testHashWorks (line 10) | def testHashWorks(self):
method testSameHashIfDifferentOrder (line 34) | def testSameHashIfDifferentOrder(self):
method testReplace (line 50) | def testReplace(self):
FILE: pakala/utils.py
class CodeError (line 18) | class CodeError(Exception):
class InterpreterError (line 22) | class InterpreterError(Exception):
method __init__ (line 23) | def __init__(self, state, message):
function bvv (line 28) | def bvv(v):
function get_solver (line 32) | def get_solver():
function bvv_to_number (line 36) | def bvv_to_number(bvv):
function number_to_address (line 43) | def number_to_address(number):
FILE: solidity_tests/test_solidity.py
class SolidityTest (line 31) | class SolidityTest(unittest.TestCase):
method __init__ (line 32) | def __init__(self, filename):
method shortDescription (line 36) | def shortDescription(self):
method runTest (line 40) | def runTest(self):
function load_tests (line 84) | def load_tests(loader, tests, pattern):
Condensed preview — 42 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (209K chars).
[
{
"path": ".circleci/config.yml",
"chars": 1374,
"preview": "# Python CircleCI 2.0 configuration file\n#\n# Check https://circleci.com/docs/2.0/language-python/ for more details\n#\nver"
},
{
"path": ".flake8",
"chars": 30,
"preview": "[flake8]\nmax-line-length = 88\n"
},
{
"path": ".gitignore",
"chars": 19,
"preview": "*.pyc\n__pycache__/\n"
},
{
"path": "LICENSE.txt",
"chars": 32473,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "README.md",
"chars": 2679,
"preview": "Pakala\n======\n\n[](https://pypi.python.org/pypi/pakala)\n[ 2018 Korantin Auguste\n\n This"
},
{
"path": "pakala/env.py",
"chars": 3208,
"preview": "import pprint\nimport time\n\nimport claripy\nfrom eth.vm import code_stream\nfrom web3 import Web3\n\nfrom pakala import memor"
},
{
"path": "pakala/memory.py",
"chars": 5663,
"preview": "import logging\n\nimport claripy\n\nfrom pakala import utils\n\nlogger = logging.getLogger(__name__)\n\n# Maximum size the memor"
},
{
"path": "pakala/recursive_analyzer.py",
"chars": 9244,
"preview": "\"\"\"\n pakala: EVM symbolic execution tool and vulnerability scanner.\n Copyright (C) 2018 Korantin Auguste\n\n This"
},
{
"path": "pakala/sm.py",
"chars": 34140,
"preview": "\"\"\"\n pakala: EVM symbolic execution tool and vulnerability scanner.\n Copyright (C) 2018 Korantin Auguste\n\n This"
},
{
"path": "pakala/state.py",
"chars": 5593,
"preview": "import logging\nimport pprint\nimport json\n\nfrom pakala import memory\nfrom pakala import utils\n\nlogger = logging.getLogger"
},
{
"path": "pakala/summary.py",
"chars": 3256,
"preview": "\"\"\"Experimental module to print basic information about a contract.\n\nFor now it gives a list of its methods (and try to "
},
{
"path": "pakala/test_analyzer.py",
"chars": 7538,
"preview": "import claripy\nimport unittest\nfrom unittest.mock import patch\nimport logging\n\nfrom pakala.analyzer import Analyzer\nfrom"
},
{
"path": "pakala/test_claripy_sha3.py",
"chars": 9517,
"preview": "import unittest\nimport functools\nimport logging\n\nimport claripy\n\nfrom pakala.claripy_sha3 import Sha3\nfrom pakala.utils "
},
{
"path": "pakala/test_env.py",
"chars": 601,
"preview": "import unittest\nimport claripy\n\nfrom pakala import env\n\n\nclass TestEnv(unittest.TestCase):\n def testReplace(self):\n "
},
{
"path": "pakala/test_memory.py",
"chars": 6543,
"preview": "import claripy\nimport unittest\nimport logging\n\nfrom pakala.memory import Memory, CalldataMemory\nfrom pakala import utils"
},
{
"path": "pakala/test_recursive_analyzer.py",
"chars": 13696,
"preview": "import claripy\nimport unittest\nimport logging\nimport random\nimport itertools\n\nfrom pakala.recursive_analyzer import Recu"
},
{
"path": "pakala/test_sm.py",
"chars": 22383,
"preview": "import unittest\nfrom unittest import mock\nimport random\nimport numbers\nimport codecs\n\nimport claripy\n\nfrom pakala.env im"
},
{
"path": "pakala/test_state.py",
"chars": 1847,
"preview": "import claripy\nimport unittest\nimport functools\n\nfrom pakala.state import State\nfrom pakala import env\n\n\nclass TestState"
},
{
"path": "pakala/utils.py",
"chars": 924,
"preview": "import numbers\nimport logging\n\nimport claripy\n\nfrom pakala import claripy_sha3\n\n# Custom logging levels:\nINFO_INTERACTIV"
},
{
"path": "requirements.txt",
"chars": 88,
"preview": "py-evm==0.3.0a12\nclaripy==8.19.7.25\nmock\nweb3==5.3.0\ncoloredlogs==10.0\neth-utils==1.8.1\n"
},
{
"path": "setup.py",
"chars": 1464,
"preview": "# Always prefer setuptools over distutils\nfrom setuptools import setup, find_packages\n\n# To use a consistent encoding\nfr"
},
{
"path": "solidity_tests/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "solidity_tests/arbitrary_storage_write.sol",
"chars": 436,
"preview": "// See:\n// https://github.com/Arachnid/uscc/tree/master/submissions-2017/doughoyte\n// for inspiration.\n\ncontract Arbitra"
},
{
"path": "solidity_tests/arbitrary_storage_write2.sol",
"chars": 397,
"preview": "contract ArbitraryStorageWrite {\n uint256[] private people;\n mapping (address => bool) owners;\n\n modifier onlyOwners("
},
{
"path": "solidity_tests/array_write.sol",
"chars": 550,
"preview": "//This code is derived from the Capture the Ether https://capturetheether.com/challenges/math/mapping/\n\ncontract Map {\n "
},
{
"path": "solidity_tests/constructor_wrongly_named.sol",
"chars": 631,
"preview": "contract Crowdfunding {\n\n mapping(address => uint) public balances;\n address public owner;\n uint256 INVEST_MIN = 1 et"
},
{
"path": "solidity_tests/delegatecall.sol",
"chars": 202,
"preview": "contract Proxy {\n function forward(address callee, bytes memory _data) public {\n bool status;\n bytes memory resul"
},
{
"path": "solidity_tests/mapping.sol",
"chars": 1112,
"preview": "contract Mapping {\n struct Participant {\n uint total_paid;\n uint payout;\n }\n\n mapping(address => "
},
{
"path": "solidity_tests/mapping2.sol",
"chars": 765,
"preview": "contract Mapping {\n struct Participant {\n uint total_paid;\n uint payout;\n }\n\n mapping(address => "
},
{
"path": "solidity_tests/multiple_write_multiple_tx.sol",
"chars": 263,
"preview": "contract MultipleWriteMultipleTx {\n uint256 public count = 0;\n\n function increment() public {\n count++;\n "
},
{
"path": "solidity_tests/multiple_write_one_tx.sol",
"chars": 345,
"preview": "contract MultipleWriteOneTx {\n uint256 private initialized = 0;\n uint256 public count = 0;\n\n function increment"
},
{
"path": "solidity_tests/recursive_mapping.sol",
"chars": 859,
"preview": "contract RecursiveMapping {\n struct Participant {\n uint total_paid;\n mapping(address => uint) balances;"
},
{
"path": "solidity_tests/simple_ether_drain.sol",
"chars": 162,
"preview": "contract SimpleEtherDrain {\n\n function withdrawAllAnyone() public {\n msg.sender.transfer(address(this).balance);\n }"
},
{
"path": "solidity_tests/simple_suicide.sol",
"chars": 100,
"preview": "contract SimpleSuicide {\n\n function sudicideAnyone() public {\n selfdestruct(msg.sender);\n }\n\n}\n"
},
{
"path": "solidity_tests/string.sol",
"chars": 185,
"preview": "contract String {\n function passwordSend(bytes32 s) public payable {\n require(s == \"12345678901234567890magic\");\n "
},
{
"path": "solidity_tests/string_unbounded.sol",
"chars": 527,
"preview": "library StringUtils {\n function equal(string memory _a, string memory _b) internal returns (bool) {\n bytes mem"
},
{
"path": "solidity_tests/test_solidity.py",
"chars": 2879,
"preview": "import unittest\nimport glob\nimport os\nimport logging\nimport json\nimport subprocess\nimport codecs\nimport collections\nimpo"
},
{
"path": "solidity_tests/wrapped_ether.sol",
"chars": 1644,
"preview": "contract WETH9 {\n string public name = \"Wrapped Ether\";\n string public symbol = \"WETH\";\n uint8 public de"
}
]
About this extraction
This page contains the full source code of the palkeo/pakala GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 42 files (195.2 KB), approximately 48.1k tokens, and a symbol index with 288 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.