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