diff --git a/COPYING b/COPYING deleted file mode 100644 index 53d1f3d01..000000000 --- a/COPYING +++ /dev/null @@ -1,675 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. - diff --git a/cmd/opera/launcher/chaincmd.go b/cmd/opera/launcher/chaincmd.go index 58acde6a3..a6ee7dbd2 100644 --- a/cmd/opera/launcher/chaincmd.go +++ b/cmd/opera/launcher/chaincmd.go @@ -8,9 +8,18 @@ import ( var ( EvmExportMode = cli.StringFlag{ Name: "export.evm.mode", - Usage: `EVM export mode ("full" or "ext-mpt" or "mpt" or "none")`, + Usage: `EVM export mode ("full" or "ext-mpt" or "mpt")`, Value: "mpt", } + EvmExportExclude = cli.StringFlag{ + Name: "export.evm.exclude", + Usage: `DB of EVM keys to exclude from genesis`, + } + GenesisExportSections = cli.StringFlag{ + Name: "export.sections", + Usage: `Genesis sections to export separated by comma (e.g. "brs-1" or "ers" or "evm-2")`, + Value: "brs,ers,evm", + } importCommand = cli.Command{ Name: "import", Usage: "Import a blockchain file", @@ -132,11 +141,13 @@ be gzipped { Name: "genesis", Usage: "Export current state into a genesis file", - ArgsUsage: " [ ] [--export.evm.mode=none]", + ArgsUsage: " [ ] [--export.evm.mode=MODE --export.evm.exclude=DB_PATH --export.sections=A,B,C]", Action: utils.MigrateFlags(exportGenesis), Flags: []cli.Flag{ DataDirFlag, EvmExportMode, + EvmExportExclude, + GenesisExportSections, }, Description: ` opera export genesis @@ -146,6 +157,20 @@ Requires a first argument of the file to write to. Optional second and third arguments control the first and last epoch to write. EVM export mode is configured with --export.evm.mode. +`, + }, + { + Name: "evm-keys", + Usage: "Export EVM node keys", + ArgsUsage: "", + Action: utils.MigrateFlags(exportEvmKeys), + Flags: []cli.Flag{ + DataDirFlag, + }, + Description: ` + opera export evm-keys + +Requires a first argument of the DB directory to write to. `, }, }, diff --git a/cmd/opera/launcher/check.go b/cmd/opera/launcher/check.go index 03de24224..5322c58d0 100644 --- a/cmd/opera/launcher/check.go +++ b/cmd/opera/launcher/check.go @@ -27,12 +27,14 @@ func checkEvm(ctx *cli.Context) error { start, reported := time.Now(), time.Now() var prevPoint idx.Block + var prevIndex idx.Block checkBlocks := func(stateOK func(root common.Hash) (bool, error)) { var ( lastIdx = gdb.GetLatestBlockIndex() prevPointRootExist bool ) gdb.ForEachBlock(func(index idx.Block, block *inter.Block) { + prevIndex = index found, err := stateOK(common.Hash(block.Root)) if found != prevPointRootExist { if index > 0 && found { @@ -57,9 +59,9 @@ func checkEvm(ctx *cli.Context) error { }) } - if err := evms.CheckEvm(checkBlocks); err != nil { + if err := evms.CheckEvm(checkBlocks, true); err != nil { return err } - log.Info("EVM storage is verified", "last", prevPoint, "elapsed", common.PrettyDuration(time.Since(start))) + log.Info("EVM storage is verified", "last", prevIndex, "elapsed", common.PrettyDuration(time.Since(start))) return nil } diff --git a/cmd/opera/launcher/config.go b/cmd/opera/launcher/config.go index 610d5ec21..7602bdf0c 100644 --- a/cmd/opera/launcher/config.go +++ b/cmd/opera/launcher/config.go @@ -90,6 +90,11 @@ var ( Usage: "Sets a cap on transaction fee (in FTM) that can be sent via the RPC APIs (0 = no cap)", Value: gossip.DefaultConfig(cachescale.Identity).RPCTxFeeCap, } + RPCGlobalTimeoutFlag = cli.DurationFlag{ + Name: "rpc.timeout", + Usage: "Time limit for RPC calls execution", + Value: gossip.DefaultConfig(cachescale.Identity).RPCTimeout, + } SyncModeFlag = cli.StringFlag{ Name: "syncmode", @@ -328,6 +333,9 @@ func gossipConfigWithFlags(ctx *cli.Context, src gossip.Config) (gossip.Config, if ctx.GlobalIsSet(RPCGlobalTxFeeCapFlag.Name) { cfg.RPCTxFeeCap = ctx.GlobalFloat64(RPCGlobalTxFeeCapFlag.Name) } + if ctx.GlobalIsSet(RPCGlobalTimeoutFlag.Name) { + cfg.RPCTimeout = ctx.GlobalDuration(RPCGlobalTimeoutFlag.Name) + } if ctx.GlobalIsSet(SyncModeFlag.Name) { if syncmode := ctx.GlobalString(SyncModeFlag.Name); syncmode != "full" && syncmode != "snap" { utils.Fatalf("--%s must be either 'full' or 'snap'", SyncModeFlag.Name) diff --git a/cmd/opera/launcher/db-transform.go b/cmd/opera/launcher/db-transform.go index 59b933ef0..61f0d2c81 100644 --- a/cmd/opera/launcher/db-transform.go +++ b/cmd/opera/launcher/db-transform.go @@ -16,6 +16,7 @@ import ( "gopkg.in/urfave/cli.v1" "github.com/Fantom-foundation/go-opera/integration" + "github.com/Fantom-foundation/go-opera/utils/compactdb" ) func dbTransform(ctx *cli.Context) error { @@ -255,16 +256,17 @@ func transformComponent(datadir string, dbTypes, tmpDbTypes map[multidb.TypeName } oldDB = batched.Wrap(oldDB) defer oldDB.Close() + oldHumanName := path.Join(string(e.Old.Type), e.Old.Name) newDB, err := tmpDbTypes[e.New.Type].OpenDB(e.New.Name) if err != nil { return err } toMove[dbLocatorOf(e.New)] = true - newDbName := "tmp/" + e.New.Name newDB = batched.Wrap(newDB) defer newDB.Close() - log.Info("Copying DB table", "req", e.Req, "old_db_type", e.Old.Type, "old_db_name", e.Old.Name, "old_table", e.Old.Table, - "new_db_type", e.New.Type, "new_db_name", newDbName, "new_table", e.New.Table) + newHumanName := path.Join("tmp", string(e.New.Type), e.New.Name) + log.Info("Copying DB table", "req", e.Req, "old_db", oldHumanName, "old_table", e.Old.Table, + "new_db", newHumanName, "new_table", e.New.Table) oldTable := table.New(oldDB, []byte(e.Old.Table)) newTable := table.New(newDB, []byte(e.New.Table)) it := oldTable.NewIterator(nil, nil) @@ -288,6 +290,11 @@ func transformComponent(datadir string, dbTypes, tmpDbTypes map[multidb.TypeName keys = keys[:0] values = values[:0] } + err = compactdb.Compact(newTable, newHumanName) + if err != nil { + log.Error("Database compaction failed", "err", err) + return err + } return nil }() if err != nil { diff --git a/cmd/opera/launcher/dbcmd.go b/cmd/opera/launcher/dbcmd.go index 9228dd427..644dfd8c9 100644 --- a/cmd/opera/launcher/dbcmd.go +++ b/cmd/opera/launcher/dbcmd.go @@ -15,6 +15,7 @@ import ( "github.com/Fantom-foundation/go-opera/gossip" "github.com/Fantom-foundation/go-opera/integration" + "github.com/Fantom-foundation/go-opera/utils/compactdb" ) var ( @@ -127,31 +128,36 @@ func compact(ctx *cli.Context) error { producers := makeCheckedDBsProducers(cfg) for typ, p := range producers { for _, name := range p.Names() { - humanName := path.Join(string(typ), name) - db, err := p.OpenDB(name) - defer db.Close() - if err != nil { - log.Error("Cannot open db or db does not exists", "db", humanName) + if err := compactDB(typ, name, p); err != nil { return err } + } + } - log.Info("Stats before compaction", "db", humanName) - showDbStats(db) + return nil +} - log.Info("Triggering compaction", "db", humanName) - for b := byte(0); b < 255; b++ { - log.Trace("Compacting chain database", "db", humanName, "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1)) - if err := db.Compact([]byte{b}, []byte{b + 1}); err != nil { - log.Error("Database compaction failed", "err", err) - return err - } - } +func compactDB(typ multidb.TypeName, name string, producer kvdb.DBProducer) error { + humanName := path.Join(string(typ), name) + db, err := producer.OpenDB(name) + defer db.Close() + if err != nil { + log.Error("Cannot open db or db does not exists", "db", humanName) + return err + } - log.Info("Stats after compaction", "db", humanName) - showDbStats(db) - } + log.Info("Stats before compaction", "db", humanName) + showDbStats(db) + + err = compactdb.Compact(db, humanName) + if err != nil { + log.Error("Database compaction failed", "err", err) + return err } + log.Info("Stats after compaction", "db", humanName) + showDbStats(db) + return nil } diff --git a/cmd/opera/launcher/export.go b/cmd/opera/launcher/export.go index e16411364..30b7bd48c 100644 --- a/cmd/opera/launcher/export.go +++ b/cmd/opera/launcher/export.go @@ -10,11 +10,14 @@ import ( "github.com/Fantom-foundation/lachesis-base/hash" "github.com/Fantom-foundation/lachesis-base/inter/idx" + "github.com/Fantom-foundation/lachesis-base/kvdb/batched" + "github.com/Fantom-foundation/lachesis-base/kvdb/pebble" "github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/rlp" "github.com/status-im/keycard-go/hexutils" + "github.com/syndtr/goleveldb/leveldb/opt" "gopkg.in/urfave/cli.v1" "github.com/Fantom-foundation/go-opera/gossip" @@ -114,3 +117,38 @@ func exportTo(w io.Writer, gdb *gossip.Store, from, to idx.Epoch) (err error) { return } + +func exportEvmKeys(ctx *cli.Context) error { + if len(ctx.Args()) < 1 { + utils.Fatalf("This command requires an argument.") + } + + cfg := makeAllConfigs(ctx) + + rawDbs := makeDirectDBsProducer(cfg) + gdb := makeGossipStore(rawDbs, cfg) + defer gdb.Close() + + fn := ctx.Args().First() + + keysDB_, err := pebble.New(fn, 1024*opt.MiB, utils.MakeDatabaseHandles()/2, nil, nil) + if err != nil { + return err + } + keysDB := batched.Wrap(keysDB_) + defer keysDB.Close() + + it := gdb.EvmStore().EvmDb.NewIterator(nil, nil) + // iterate only over MPT data + it = mptAndPreimageIterator{it} + defer it.Release() + + log.Info("Exporting EVM keys", "dir", fn) + for it.Next() { + if err := keysDB.Put(it.Key(), []byte{0}); err != nil { + return err + } + } + log.Info("Exported EVM keys", "dir", fn) + return nil +} diff --git a/cmd/opera/launcher/genesiscmd.go b/cmd/opera/launcher/genesiscmd.go index 39e9844da..211126fc3 100644 --- a/cmd/opera/launcher/genesiscmd.go +++ b/cmd/opera/launcher/genesiscmd.go @@ -9,16 +9,20 @@ import ( "os" "path" "strconv" + "strings" "github.com/Fantom-foundation/lachesis-base/common/bigendian" "github.com/Fantom-foundation/lachesis-base/hash" "github.com/Fantom-foundation/lachesis-base/inter/idx" "github.com/Fantom-foundation/lachesis-base/kvdb" + "github.com/Fantom-foundation/lachesis-base/kvdb/pebble" "github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/rlp" + "github.com/syndtr/goleveldb/leveldb/opt" "gopkg.in/urfave/cli.v1" + "github.com/Fantom-foundation/go-opera/gossip" "github.com/Fantom-foundation/go-opera/gossip/evmstore" "github.com/Fantom-foundation/go-opera/inter/ibr" "github.com/Fantom-foundation/go-opera/inter/ier" @@ -65,6 +69,20 @@ func (it mptAndPreimageIterator) Next() bool { return false } +type excludingIterator struct { + kvdb.Iterator + exclude kvdb.Reader +} + +func (it excludingIterator) Next() bool { + for it.Iterator.Next() { + if ok, _ := it.exclude.Has(it.Key()); !ok { + return true + } + } + return false +} + type unitWriter struct { plain io.WriteSeeker gziper *gzip.Writer @@ -176,6 +194,14 @@ func (w *unitWriter) Write(b []byte) (n int, err error) { return } +func getEpochBlock(epoch idx.Epoch, store *gossip.Store) idx.Block { + bs, _ := store.GetHistoryBlockEpochState(epoch) + if bs == nil { + return 0 + } + return bs.LastBlock.Idx +} + func exportGenesis(ctx *cli.Context) error { if len(ctx.Args()) < 1 { utils.Fatalf("This command requires an argument.") @@ -198,8 +224,35 @@ func exportGenesis(ctx *cli.Context) error { to = idx.Epoch(n) } mode := ctx.String(EvmExportMode.Name) - if mode != "full" && mode != "ext-mpt" && mode != "mpt" && mode != "none" { - return errors.New("--export.evm.mode must be one of {full, ext-mpt, mpt, none}") + if mode != "full" && mode != "ext-mpt" && mode != "mpt" { + return errors.New("--export.evm.mode must be one of {full, ext-mpt, mpt}") + } + + var excludeEvmDB kvdb.Store + if excludeEvmDBPath := ctx.String(EvmExportExclude.Name); len(excludeEvmDBPath) > 0 { + db, err := pebble.New(excludeEvmDBPath, 1024*opt.MiB, utils.MakeDatabaseHandles()/2, nil, nil) + if err != nil { + return err + } + excludeEvmDB = db + } + + sectionsStr := ctx.String(GenesisExportSections.Name) + sections := map[string]string{} + for _, str := range strings.Split(sectionsStr, ",") { + before := len(sections) + if strings.HasPrefix(str, "brs") { + sections["brs"] = str + } else if strings.HasPrefix(str, "ers") { + sections["ers"] = str + } else if strings.HasPrefix(str, "evm") { + sections["evm"] = str + } else { + return fmt.Errorf("unknown section '%s': has to start with either 'brs' or 'ers' or 'evm'", str) + } + if len(sections) == before { + return fmt.Errorf("duplicate section: '%s'", str) + } } cfg := makeAllConfigs(ctx) @@ -243,12 +296,10 @@ func exportGenesis(ctx *cli.Context) error { if to > gdb.GetEpoch() { to = gdb.GetEpoch() } - toBlock := idx.Block(0) - fromBlock := idx.Block(0) - { + if len(sections["ers"]) > 0 { log.Info("Exporting epochs", "from", from, "to", to) writer := newUnitWriter(plain) - err := writer.Start(header, genesisstore.EpochsSection, tmpPath) + err := writer.Start(header, sections["ers"], tmpPath) if err != nil { return err } @@ -266,28 +317,29 @@ func exportGenesis(ctx *cli.Context) error { if err != nil { return err } - if i == from { - fromBlock = er.BlockState.LastBlock.Idx - } - if i == to { - toBlock = er.BlockState.LastBlock.Idx - } } epochsHash, err = writer.Flush() if err != nil { return err } - log.Info("Exported epochs", "hash", epochsHash.String()) + log.Info("Exported epochs") + fmt.Printf("- Epochs hash: %v \n", epochsHash.String()) } - if fromBlock < 1 { - // avoid underflow - fromBlock = 1 - } - { + if len(sections["brs"]) > 0 { + toBlock := getEpochBlock(to, gdb) + fromBlock := getEpochBlock(from, gdb) + if sections["brs"] != "brs" { + // to continue prev section, include blocks of prev epochs too, excluding first blocks of prev epoch (which is last block if prev section) + fromBlock = getEpochBlock(from-1, gdb) + 1 + } + if fromBlock < 1 { + // avoid underflow + fromBlock = 1 + } log.Info("Exporting blocks", "from", fromBlock, "to", toBlock) writer := newUnitWriter(plain) - err := writer.Start(header, genesisstore.BlocksSection, tmpPath) + err := writer.Start(header, sections["brs"], tmpPath) if err != nil { return err } @@ -313,13 +365,14 @@ func exportGenesis(ctx *cli.Context) error { if err != nil { return err } - log.Info("Exported blocks", "hash", blocksHash.String()) + log.Info("Exported blocks") + fmt.Printf("- Blocks hash: %v \n", blocksHash.String()) } - if mode != "none" { - log.Info("Exporting EVM data", "from", fromBlock, "to", toBlock) + if len(sections["evm"]) > 0 { + log.Info("Exporting EVM data") writer := newUnitWriter(plain) - err := writer.Start(header, genesisstore.EvmSection, tmpPath) + err := writer.Start(header, sections["evm"], tmpPath) if err != nil { return err } @@ -331,6 +384,9 @@ func exportGenesis(ctx *cli.Context) error { // iterate only over MPT data and preimages it = mptAndPreimageIterator{it} } + if excludeEvmDB != nil { + it = excludingIterator{it, excludeEvmDB} + } defer it.Release() err = iodb.Write(writer, it) if err != nil { @@ -340,12 +396,9 @@ func exportGenesis(ctx *cli.Context) error { if err != nil { return err } - log.Info("Exported EVM data", "hash", evmHash.String()) + log.Info("Exported EVM data") + fmt.Printf("- EVM hash: %v \n", evmHash.String()) } - fmt.Printf("- Epochs hash: %v \n", epochsHash.String()) - fmt.Printf("- Blocks hash: %v \n", blocksHash.String()) - fmt.Printf("- EVM hash: %v \n", evmHash.String()) - return nil } diff --git a/cmd/opera/launcher/launcher.go b/cmd/opera/launcher/launcher.go index fc598d3c3..20732e7aa 100644 --- a/cmd/opera/launcher/launcher.go +++ b/cmd/opera/launcher/launcher.go @@ -15,6 +15,7 @@ import ( "github.com/ethereum/go-ethereum/ethclient" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/node" + "github.com/ethereum/go-ethereum/p2p/discover/discfilter" "github.com/ethereum/go-ethereum/params" "gopkg.in/urfave/cli.v1" @@ -157,6 +158,7 @@ func initFlags() { utils.IPCPathFlag, RPCGlobalGasCapFlag, RPCGlobalTxFeeCapFlag, + RPCGlobalTimeoutFlag, } metricsFlags = []cli.Flag{ @@ -189,6 +191,7 @@ func initFlags() { // init the CLI app. func init() { + discfilter.Enable() overrideFlags() overrideParams() diff --git a/cmd/opera/launcher/params.go b/cmd/opera/launcher/params.go index 2ca2e43d1..cdfd45744 100644 --- a/cmd/opera/launcher/params.go +++ b/cmd/opera/launcher/params.go @@ -42,52 +42,82 @@ var ( Name: "Mainnet-5577 with pruned MPT", Header: mainnetHeader, Hashes: genesis.Hashes{ - genesisstore.EpochsSection: hash.HexToHash("0x945d8084b4e6e1e78cfe9472fefca3f6ecc7041765dfed24f64e9946252f569a"), - genesisstore.BlocksSection: hash.HexToHash("0xe3ec041f3cca79928aa4abef588b48e96ff3cfa3908b2268af3ac5496c722fec"), - genesisstore.EvmSection: hash.HexToHash("0x12dd52ac21fee5d76b47a64386e73187d5260e448e8044f38c6c73eaa627e4b5"), + genesisstore.EpochsSection(0): hash.HexToHash("0x945d8084b4e6e1e78cfe9472fefca3f6ecc7041765dfed24f64e9946252f569a"), + genesisstore.BlocksSection(0): hash.HexToHash("0xe3ec041f3cca79928aa4abef588b48e96ff3cfa3908b2268af3ac5496c722fec"), + genesisstore.EvmSection(0): hash.HexToHash("0x12dd52ac21fee5d76b47a64386e73187d5260e448e8044f38c6c73eaa627e4b5"), }, }, { Name: "Mainnet-5577 with full MPT", Header: mainnetHeader, Hashes: genesis.Hashes{ - genesisstore.EpochsSection: hash.HexToHash("0x945d8084b4e6e1e78cfe9472fefca3f6ecc7041765dfed24f64e9946252f569a"), - genesisstore.BlocksSection: hash.HexToHash("0xe3ec041f3cca79928aa4abef588b48e96ff3cfa3908b2268af3ac5496c722fec"), - genesisstore.EvmSection: hash.HexToHash("0x54614c9475963ed706f3e654bee0faf9ca21e29c588ad4070fd5b5897c8e0b5d"), + genesisstore.EpochsSection(0): hash.HexToHash("0x945d8084b4e6e1e78cfe9472fefca3f6ecc7041765dfed24f64e9946252f569a"), + genesisstore.BlocksSection(0): hash.HexToHash("0xe3ec041f3cca79928aa4abef588b48e96ff3cfa3908b2268af3ac5496c722fec"), + genesisstore.EvmSection(0): hash.HexToHash("0x54614c9475963ed706f3e654bee0faf9ca21e29c588ad4070fd5b5897c8e0b5d"), }, }, { Name: "Mainnet-109331 without history", Header: mainnetHeader, Hashes: genesis.Hashes{ - genesisstore.EpochsSection: hash.HexToHash("0xf0bef59de85dde7772bf43c62267eb312b0dd2c412ec5f04d96b6ea55178e901"), - genesisstore.BlocksSection: hash.HexToHash("0x80fb348f77f65f0c357f69e29ca123a4c8f1ba60ff445510474be952a1e28d7a"), + genesisstore.EpochsSection(0): hash.HexToHash("0xf0bef59de85dde7772bf43c62267eb312b0dd2c412ec5f04d96b6ea55178e901"), + genesisstore.BlocksSection(0): hash.HexToHash("0x80fb348f77f65f0c357f69e29ca123a4c8f1ba60ff445510474be952a1e28d7a"), }, }, { Name: "Mainnet-109331 without MPT", Header: mainnetHeader, Hashes: genesis.Hashes{ - genesisstore.EpochsSection: hash.HexToHash("0x71cdb819c2745a4853016bbb9690053b70fac679b168cd9a4999bf2a3dfb5578"), - genesisstore.BlocksSection: hash.HexToHash("0xb7394f84b73528423a5b634bfb3cec8ab0a015b387bf6cbe70b378b08e9253bd"), + genesisstore.EpochsSection(0): hash.HexToHash("0x71cdb819c2745a4853016bbb9690053b70fac679b168cd9a4999bf2a3dfb5578"), + genesisstore.BlocksSection(0): hash.HexToHash("0xb7394f84b73528423a5b634bfb3cec8ab0a015b387bf6cbe70b378b08e9253bd"), }, }, { Name: "Mainnet-109331 with pruned MPT", Header: mainnetHeader, Hashes: genesis.Hashes{ - genesisstore.EpochsSection: hash.HexToHash("0x71cdb819c2745a4853016bbb9690053b70fac679b168cd9a4999bf2a3dfb5578"), - genesisstore.BlocksSection: hash.HexToHash("0xb7394f84b73528423a5b634bfb3cec8ab0a015b387bf6cbe70b378b08e9253bd"), - genesisstore.EvmSection: hash.HexToHash("0x617b8c4d74d1598f7d3914ba4c7cd46b7c98d5e044987c6c8d023cc59e849df7"), + genesisstore.EpochsSection(0): hash.HexToHash("0x71cdb819c2745a4853016bbb9690053b70fac679b168cd9a4999bf2a3dfb5578"), + genesisstore.BlocksSection(0): hash.HexToHash("0xb7394f84b73528423a5b634bfb3cec8ab0a015b387bf6cbe70b378b08e9253bd"), + genesisstore.EvmSection(0): hash.HexToHash("0x617b8c4d74d1598f7d3914ba4c7cd46b7c98d5e044987c6c8d023cc59e849df7"), }, }, { Name: "Mainnet-109331 with full MPT", Header: mainnetHeader, Hashes: genesis.Hashes{ - genesisstore.EpochsSection: hash.HexToHash("0x71cdb819c2745a4853016bbb9690053b70fac679b168cd9a4999bf2a3dfb5578"), - genesisstore.BlocksSection: hash.HexToHash("0xb7394f84b73528423a5b634bfb3cec8ab0a015b387bf6cbe70b378b08e9253bd"), - genesisstore.EvmSection: hash.HexToHash("0xef0e1b833321a8de98aaaa1a3946378c78d66ab16b39eb0ad56636d5f7f9f2c5"), + genesisstore.EpochsSection(0): hash.HexToHash("0x71cdb819c2745a4853016bbb9690053b70fac679b168cd9a4999bf2a3dfb5578"), + genesisstore.BlocksSection(0): hash.HexToHash("0xb7394f84b73528423a5b634bfb3cec8ab0a015b387bf6cbe70b378b08e9253bd"), + genesisstore.EvmSection(0): hash.HexToHash("0xef0e1b833321a8de98aaaa1a3946378c78d66ab16b39eb0ad56636d5f7f9f2c5"), + }, + }, + + { + Name: "Mainnet-171200 without history", + Header: mainnetHeader, + Hashes: genesis.Hashes{ + genesisstore.EpochsSection(0): hash.HexToHash("0xb1954a0ac01a35a9ff6026d239e0be659fb4c37c356a94318bbe9201b9b2f3bf"), + genesisstore.BlocksSection(0): hash.HexToHash("0x48ea3ccd2e2ff819386aa6d5ba86b12abb92f2f2e3b405e903f71e3f33f1d258"), + }, + }, + { + Name: "Mainnet-171200 without MPT", + Header: mainnetHeader, + Hashes: genesis.Hashes{ + genesisstore.EpochsSection(0): hash.HexToHash("0x71cdb819c2745a4853016bbb9690053b70fac679b168cd9a4999bf2a3dfb5578"), + genesisstore.BlocksSection(0): hash.HexToHash("0xb7394f84b73528423a5b634bfb3cec8ab0a015b387bf6cbe70b378b08e9253bd"), + genesisstore.EpochsSection(1): hash.HexToHash("0xda430371772ee2fefd1caa342b6a5cb188041a01730f681099dd241bc57a3f77"), + genesisstore.BlocksSection(1): hash.HexToHash("0x14b8b9c3b47cc174ae5c36599cebdef551ad35032ed29c087abb814ac5559619"), + }, + }, + { + Name: "Mainnet-171200 with pruned MPT", + Header: mainnetHeader, + Hashes: genesis.Hashes{ + genesisstore.EpochsSection(0): hash.HexToHash("0x71cdb819c2745a4853016bbb9690053b70fac679b168cd9a4999bf2a3dfb5578"), + genesisstore.BlocksSection(0): hash.HexToHash("0xb7394f84b73528423a5b634bfb3cec8ab0a015b387bf6cbe70b378b08e9253bd"), + genesisstore.EpochsSection(1): hash.HexToHash("0xda430371772ee2fefd1caa342b6a5cb188041a01730f681099dd241bc57a3f77"), + genesisstore.BlocksSection(1): hash.HexToHash("0x14b8b9c3b47cc174ae5c36599cebdef551ad35032ed29c087abb814ac5559619"), + genesisstore.EvmSection(0): hash.HexToHash("0x2a685df416eeca50f4b725117ae88deb35f05e3c51f34e9555ff6ffc62e75d14"), }, }, @@ -95,52 +125,52 @@ var ( Name: "Testnet-2458 with pruned MPT", Header: testnetHeader, Hashes: genesis.Hashes{ - genesisstore.EpochsSection: hash.HexToHash("0x4a5caf86d7f5a31dad91f2cbd44db052c602f515e5319f828adb585a7a6723d6"), - genesisstore.BlocksSection: hash.HexToHash("0x07eadb81c1e2a1b5c444c8c2430c6873380f447de64790b25abe9e7fa6874f65"), - genesisstore.EvmSection: hash.HexToHash("0xa96e006ae17d15e1244c3e7ff4d556e5a3849e70df7a81704787f3273f37c9b1"), + genesisstore.EpochsSection(0): hash.HexToHash("0x4a5caf86d7f5a31dad91f2cbd44db052c602f515e5319f828adb585a7a6723d6"), + genesisstore.BlocksSection(0): hash.HexToHash("0x07eadb81c1e2a1b5c444c8c2430c6873380f447de64790b25abe9e7fa6874f65"), + genesisstore.EvmSection(0): hash.HexToHash("0xa96e006ae17d15e1244c3e7ff4d556e5a3849e70df7a81704787f3273f37c9b1"), }, }, { Name: "Testnet-2458 with full MPT", Header: testnetHeader, Hashes: genesis.Hashes{ - genesisstore.EpochsSection: hash.HexToHash("0x4a5caf86d7f5a31dad91f2cbd44db052c602f515e5319f828adb585a7a6723d6"), - genesisstore.BlocksSection: hash.HexToHash("0x07eadb81c1e2a1b5c444c8c2430c6873380f447de64790b25abe9e7fa6874f65"), - genesisstore.EvmSection: hash.HexToHash("0x3c635232f82cabdfc76405fd03c58134fb00ff9fc0ad080a8a8ae40a7a6fe604"), + genesisstore.EpochsSection(0): hash.HexToHash("0x4a5caf86d7f5a31dad91f2cbd44db052c602f515e5319f828adb585a7a6723d6"), + genesisstore.BlocksSection(0): hash.HexToHash("0x07eadb81c1e2a1b5c444c8c2430c6873380f447de64790b25abe9e7fa6874f65"), + genesisstore.EvmSection(0): hash.HexToHash("0x3c635232f82cabdfc76405fd03c58134fb00ff9fc0ad080a8a8ae40a7a6fe604"), }, }, { Name: "Testnet-6226 without history", Header: testnetHeader, Hashes: genesis.Hashes{ - genesisstore.EpochsSection: hash.HexToHash("0x5527a0c5e45b84c1350ccc77a9644eb797afd1e87887c35526d7622b12881b22"), - genesisstore.BlocksSection: hash.HexToHash("0xf209c98aa5d3473dd71164165152e8802fb95b71d9dbfe394a0addcf81808d5c"), + genesisstore.EpochsSection(0): hash.HexToHash("0x5527a0c5e45b84c1350ccc77a9644eb797afd1e87887c35526d7622b12881b22"), + genesisstore.BlocksSection(0): hash.HexToHash("0xf209c98aa5d3473dd71164165152e8802fb95b71d9dbfe394a0addcf81808d5c"), }, }, { Name: "Testnet-6226 without MPT", Header: testnetHeader, Hashes: genesis.Hashes{ - genesisstore.EpochsSection: hash.HexToHash("0x61040a80f16755b86d67f13880f55c1238d307e2e1c6fc87951eb3bdee0bdff2"), - genesisstore.BlocksSection: hash.HexToHash("0x12010621d8cf4dcd4ea357e98eac61edf9517a6df752cb2d929fca69e56bd8d1"), + genesisstore.EpochsSection(0): hash.HexToHash("0x61040a80f16755b86d67f13880f55c1238d307e2e1c6fc87951eb3bdee0bdff2"), + genesisstore.BlocksSection(0): hash.HexToHash("0x12010621d8cf4dcd4ea357e98eac61edf9517a6df752cb2d929fca69e56bd8d1"), }, }, { Name: "Testnet-6226 with pruned MPT", Header: testnetHeader, Hashes: genesis.Hashes{ - genesisstore.EpochsSection: hash.HexToHash("0x61040a80f16755b86d67f13880f55c1238d307e2e1c6fc87951eb3bdee0bdff2"), - genesisstore.BlocksSection: hash.HexToHash("0x12010621d8cf4dcd4ea357e98eac61edf9517a6df752cb2d929fca69e56bd8d1"), - genesisstore.EvmSection: hash.HexToHash("0x86ec3c7938ab053fc84bbbc8f5259bc81885ec424df91272c553f371464840fc"), + genesisstore.EpochsSection(0): hash.HexToHash("0x61040a80f16755b86d67f13880f55c1238d307e2e1c6fc87951eb3bdee0bdff2"), + genesisstore.BlocksSection(0): hash.HexToHash("0x12010621d8cf4dcd4ea357e98eac61edf9517a6df752cb2d929fca69e56bd8d1"), + genesisstore.EvmSection(0): hash.HexToHash("0x86ec3c7938ab053fc84bbbc8f5259bc81885ec424df91272c553f371464840fc"), }, }, { Name: "Testnet-6226 with full MPT", Header: testnetHeader, Hashes: genesis.Hashes{ - genesisstore.EpochsSection: hash.HexToHash("0x61040a80f16755b86d67f13880f55c1238d307e2e1c6fc87951eb3bdee0bdff2"), - genesisstore.BlocksSection: hash.HexToHash("0x12010621d8cf4dcd4ea357e98eac61edf9517a6df752cb2d929fca69e56bd8d1"), - genesisstore.EvmSection: hash.HexToHash("0x9227c80bf56e4af08dc32cb6043cc43672f2be8177d550ab34a7a9f57f4f104b"), + genesisstore.EpochsSection(0): hash.HexToHash("0x61040a80f16755b86d67f13880f55c1238d307e2e1c6fc87951eb3bdee0bdff2"), + genesisstore.BlocksSection(0): hash.HexToHash("0x12010621d8cf4dcd4ea357e98eac61edf9517a6df752cb2d929fca69e56bd8d1"), + genesisstore.EvmSection(0): hash.HexToHash("0x9227c80bf56e4af08dc32cb6043cc43672f2be8177d550ab34a7a9f57f4f104b"), }, }, } diff --git a/ethapi/api.go b/ethapi/api.go index 7145a8dfa..4cea9a97f 100644 --- a/ethapi/api.go +++ b/ethapi/api.go @@ -52,6 +52,8 @@ import ( "github.com/Fantom-foundation/go-opera/evmcore" "github.com/Fantom-foundation/go-opera/gossip/gasprice" "github.com/Fantom-foundation/go-opera/opera" + "github.com/Fantom-foundation/go-opera/utils/adapters/ethdb2kvdb" + "github.com/Fantom-foundation/go-opera/utils/compactdb" "github.com/Fantom-foundation/go-opera/utils/signers/gsignercache" "github.com/Fantom-foundation/go-opera/utils/signers/internaltx" ) @@ -2376,12 +2378,9 @@ func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) { // ChaindbCompact flattens the entire key-value database into a single level, // removing all unused slots and merging all keys. func (api *PrivateDebugAPI) ChaindbCompact() error { - for b := byte(0); b < 255; b++ { - log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1)) - if err := api.b.ChainDb().Compact([]byte{b}, []byte{b + 1}); err != nil { - log.Error("Database compaction failed", "err", err) - return err - } + if err := compactdb.Compact(ethdb2kvdb.Wrap(api.b.ChainDb()), "EVM"); err != nil { + log.Error("Database compaction failed", "err", err) + return err } return nil } diff --git a/go.mod b/go.mod index f15d92b41..b9a247851 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/Fantom-foundation/go-opera go 1.14 require ( - github.com/Fantom-foundation/lachesis-base v0.0.0-20220904103856-4bb2a8448a22 + github.com/Fantom-foundation/lachesis-base v0.0.0-20221101131534-22299068014e github.com/allegro/bigcache v1.2.1 // indirect github.com/certifi/gocertifi v0.0.0-20191021191039-0944d244cd40 // indirect github.com/cespare/cp v1.1.1 @@ -45,6 +45,6 @@ require ( gopkg.in/urfave/cli.v1 v1.20.0 ) -replace github.com/ethereum/go-ethereum => github.com/Fantom-foundation/go-ethereum v1.10.8-ftm-rc8 +replace github.com/ethereum/go-ethereum => github.com/Fantom-foundation/go-ethereum v1.10.8-ftm-rc9 replace github.com/dvyukov/go-fuzz => github.com/guzenok/go-fuzz v0.0.0-20210103140116-f9104dfb626f diff --git a/go.sum b/go.sum index dca3559a5..b9bb3a984 100644 --- a/go.sum +++ b/go.sum @@ -39,10 +39,10 @@ github.com/CloudyKit/jet v2.1.3-0.20180809161101-62edd43e4f88+incompatible/go.mo github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= github.com/DataDog/zstd v1.4.5 h1:EndNeuB0l9syBZhut0wns3gV1hL8zX8LIu6ZiVHWLIQ= github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= -github.com/Fantom-foundation/go-ethereum v1.10.8-ftm-rc8 h1:A2XvonIgWN+pKdUvlpACCzdtuF7a41HG5ILaOMPi1cY= -github.com/Fantom-foundation/go-ethereum v1.10.8-ftm-rc8/go.mod h1:IeQDjWCNBj/QiWIPosfF6/kRC6pHPNs7W7LfBzjj+P4= -github.com/Fantom-foundation/lachesis-base v0.0.0-20220904103856-4bb2a8448a22 h1:wlB+I8x5mf1a3zlIuOTumy2ye/zglOIGcmTOfJ2bi8s= -github.com/Fantom-foundation/lachesis-base v0.0.0-20220904103856-4bb2a8448a22/go.mod h1:CFMonaK1v/QHwpjLszuycFDgLXNazZqZxciwhKwXDVQ= +github.com/Fantom-foundation/go-ethereum v1.10.8-ftm-rc9 h1:aB5yATSn4a2SmEr717Tq/YBWHcobLnRgAjXuLnqt420= +github.com/Fantom-foundation/go-ethereum v1.10.8-ftm-rc9/go.mod h1:IeQDjWCNBj/QiWIPosfF6/kRC6pHPNs7W7LfBzjj+P4= +github.com/Fantom-foundation/lachesis-base v0.0.0-20221101131534-22299068014e h1:MrNcnBTl5UOn7d1qVb+BfKx+BPZDdfQm1CUDzQkOhEg= +github.com/Fantom-foundation/lachesis-base v0.0.0-20221101131534-22299068014e/go.mod h1:CFMonaK1v/QHwpjLszuycFDgLXNazZqZxciwhKwXDVQ= github.com/Joker/hpp v1.0.0/go.mod h1:8x5n+M1Hp5hC0g8okX3sR3vFQwynaX/UgSOM9MeBKzY= github.com/Joker/jade v1.0.1-0.20190614124447-d475f43051e7/go.mod h1:6E6s8o2AE4KhCrqr6GRJjdC/gNfTdxkIXvuGZZda2VM= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= diff --git a/gossip/c_block_callbacks.go b/gossip/c_block_callbacks.go index 5e92f932f..50d4213c9 100644 --- a/gossip/c_block_callbacks.go +++ b/gossip/c_block_callbacks.go @@ -53,6 +53,7 @@ var ( blockInsertTimer = metrics.GetOrRegisterTimer("chain/inserts", nil) blockExecutionTimer = metrics.GetOrRegisterTimer("chain/execution", nil) blockWriteTimer = metrics.GetOrRegisterTimer("chain/write", nil) + blockAgeGauge = metrics.GetOrRegisterGauge("chain/block/age", nil) ) type ExtendedTxPosition struct { @@ -437,9 +438,11 @@ func consensusCallbackBeginBlockFn( blockInsertTimer.UpdateSince(start) now := time.Now() + blockAge := now.Sub(block.Time.Time()) log.Info("New block", "index", blockCtx.Idx, "id", block.Atropos, "gas_used", evmBlock.GasUsed, "txs", fmt.Sprintf("%d/%d", len(evmBlock.Transactions), len(block.SkippedTxs)), - "age", utils.PrettyDuration(now.Sub(block.Time.Time())), "t", utils.PrettyDuration(now.Sub(start))) + "age", utils.PrettyDuration(blockAge), "t", utils.PrettyDuration(now.Sub(start))) + blockAgeGauge.Update(int64(blockAge.Nanoseconds())) } if confirmedEvents.Len() != 0 { atomic.StoreUint32(blockBusyFlag, 1) diff --git a/gossip/config.go b/gossip/config.go index ef78f0a7d..8f2b2831e 100644 --- a/gossip/config.go +++ b/gossip/config.go @@ -97,6 +97,9 @@ type ( // send-transction variants. The unit is ether. RPCTxFeeCap float64 `toml:",omitempty"` + // RPCTimeout is a global time limit for RPC methods execution. + RPCTimeout time.Duration + // allows only for EIP155 transactions. AllowUnprotectedTxs bool @@ -213,6 +216,7 @@ func DefaultConfig(scale cachescale.Func) Config { RPCGasCap: 50000000, RPCTxFeeCap: 100, // 100 FTM + RPCTimeout: 5 * time.Second, } sessionCfg := cfg.Protocol.DagStreamLeecher.Session cfg.Protocol.DagProcessor.EventsBufferLimit.Num = idx.Event(sessionCfg.ParallelChunksDownload)* diff --git a/gossip/emitter/piecefuncs.go b/gossip/emitter/piecefuncs.go index f1cad0338..31255a8b2 100644 --- a/gossip/emitter/piecefuncs.go +++ b/gossip/emitter/piecefuncs.go @@ -14,12 +14,8 @@ var ( Y: 1.0 * piecefunc.DecimalUnit, }, { - X: 0.34 * piecefunc.DecimalUnit, - Y: 1.05 * piecefunc.DecimalUnit, - }, - { - X: 0.67 * piecefunc.DecimalUnit, - Y: 1.20 * piecefunc.DecimalUnit, + X: 0.78 * piecefunc.DecimalUnit, + Y: 1.1 * piecefunc.DecimalUnit, }, { X: 0.8 * piecefunc.DecimalUnit, @@ -99,11 +95,11 @@ var ( }, { X: 50, - Y: 0.2 * piecefunc.DecimalUnit, + Y: 0.1 * piecefunc.DecimalUnit, }, { X: 100, - Y: 0.7 * piecefunc.DecimalUnit, + Y: 0.4 * piecefunc.DecimalUnit, }, { X: 200, diff --git a/gossip/evmstore/store.go b/gossip/evmstore/store.go index ebf7f8ff1..f27969f49 100644 --- a/gossip/evmstore/store.go +++ b/gossip/evmstore/store.go @@ -16,7 +16,6 @@ import ( "github.com/ethereum/go-ethereum/core/state/snapshot" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/trie" "github.com/syndtr/goleveldb/leveldb/opt" @@ -262,8 +261,8 @@ func (s *Store) Cap() { nodes, imgs = triedb.Size() limit = common.StorageSize(s.cfg.Cache.TrieDirtyLimit) ) + // If we exceeded our memory allowance, flush matured singleton nodes to disk if nodes > limit+ethdb.IdealBatchSize || imgs > 4*1024*1024 { - log.Warn("If we exceeded our memory allowance, flush matured singleton nodes to disk") triedb.Cap(limit) } } diff --git a/gossip/evmstore/utils.go b/gossip/evmstore/utils.go index 5cace1c8c..5b9a65ce3 100644 --- a/gossip/evmstore/utils.go +++ b/gossip/evmstore/utils.go @@ -28,7 +28,7 @@ var ( emptyHash = common.Hash{} ) -func (s *Store) CheckEvm(forEachState func(func(root common.Hash) (found bool, err error))) error { +func (s *Store) CheckEvm(forEachState func(func(root common.Hash) (found bool, err error)), onlyRoots bool) error { log.Info("Checking every node hash") nodeIt := s.table.Evm.NewIterator(nil, nil) defer nodeIt.Release() @@ -68,7 +68,11 @@ func (s *Store) CheckEvm(forEachState func(func(root common.Hash) (found bool, e } } - log.Info("Checking presence of every node") + if onlyRoots { + log.Info("Checking presence of every root") + } else { + log.Info("Checking presence of every node") + } var ( visitedHashes = make([]common.Hash, 0, 1000000) visitedI = 0 @@ -88,7 +92,7 @@ func (s *Store) CheckEvm(forEachState func(func(root common.Hash) (found bool, e forEachState(func(root common.Hash) (found bool, err error) { stateTrie, err := s.EvmState.OpenTrie(root) found = stateTrie != nil && err == nil - if !found { + if !found || onlyRoots { return } diff --git a/gossip/handler.go b/gossip/handler.go index 15a306c2f..3da134aed 100644 --- a/gossip/handler.go +++ b/gossip/handler.go @@ -5,6 +5,7 @@ import ( "fmt" "math" "math/rand" + "strings" "sync" "time" @@ -19,6 +20,7 @@ import ( notify "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/p2p" + "github.com/ethereum/go-ethereum/p2p/discover/discfilter" "github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/trie" @@ -281,7 +283,7 @@ func newHandler( }, PeerEpoch: func(peer string) idx.Epoch { p := h.peers.Peer(peer) - if p == nil { + if p == nil || p.Useless() { return 0 } return p.progress.Epoch @@ -317,7 +319,7 @@ func newHandler( }, PeerBlock: func(peer string) idx.Block { p := h.peers.Peer(peer) - if p == nil { + if p == nil || p.Useless() { return 0 } return p.progress.LastBlockIdx @@ -358,7 +360,7 @@ func newHandler( }, PeerBlock: func(peer string) idx.Block { p := h.peers.Peer(peer) - if p == nil { + if p == nil || p.Useless() { return 0 } return p.progress.LastBlockIdx @@ -396,7 +398,7 @@ func newHandler( }, PeerEpoch: func(peer string) idx.Epoch { p := h.peers.Peer(peer) - if p == nil { + if p == nil || p.Useless() { return 0 } return p.progress.Epoch @@ -780,6 +782,22 @@ func (h *handler) handle(p *peer) error { p.Log().Error("Snapshot extension barrier failed", "err", err) return err } + useless := discfilter.Banned(p.Node().ID(), p.Node().Record()) + if !useless && (!eligibleForSnap(p.Peer) || !strings.Contains(strings.ToLower(p.Name()), "opera")) { + useless = true + discfilter.Ban(p.ID()) + } + if !p.Peer.Info().Network.Trusted && useless && h.peers.UselessNum() >= h.maxPeers/10 { + // don't allow more than 10% of useless peers + return p2p.DiscTooManyPeers + } + if !p.Peer.Info().Network.Trusted && useless { + if h.peers.UselessNum() >= h.maxPeers/10 { + // don't allow more than 10% of useless peers + return p2p.DiscTooManyPeers + } + p.SetUseless() + } h.peerWG.Add(1) defer h.peerWG.Done() @@ -791,6 +809,9 @@ func (h *handler) handle(p *peer) error { ) if err := p.Handshake(h.NetworkID, myProgress, common.Hash(genesis)); err != nil { p.Log().Debug("Handshake failed", "err", err) + if !useless { + discfilter.Ban(p.ID()) + } return err } @@ -1349,9 +1370,16 @@ func (h *handler) BroadcastEvent(event *inter.EventPayload, passed time.Duration fullRecipients := h.decideBroadcastAggressiveness(event.Size(), passed, len(peers)) - // Broadcast of full event to a subset of peers - fullBroadcast := peers[:fullRecipients] - hashBroadcast := peers[fullRecipients:] + // Exclude low quality peers from fullBroadcast + var fullBroadcast = make([]*peer, 0, fullRecipients) + var hashBroadcast = make([]*peer, 0, len(peers)) + for _, p := range peers { + if !p.Useless() && len(fullBroadcast) < fullRecipients { + fullBroadcast = append(fullBroadcast, p) + } else { + hashBroadcast = append(hashBroadcast, p) + } + } for _, peer := range fullBroadcast { peer.AsyncSendEvents(inter.EventPayloads{event}, peer.queue) } diff --git a/gossip/peer.go b/gossip/peer.go index f615732e5..95139b6ee 100644 --- a/gossip/peer.go +++ b/gossip/peer.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "sync" + "sync/atomic" "time" "github.com/Fantom-foundation/lachesis-base/hash" @@ -67,9 +68,19 @@ type peer struct { syncDrop *time.Timer // Connection dropper if `eth` sync progress isn't validated in time snapWait chan struct{} // Notification channel for snap connections + useless uint32 + sync.RWMutex } +func (p *peer) Useless() bool { + return atomic.LoadUint32(&p.useless) != 0 +} + +func (p *peer) SetUseless() { + atomic.StoreUint32(&p.useless, 1) +} + func (p *peer) SetProgress(x PeerProgress) { p.Lock() defer p.Unlock() diff --git a/gossip/peerset.go b/gossip/peerset.go index 75313d8ce..2c6bc0094 100644 --- a/gossip/peerset.go +++ b/gossip/peerset.go @@ -179,6 +179,19 @@ func (ps *peerSet) Peer(id string) *peer { return ps.peers[id] } +func (ps *peerSet) UselessNum() int { + ps.lock.RLock() + defer ps.lock.RUnlock() + + num := 0 + for _, p := range ps.peers { + if p.Useless() { + num++ + } + } + return num +} + // PeersWithoutEvent retrieves a list of peers that do not have a given event in // their set of known hashes so it might be propagated to them. func (ps *peerSet) PeersWithoutEvent(e hash.Event) []*peer { diff --git a/gossip/service.go b/gossip/service.go index 8016687fe..b4b49ea0a 100644 --- a/gossip/service.go +++ b/gossip/service.go @@ -269,6 +269,8 @@ func newService(config Config, store *Store, blockProc BlockProc, engine lachesi return nil, err } + rpc.SetExecutionTimeLimit(config.RPCTimeout) + // create API backend svc.EthAPI = &EthAPIBackend{false, svc, stateReader, txSigner, config.AllowUnprotectedTxs} diff --git a/integration/assembly.go b/integration/assembly.go index e6704b3d7..e0994548c 100644 --- a/integration/assembly.go +++ b/integration/assembly.go @@ -10,6 +10,7 @@ import ( "github.com/Fantom-foundation/lachesis-base/hash" "github.com/Fantom-foundation/lachesis-base/inter/idx" "github.com/Fantom-foundation/lachesis-base/kvdb" + "github.com/Fantom-foundation/lachesis-base/kvdb/multidb" "github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/cmd/utils" @@ -21,6 +22,7 @@ import ( "github.com/Fantom-foundation/go-opera/gossip" "github.com/Fantom-foundation/go-opera/opera/genesis" "github.com/Fantom-foundation/go-opera/utils/adapters/vecmt2dagidx" + "github.com/Fantom-foundation/go-opera/utils/compactdb" "github.com/Fantom-foundation/go-opera/vecmt" ) @@ -143,6 +145,16 @@ func CheckStateInitialized(chaindataDir string, cfg DBsConfig) error { return dbs.Close() } +func compactDB(typ multidb.TypeName, name string, producer kvdb.DBProducer) error { + humanName := path.Join(string(typ), name) + db, err := producer.OpenDB(name) + defer db.Close() + if err != nil { + return err + } + return compactdb.Compact(db, humanName) +} + func makeEngine(chaindataDir string, g *genesis.Genesis, genesisProc bool, cfg Configs) (*abft.Lachesis, *vecmt.Index, *gossip.Store, *abft.Store, gossip.BlockProc, func() error, error) { // Genesis processing if genesisProc { @@ -164,6 +176,17 @@ func makeEngine(chaindataDir string, g *genesis.Genesis, genesisProc bool, cfg C _ = dbs.Close() setGenesisComplete(chaindataDir) } + // Compact DBs after first launch + if genesisProc { + genesisProducers, _ := SupportedDBs(chaindataDir, cfg.DBs.GenesisCache) + for typ, p := range genesisProducers { + for _, name := range p.Names() { + if err := compactDB(typ, name, p); err != nil { + return nil, nil, nil, nil, gossip.BlockProc{}, nil, err + } + } + } + } // Check DBs are synced { err := CheckStateInitialized(chaindataDir, cfg.DBs) diff --git a/integration/legacy_migrate.go b/integration/legacy_migrate.go index 7c5880c6c..5c7633eb0 100644 --- a/integration/legacy_migrate.go +++ b/integration/legacy_migrate.go @@ -17,6 +17,8 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/log" "github.com/syndtr/goleveldb/leveldb/opt" + + "github.com/Fantom-foundation/go-opera/utils/compactdb" ) func lastKey(db kvdb.Store) []byte { @@ -111,6 +113,10 @@ func transform(m transformTask) error { } keys = keys[:0] } + // compact the new DB + if err := compactdb.Compact(dst, m.name); err != nil { + return err + } return nil } diff --git a/integration/makegenesis/genesis.go b/integration/makegenesis/genesis.go index ecc94cc1c..240af2aeb 100644 --- a/integration/makegenesis/genesis.go +++ b/integration/makegenesis/genesis.go @@ -233,19 +233,19 @@ func (f *memFile) Close() error { func (b *GenesisBuilder) Build(head genesis.Header) *genesisstore.Store { return genesisstore.NewStore(func(name string) (io.Reader, error) { buf := &memFile{bytes.NewBuffer(nil)} - if name == genesisstore.BlocksSection { + if name == genesisstore.BlocksSection(0) { for i := len(b.blocks) - 1; i >= 0; i-- { _ = rlp.Encode(buf, b.blocks[i]) } return buf, nil } - if name == genesisstore.EpochsSection { + if name == genesisstore.EpochsSection(0) { for i := len(b.epochs) - 1; i >= 0; i-- { _ = rlp.Encode(buf, b.epochs[i]) } return buf, nil } - if name == genesisstore.EvmSection { + if name == genesisstore.EvmSection(0) { it := b.tmpEvmStore.EvmDb.NewIterator(nil, nil) defer it.Release() _ = iodb.Write(buf, it) diff --git a/integration/metric.go b/integration/metric.go index f01cff8e8..49d153193 100644 --- a/integration/metric.go +++ b/integration/metric.go @@ -83,7 +83,7 @@ func (ds *StoreWithMetrics) meter(refresh time.Duration) { continue } var nDiskSize int64 - if n, err := fmt.Sscanf(diskSize, "Size(B):%d", &nDiskSize); n != 1 || err != nil { + if n, err := fmt.Sscanf(diskSize, "%d", &nDiskSize); n != 1 || err != nil { ds.log.Error("Bad syntax of disk size entry", "size", diskSize) merr = err continue @@ -146,16 +146,16 @@ func (db *DBProducerWithMetrics) OpenDB(name string) (kvdb.Store, error) { return nil, err } dm := WrapStoreWithMetrics(ds) - // disk size gauge should be meter separatly for each db name; otherwise, - // the last db siae metric will overwrite all the previoius one - dm.diskSizeGauge = metrics.GetOrRegisterGauge("opera/chaindata/"+name+"/disk/size", nil) - if strings.HasPrefix(name, "gossip-") || strings.HasPrefix(name, "lachesis-") { + // disk size gauge should be metered separately for each db name; otherwise, + // the last db size metric will overwrite all the previous ones + dm.diskSizeGauge = metrics.GetOrRegisterGauge("opera/chaindata/"+strings.ReplaceAll(name, "-", "_")+"/disk/size", nil) + if strings.HasPrefix(name, "gossip-") || strings.HasPrefix(name, "lachesis-") || strings.HasPrefix(name, "epoch-") { name = "epochs" } logger := log.New("database", name) dm.log = logger - dm.diskReadMeter = metrics.GetOrRegisterMeter("opera/chaindata/"+name+"/disk/read", nil) - dm.diskWriteMeter = metrics.GetOrRegisterMeter("opera/chaindata/"+name+"/disk/write", nil) + dm.diskReadMeter = metrics.GetOrRegisterMeter("opera/chaindata/"+strings.ReplaceAll(name, "-", "_")+"/disk/read", nil) + dm.diskWriteMeter = metrics.GetOrRegisterMeter("opera/chaindata/"+strings.ReplaceAll(name, "-", "_")+"/disk/write", nil) // Start up the metrics gathering and return go dm.meter(metricsGatheringInterval) diff --git a/opera/genesisstore/disk.go b/opera/genesisstore/disk.go index e9116ceda..4919eb1e3 100644 --- a/opera/genesisstore/disk.go +++ b/opera/genesisstore/disk.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "io" + "strings" "time" "github.com/Fantom-foundation/lachesis-base/common/bigendian" @@ -133,14 +134,19 @@ func OpenGenesisStore(rawReader ReadAtSeekerCloser) (*Store, genesis.Hashes, err // wrap with a logger // human-readable name name := unit.UnitName - if unit.UnitName == BlocksSection { - name = "blocks" + scanfName := strings.ReplaceAll(name, "-", "") + if scanfName[len(scanfName)-1] < '0' || scanfName[len(scanfName)-1] > '9' { + scanfName += "0" } - if unit.UnitName == EpochsSection { - name = "epochs" + var part int + if _, err := fmt.Sscanf(scanfName, "brs%d", &part); err == nil { + name = fmt.Sprintf("blocks unit %d", part) } - if unit.UnitName == EvmSection { - name = "EVM data" + if _, err := fmt.Sscanf(scanfName, "ers%d", &part); err == nil { + name = fmt.Sprintf("epochs unit %d", part) + } + if _, err := fmt.Sscanf(scanfName, "evm%d", &part); err == nil { + name = fmt.Sprintf("EVM unit %d", part) } loggedReader := filelog.Wrap(gzipReader, name, uncompressedSize, time.Minute) diff --git a/opera/genesisstore/store.go b/opera/genesisstore/store.go index 8653c0ea9..2d41c7d06 100644 --- a/opera/genesisstore/store.go +++ b/opera/genesisstore/store.go @@ -7,11 +7,17 @@ import ( "github.com/Fantom-foundation/go-opera/opera/genesis" ) -const ( - BlocksSection = "brs" - EpochsSection = "ers" - EvmSection = "evm" -) +func BlocksSection(i int) string { + return getSectionName("brs", i) +} + +func EpochsSection(i int) string { + return getSectionName("ers", i) +} + +func EvmSection(i int) string { + return getSectionName("evm", i) +} type FilesMap func(string) (io.Reader, error) diff --git a/opera/genesisstore/store_genesis.go b/opera/genesisstore/store_genesis.go index aa78bc7a1..2ca219745 100644 --- a/opera/genesisstore/store_genesis.go +++ b/opera/genesisstore/store_genesis.go @@ -38,7 +38,7 @@ func getSectionName(base string, i int) string { if i == 0 { return base } - return fmt.Sprintf("%s-%d", BlocksSection, i) + return fmt.Sprintf("%s-%d", base, i) } func (s Store) Header() genesis.Header { @@ -50,10 +50,10 @@ func (s *Store) Blocks() genesis.Blocks { } func (s Blocks) ForEach(fn func(ibr.LlrIdxFullBlockRecord) bool) { - for i := 0; ; i++ { - f, err := s.fMap(getSectionName(BlocksSection, i)) + for i := 1000; i >= 0; i-- { + f, err := s.fMap(BlocksSection(i)) if err != nil { - return + continue } stream := rlp.NewStream(f, 0) for { @@ -77,10 +77,10 @@ func (s *Store) Epochs() genesis.Epochs { } func (s Epochs) ForEach(fn func(ier.LlrIdxFullEpochRecord) bool) { - for i := 0; ; i++ { - f, err := s.fMap(getSectionName(EpochsSection, i)) + for i := 1000; i >= 0; i-- { + f, err := s.fMap(EpochsSection(i)) if err != nil { - return + continue } stream := rlp.NewStream(f, 0) for { @@ -104,10 +104,10 @@ func (s *Store) RawEvmItems() genesis.EvmItems { } func (s RawEvmItems) ForEach(fn func(key, value []byte) bool) { - for i := 0; ; i++ { - f, err := s.fMap(getSectionName(EvmSection, i)) + for i := 1000; i >= 0; i-- { + f, err := s.fMap(EvmSection(i)) if err != nil { - return + continue } it := iodb.NewIterator(f) for it.Next() { diff --git a/topicsdb/search_parallel.go b/topicsdb/search_parallel.go index ef95be2ac..ab40ef997 100644 --- a/topicsdb/search_parallel.go +++ b/topicsdb/search_parallel.go @@ -37,6 +37,7 @@ func (tt *Index) searchParallel(ctx context.Context, pattern [][]common.Hash, bl return } if rec.topicsCount < uint8(len(pattern)-1) { + gonext = true return } diff --git a/topicsdb/topicsdb_test.go b/topicsdb/topicsdb_test.go index b59d70ad7..f4846e548 100644 --- a/topicsdb/topicsdb_test.go +++ b/topicsdb/topicsdb_test.go @@ -196,6 +196,88 @@ func TestIndexSearchMultyVariants(t *testing.T) { } } +func TestIndexSearchShortCircuits(t *testing.T) { + logger.SetTestMode(t) + var ( + hash1 = common.BytesToHash([]byte("topic1")) + hash2 = common.BytesToHash([]byte("topic2")) + hash3 = common.BytesToHash([]byte("topic3")) + hash4 = common.BytesToHash([]byte("topic4")) + addr1 = randAddress() + addr2 = randAddress() + ) + testdata := []*types.Log{{ + BlockNumber: 1, + Address: addr1, + Topics: []common.Hash{hash1, hash2}, + }, { + BlockNumber: 3, + Address: addr1, + Topics: []common.Hash{hash1, hash2, hash3}, + }, { + BlockNumber: 998, + Address: addr2, + Topics: []common.Hash{hash1, hash2, hash4}, + }, { + BlockNumber: 999, + Address: addr1, + Topics: []common.Hash{hash1, hash2, hash4}, + }, + } + + index := New(memorydb.NewProducer("")) + + for _, l := range testdata { + err := index.Push(l) + require.NoError(t, err) + } + + for dsc, method := range map[string]func(context.Context, idx.Block, idx.Block, [][]common.Hash) ([]*types.Log, error){ + "sync": index.FindInBlocks, + "async": index.FindInBlocksAsync, + } { + t.Run(dsc, func(t *testing.T) { + + t.Run("topics count 1", func(t *testing.T) { + require := require.New(t) + got, err := method(nil, 0, 1000, [][]common.Hash{ + {addr1.Hash()}, + {}, + {}, + {hash3}, + }) + require.NoError(err) + require.Equal(1, len(got)) + }) + + t.Run("topics count 2", func(t *testing.T) { + require := require.New(t) + got, err := method(nil, 0, 1000, [][]common.Hash{ + {addr1.Hash()}, + {}, + {}, + {hash3, hash4}, + }) + require.NoError(err) + require.Equal(2, len(got)) + }) + + t.Run("block range", func(t *testing.T) { + require := require.New(t) + got, err := method(nil, 3, 998, [][]common.Hash{ + {addr1.Hash()}, + {}, + {}, + {hash3, hash4}, + }) + require.NoError(err) + require.Equal(1, len(got)) + }) + + }) + } +} + func TestIndexSearchSingleVariant(t *testing.T) { logger.SetTestMode(t) diff --git a/utils/compactdb/compactdb.go b/utils/compactdb/compactdb.go new file mode 100644 index 000000000..b073e6a51 --- /dev/null +++ b/utils/compactdb/compactdb.go @@ -0,0 +1,105 @@ +package compactdb + +import ( + "bytes" + "math/big" + "time" + + "github.com/Fantom-foundation/lachesis-base/kvdb" + "github.com/Fantom-foundation/lachesis-base/kvdb/table" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" + "github.com/status-im/keycard-go/hexutils" +) + +func isEmptyDB(db kvdb.Iteratee) bool { + it := db.NewIterator(nil, nil) + defer it.Release() + return !it.Next() +} + +func firstKey(db kvdb.Store) []byte { + it := db.NewIterator(nil, nil) + defer it.Release() + if !it.Next() { + return nil + } + return it.Key() +} + +func lastKey(db kvdb.Store) []byte { + var start []byte + for { + for b := 0xff; b >= 0; b-- { + if !isEmptyDB(table.New(db, append(start, byte(b)))) { + start = append(start, byte(b)) + break + } + if b == 0 { + return start + } + } + } +} + +func addToPrefix(prefix *big.Int, diff *big.Int, size int) []byte { + endBn := new(big.Int).Set(prefix) + endBn.Add(endBn, diff) + if len(endBn.Bytes()) > size { + // overflow + return bytes.Repeat([]byte{0xff}, size) + } + end := endBn.Bytes() + res := make([]byte, size-len(end), size) + return append(res, end...) +} + +func Compact(unprefixedDB kvdb.Store, loggingName string) error { + lastLog := time.Time{} + compact := func(db kvdb.Store, b int, start, end []byte) error { + if len(loggingName) != 0 && time.Since(lastLog) > time.Second*16 { + log.Info("Compacting DB", "name", loggingName, "until", hexutils.BytesToHex(append([]byte{byte(b)}, end...))) + lastLog = time.Now() + } + return db.Compact(start, end) + } + + for b := 0; b < 256; b++ { + prefixed := table.New(unprefixedDB, []byte{byte(b)}) + first := firstKey(prefixed) + if first == nil { + continue + } + last := lastKey(prefixed) + if last == nil { + continue + } + keySize := len(last) + if keySize < len(first) { + keySize = len(first) + } + first = common.RightPadBytes(first, keySize-len(first)) + last = common.RightPadBytes(last, keySize-len(last)) + firstBn := new(big.Int).SetBytes(first) + lastBn := new(big.Int).SetBytes(last) + diff := new(big.Int).Sub(lastBn, firstBn) + if diff.Cmp(big.NewInt(10000)) < 0 { + // short circuit if too few keys + err := compact(prefixed, b, nil, nil) + if err != nil { + return err + } + continue + } + var prev []byte + for i := 32; i >= 1; i-- { + until := addToPrefix(firstBn, new(big.Int).Div(diff, big.NewInt(int64(i))), keySize) + err := compact(prefixed, b, prev, until) + if err != nil { + return err + } + prev = common.CopyBytes(until) + } + } + return nil +} diff --git a/version/version.go b/version/version.go index 54894e228..861f2efe8 100644 --- a/version/version.go +++ b/version/version.go @@ -11,7 +11,7 @@ func init() { params.VersionMajor = 1 // Major version component of the current release params.VersionMinor = 1 // Minor version component of the current release params.VersionPatch = 2 // Patch version component of the current release - params.VersionMeta = "txtracing-rc.2" // Version metadata to append to the version string + params.VersionMeta = "txtracing-rc.3" // Version metadata to append to the version string } func BigToString(b *big.Int) string {