From e13986ef66ba6486ace533f5310500375a68cc34 Mon Sep 17 00:00:00 2001 From: KeefeL <90749943+KeefeL@users.noreply.github.com> Date: Thu, 6 Apr 2023 10:37:07 +0800 Subject: [PATCH 1/2] update license (#38) Co-authored-by: Keefe Liu --- COPYING | 661 +++++++++++++++++++++++++++++++++++++++++++++++++ COPYING.LESSER | 165 ------------ README.md | 4 +- 3 files changed, 663 insertions(+), 167 deletions(-) create mode 100644 COPYING delete mode 100644 COPYING.LESSER diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..bae94e1 --- /dev/null +++ b/COPYING @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 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 Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are 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. + + 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. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + 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 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 work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + 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 AGPL, see +. \ No newline at end of file diff --git a/COPYING.LESSER b/COPYING.LESSER deleted file mode 100644 index 65c5ca8..0000000 --- a/COPYING.LESSER +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER 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. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser 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 -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/README.md b/README.md index 0be2d60..ffe887c 100644 --- a/README.md +++ b/README.md @@ -196,5 +196,5 @@ Please make sure your contributions adhere to our coding guidelines: ## License The repo is licensed under the -[GNU Lesser General Public License v3.0](https://www.gnu.org/licenses/lgpl-3.0.en.html), -also included in our repository in the `COPYING.LESSER` file. \ No newline at end of file +[GNU Affero General Public License v3.0](https://www.gnu.org/licenses/agpl-3.0.en.html), also +included in our repository in the `COPYING` file. \ No newline at end of file From 4fd89d012e11921ce295e51979421e0d0368b72a Mon Sep 17 00:00:00 2001 From: Alexxxxxx <118710506+alexgao001@users.noreply.github.com> Date: Fri, 7 Apr 2023 13:30:32 +0800 Subject: [PATCH 2/2] fix: a few issues for inturn relayer delivery and rate limit (#37) add missing index and fix db transaction rate limit for votepool interaction inturn relayer seq and nonce storage from db to in-memory --- README.md | 16 ++- app/app.go | 32 +++++- assembler/bsc_assembler.go | 81 +++++++-------- assembler/greenfield_assembler.go | 125 +++++++++++++----------- common/const.go | 8 +- config/config.go | 113 ++++++++++----------- config/config.json | 22 +++-- config/local/config_local_0.json | 26 ++--- config/local/config_local_1.json | 26 ++--- config/local/config_local_2.json | 28 +++--- db/dao/bsc_dao.go | 11 ++- db/dao/dao_manager.go | 4 +- db/dao/greenfield_dao.go | 19 ++-- db/dao/sequence_dao.go | 47 --------- db/dao/vote_dao.go | 16 +++ db/model/bsc_model.go | 2 +- db/model/sequence_model.go | 24 ----- db/model/votepool_model.go | 6 +- executor/bsc_executor.go | 2 +- executor/greenfield_executor.go | 8 +- go.mod | 4 +- go.sum | 8 +- integrationtest/config/config_test.json | 26 ++--- listener/greenfield_listener.go | 42 +------- relayer/greenfield_relayer.go | 5 + types/types.go | 10 ++ vote/bsc_vote_processor.go | 26 ++--- vote/greenfield_vote_processor.go | 107 ++++++++++++++------ 28 files changed, 441 insertions(+), 403 deletions(-) delete mode 100644 db/dao/sequence_dao.go delete mode 100644 db/model/sequence_model.go diff --git a/README.md b/README.md index ffe887c..a9cf03c 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ Go version above 1.19 "key_type": "local_private_key", "aws_region": "", "aws_secret_name": "", + "aws_bls_secret_name": "", "rpc_addrs": [ "http://127.0.0.1:26750", "http://127.0.0.1:26751", @@ -50,10 +51,12 @@ Go version above 1.19 ], "private_key": "your_private_key", "bls_private_key": "your_private_key", - "chain_id": 1, // greenfield oracle module defines this + "chain_id": 18, // greenfield oracle module defines this "start_height": 1, + "number_of_blocks_for_finality": 0, "monitor_channel_list": [1,2,3], - "gas_limit": 210000, + "gas_limit": 30000, + "fee_amount": 150000000000000, "chain_id_string": "greenfield_9000-121" }, "bsc_config": { @@ -103,7 +106,14 @@ Go version above 1.19 ``` "db_config": { "dialect": "mysql", - "db_path": "root:pass@tcp(127.0.0.1:3306)/greenfield-relayer?charset=utf8&parseTime=True&loc=Local" + "key_type": "local_private_key", + "aws_region": "", + "aws_secret_name": "", + "password": "pass", + "username": "root", + "url": "/local-greenfield-relayer1?charset=utf8&parseTime=True&loc=Local", + "max_idle_conns": 10, + "max_open_conns": 100 } ``` diff --git a/app/app.go b/app/app.go index 209de56..b8787b6 100644 --- a/app/app.go +++ b/app/app.go @@ -3,10 +3,14 @@ package app import ( "encoding/json" "fmt" + "log" + "os" + "time" "github.com/spf13/viper" "gorm.io/driver/mysql" "gorm.io/gorm" + "gorm.io/gorm/logger" "github.com/bnb-chain/greenfield-relayer/assembler" "github.com/bnb-chain/greenfield-relayer/config" @@ -35,20 +39,38 @@ func NewApp(cfg *config.Config) *App { url := cfg.DBConfig.Url dbPath := fmt.Sprintf("%s:%s@%s", username, password, url) - db, err := gorm.Open(mysql.Open(dbPath), &gorm.Config{}) + newLogger := logger.New( + log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer + logger.Config{ + SlowThreshold: time.Second, // Slow SQL threshold + LogLevel: logger.Silent, // Log level + IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger + Colorful: true, // Disable color + }, + ) + + db, err := gorm.Open(mysql.Open(dbPath), &gorm.Config{ + Logger: newLogger, + }) if err != nil { panic(fmt.Sprintf("open db error, err=%s", err.Error())) } + dbConfig, err := db.DB() + if err != nil { + panic(err) + } + + dbConfig.SetMaxIdleConns(cfg.DBConfig.MaxIdleConns) + dbConfig.SetMaxOpenConns(cfg.DBConfig.MaxOpenConns) + model.InitBSCTables(db) model.InitGreenfieldTables(db) model.InitVoteTables(db) - model.InitSequenceTable(db) greenfieldDao := dao.NewGreenfieldDao(db) bscDao := dao.NewBSCDao(db) voteDao := dao.NewVoteDao(db) - seqDao := dao.NewSequenceDao(db) - daoManager := dao.NewDaoManager(greenfieldDao, bscDao, voteDao, seqDao) + daoManager := dao.NewDaoManager(greenfieldDao, bscDao, voteDao) greenfieldExecutor := executor.NewGreenfieldExecutor(cfg) bscExecutor := executor.NewBSCExecutor(cfg) @@ -66,7 +88,7 @@ func NewApp(cfg *config.Config) *App { bscVoteProcessor := vote.NewBSCVoteProcessor(cfg, daoManager, signer, bscExecutor) // listeners - greenfieldListener := listener.NewGreenfieldListener(cfg, greenfieldExecutor, bscExecutor, greenfieldVoteProcessor, daoManager, metricService) + greenfieldListener := listener.NewGreenfieldListener(cfg, greenfieldExecutor, bscExecutor, daoManager, metricService) bscListener := listener.NewBSCListener(cfg, bscExecutor, greenfieldExecutor, daoManager, metricService) // assemblers diff --git a/assembler/bsc_assembler.go b/assembler/bsc_assembler.go index 97d8d0e..10bd8fb 100644 --- a/assembler/bsc_assembler.go +++ b/assembler/bsc_assembler.go @@ -19,23 +19,25 @@ import ( ) type BSCAssembler struct { - config *config.Config - greenfieldExecutor *executor.GreenfieldExecutor - bscExecutor *executor.BSCExecutor - daoManager *dao.DaoManager - blsPubKey []byte - hasRetrievedSequence bool - metricService *metric.MetricService + config *config.Config + greenfieldExecutor *executor.GreenfieldExecutor + bscExecutor *executor.BSCExecutor + daoManager *dao.DaoManager + blsPubKey []byte + inturnRelayerSequenceStatus *types.SequenceStatus + relayerNonce uint64 + metricService *metric.MetricService } func NewBSCAssembler(cfg *config.Config, executor *executor.BSCExecutor, dao *dao.DaoManager, greenfieldExecutor *executor.GreenfieldExecutor, ms *metric.MetricService) *BSCAssembler { return &BSCAssembler{ - config: cfg, - bscExecutor: executor, - daoManager: dao, - greenfieldExecutor: greenfieldExecutor, - blsPubKey: greenfieldExecutor.BlsPubKey, - metricService: ms, + config: cfg, + bscExecutor: executor, + daoManager: dao, + greenfieldExecutor: greenfieldExecutor, + blsPubKey: greenfieldExecutor.BlsPubKey, + inturnRelayerSequenceStatus: &types.SequenceStatus{}, + metricService: ms, } } @@ -63,17 +65,12 @@ func (a *BSCAssembler) process(channelId types.ChannelId) error { return err } isInturnRelyer := bytes.Equal(a.blsPubKey, inturnRelayerPubkey) + a.metricService.SetGnfdInturnRelayerMetrics(isInturnRelyer, inturnRelayer.RelayInterval.Start, inturnRelayer.RelayInterval.End) - var startSequence uint64 + var startSeq uint64 if isInturnRelyer { - seq, err := a.daoManager.SequenceDao.GetByChannelId(uint8(channelId)) - if err != nil { - return err - } - startSequence = uint64(seq.Sequence) - - if !a.hasRetrievedSequence { + if !a.inturnRelayerSequenceStatus.HasRetrieved { // in-turn relayer get the start sequence from chain first time, it starts to relay after the sequence gets updated now := time.Now().Unix() timeDiff := now - int64(inturnRelayer.RelayInterval.Start) @@ -84,28 +81,38 @@ func (a *BSCAssembler) process(channelId types.ChannelId) error { } return nil } - startSequence, err = a.bscExecutor.GetNextDeliveryOracleSequenceWithRetry() + inTurnRelayerStartSeq, err := a.bscExecutor.GetNextDeliveryOracleSequenceWithRetry() if err != nil { return err } - if err = a.daoManager.SequenceDao.Upsert(uint8(channelId), startSequence); err != nil { + nonce, err := a.greenfieldExecutor.GetNonce() + if err != nil { return err } + a.relayerNonce = nonce + a.inturnRelayerSequenceStatus.HasRetrieved = true + a.inturnRelayerSequenceStatus.NextDeliverySeq = inTurnRelayerStartSeq } - a.metricService.SetNextSequenceForChannelFromDB(uint8(channelId), startSequence) + startSeq = a.inturnRelayerSequenceStatus.NextDeliverySeq + a.metricService.SetNextSequenceForChannelFromDB(uint8(channelId), startSeq) seqFromChain, err := a.bscExecutor.GetNextDeliveryOracleSequenceWithRetry() if err != nil { return err } a.metricService.SetNextSequenceForChannelFromChain(uint8(channelId), seqFromChain) } else { - a.hasRetrievedSequence = false + a.inturnRelayerSequenceStatus.HasRetrieved = false // non-inturn relayer retries every 10 second, gets the sequence from chain time.Sleep(time.Duration(a.config.RelayConfig.GreenfieldSequenceUpdateLatency) * time.Second) - startSequence, err = a.bscExecutor.GetNextDeliveryOracleSequenceWithRetry() + startSeq, err = a.bscExecutor.GetNextDeliveryOracleSequenceWithRetry() if err != nil { return err } + startNonce, err := a.greenfieldExecutor.GetNonce() + if err != nil { + return err + } + a.relayerNonce = startNonce } endSequence, err := a.daoManager.BSCDao.GetLatestOracleSequenceByStatus(db.AllVoted) if err != nil { @@ -114,12 +121,9 @@ func (a *BSCAssembler) process(channelId types.ChannelId) error { if endSequence == -1 { return nil } - nonce, err := a.greenfieldExecutor.GetNonce() - if err != nil { - return err - } + logging.Logger.Debugf("start seq and end enq are %d and %d", startSeq, endSequence) - for i := startSequence; i <= uint64(endSequence); i++ { + for i := startSeq; i <= uint64(endSequence); i++ { pkgs, err := a.daoManager.BSCDao.GetPackagesByOracleSequence(i) if err != nil { return err @@ -138,24 +142,24 @@ func (a *BSCAssembler) process(channelId types.ChannelId) error { if !isInturnRelyer && time.Now().Unix() < pkgTime+a.config.RelayConfig.BSCToGreenfieldInturnRelayerTimeout { return nil } - if err := a.processPkgs(pkgs, uint8(channelId), i, nonce, isInturnRelyer); err != nil { + if err := a.processPkgs(pkgs, uint8(channelId), i, a.relayerNonce, isInturnRelyer); err != nil { return err } - logging.Logger.Infof("relayed packages with oracle sequence %d ", i) - nonce++ + logging.Logger.Infof("relayed packages with oracle sequence %d ", i) + a.relayerNonce++ } return nil } func (a *BSCAssembler) processPkgs(pkgs []*model.BscRelayPackage, channelId uint8, sequence uint64, nonce uint64, isInturnRelyer bool) error { // Get votes result for a packages, which are already validated and qualified to aggregate sig + votes, err := a.daoManager.VoteDao.GetVotesByChannelIdAndSequence(channelId, sequence) if err != nil { logging.Logger.Errorf("failed to get votes result for packages for channel %d and sequence %d", channelId, sequence) return err } - validators, err := a.greenfieldExecutor.QueryCachedLatestValidators() if err != nil { return err @@ -170,13 +174,14 @@ func (a *BSCAssembler) processPkgs(pkgs []*model.BscRelayPackage, channelId uint if err != nil { return err } - logging.Logger.Infof("claimed transaction with txHash %s", txHash) + logging.Logger.Infof("claimed transaction with oracle_sequence=%d, txHash=%s", sequence, txHash) var pkgIds []int64 for _, p := range pkgs { pkgIds = append(pkgIds, p.Id) } a.metricService.SetBSCProcessedBlockHeight(pkgs[0].Height) + if !isInturnRelyer { if err = a.daoManager.BSCDao.UpdateBatchPackagesClaimedTxHash(pkgIds, txHash); err != nil { return err @@ -188,8 +193,6 @@ func (a *BSCAssembler) processPkgs(pkgs []*model.BscRelayPackage, channelId uint logging.Logger.Errorf("failed to update packages to 'Delivered', error=%s", err.Error()) return err } - if err = a.daoManager.SequenceDao.Upsert(channelId, sequence+1); err != nil { - return err - } + a.inturnRelayerSequenceStatus.NextDeliverySeq = sequence + 1 return nil } diff --git a/assembler/greenfield_assembler.go b/assembler/greenfield_assembler.go index 5f80e49..6a9ec3d 100644 --- a/assembler/greenfield_assembler.go +++ b/assembler/greenfield_assembler.go @@ -21,31 +21,35 @@ import ( ) type GreenfieldAssembler struct { - mutex sync.RWMutex - config *config.Config - bscExecutor *executor.BSCExecutor - greenfieldExecutor *executor.GreenfieldExecutor - daoManager *dao.DaoManager - blsPubKey []byte - hasRetrievedSequenceByChannelMap map[types.ChannelId]bool // flag for in-turn relayer that if it has requested the sequence from chain during its interval - metricService *metric.MetricService + mutex sync.RWMutex + config *config.Config + bscExecutor *executor.BSCExecutor + greenfieldExecutor *executor.GreenfieldExecutor + daoManager *dao.DaoManager + blsPubKey []byte + inturnRelayerSequenceStatusMap map[types.ChannelId]*types.SequenceStatus // flag for in-turn relayer that if it has requested the sequence from chain during its interval + relayerNonceStatus *types.NonceStatus + metricService *metric.MetricService } func NewGreenfieldAssembler(cfg *config.Config, executor *executor.GreenfieldExecutor, dao *dao.DaoManager, bscExecutor *executor.BSCExecutor, ms *metric.MetricService) *GreenfieldAssembler { channels := cfg.GreenfieldConfig.MonitorChannelList - retrievedSequenceByChannelMap := make(map[types.ChannelId]bool) + inturnRelayerSequenceStatusMap := make(map[types.ChannelId]*types.SequenceStatus) + for _, c := range channels { - retrievedSequenceByChannelMap[types.ChannelId(c)] = false + inturnRelayerSequenceStatusMap[types.ChannelId(c)] = &types.SequenceStatus{} } + return &GreenfieldAssembler{ - config: cfg, - greenfieldExecutor: executor, - daoManager: dao, - bscExecutor: bscExecutor, - blsPubKey: executor.BlsPubKey, - hasRetrievedSequenceByChannelMap: retrievedSequenceByChannelMap, - metricService: ms, + config: cfg, + greenfieldExecutor: executor, + daoManager: dao, + bscExecutor: bscExecutor, + blsPubKey: executor.BlsPubKey, + inturnRelayerSequenceStatusMap: inturnRelayerSequenceStatusMap, + relayerNonceStatus: &types.NonceStatus{}, + metricService: ms, } } @@ -58,41 +62,45 @@ func (a *GreenfieldAssembler) AssembleTransactionsLoop() { logging.Logger.Errorf("encounter error when retrieving in-turn relayer from chain, err=%s ", err.Error()) continue } + inturnRelayerPubkey, err := hex.DecodeString(inturnRelayer.BlsPublicKey) + if err != nil { + logging.Logger.Errorf("encounter error when decode in-turn relayer key, err=%s ", err.Error()) + continue + } + isInturnRelyer := bytes.Equal(a.blsPubKey, inturnRelayerPubkey) + a.metricService.SetBSCInturnRelayerMetrics(isInturnRelyer, inturnRelayer.Start, inturnRelayer.End) + + if (isInturnRelyer && !a.relayerNonceStatus.HasRetrieved) || !isInturnRelyer { + nonce, err := a.bscExecutor.GetNonce() + if err != nil { + logging.Logger.Errorf("encounter error when get relayer nonce, err=%s ", err.Error()) + continue + } + a.relayerNonceStatus.Nonce = nonce + } + wg := new(sync.WaitGroup) - errChan := make(chan error) for _, c := range a.getMonitorChannels() { wg.Add(1) - go a.assembleTransactionAndSendForChannel(types.ChannelId(c), inturnRelayer, errChan, wg) + go a.assembleTransactionAndSendForChannel(types.ChannelId(c), inturnRelayer, isInturnRelyer, wg) } wg.Wait() } } -func (a *GreenfieldAssembler) assembleTransactionAndSendForChannel(channelId types.ChannelId, inturnRelayer *types.InturnRelayer, errChan chan error, wg *sync.WaitGroup) { +func (a *GreenfieldAssembler) assembleTransactionAndSendForChannel(channelId types.ChannelId, inturnRelayer *types.InturnRelayer, isInturnRelyer bool, wg *sync.WaitGroup) { defer wg.Done() - err := a.process(channelId, inturnRelayer) + err := a.process(channelId, inturnRelayer, isInturnRelyer) if err != nil { - errChan <- err + logging.Logger.Errorf("encounter err in assembleTransactionAndSendForChannel, err=%s", err.Error()) } } -func (a *GreenfieldAssembler) process(channelId types.ChannelId, inturnRelayer *types.InturnRelayer) error { - var startSequence uint64 - inturnRelayerPubkey, err := hex.DecodeString(inturnRelayer.BlsPublicKey) - if err != nil { - return err - } - isInturnRelyer := bytes.Equal(a.blsPubKey, inturnRelayerPubkey) - a.metricService.SetBSCInturnRelayerMetrics(isInturnRelyer, inturnRelayer.Start, inturnRelayer.End) +func (a *GreenfieldAssembler) process(channelId types.ChannelId, inturnRelayer *types.InturnRelayer, isInturnRelyer bool) error { + var startSeq uint64 + if isInturnRelyer { - // get next delivered sequence from DB - seq, err := a.daoManager.SequenceDao.GetByChannelId(uint8(channelId)) - if err != nil { - return err - } - startSequence = uint64(seq.Sequence) - // in-turn relayer get the start sequence from chain once during its interval - if !a.hasRetrievedSequenceByChannelMap[channelId] { + if !a.inturnRelayerSequenceStatusMap[channelId].HasRetrieved { now := time.Now().Unix() timeDiff := now - int64(inturnRelayer.Start) if timeDiff < a.config.RelayConfig.BSCSequenceUpdateLatency { @@ -101,18 +109,18 @@ func (a *GreenfieldAssembler) process(channelId types.ChannelId, inturnRelayer * } return nil } - startSequence, err = a.greenfieldExecutor.GetNextDeliverySequenceForChannelWithRetry(channelId) + inTurnRelayerStartSeq, err := a.greenfieldExecutor.GetNextDeliverySequenceForChannelWithRetry(channelId) if err != nil { return err } - if err = a.daoManager.SequenceDao.Upsert(uint8(channelId), startSequence); err != nil { - return err - } a.mutex.Lock() - a.hasRetrievedSequenceByChannelMap[channelId] = true + a.inturnRelayerSequenceStatusMap[channelId].HasRetrieved = true + a.inturnRelayerSequenceStatusMap[channelId].NextDeliverySeq = inTurnRelayerStartSeq a.mutex.Unlock() } - a.metricService.SetNextSequenceForChannelFromDB(uint8(channelId), startSequence) + startSeq = a.inturnRelayerSequenceStatusMap[channelId].NextDeliverySeq + // in-turn relayer get the start sequence from chain once during its interval + a.metricService.SetNextSequenceForChannelFromDB(uint8(channelId), startSeq) seqFromChain, err := a.greenfieldExecutor.GetNextDeliverySequenceForChannelWithRetry(channelId) if err != nil { return err @@ -120,11 +128,11 @@ func (a *GreenfieldAssembler) process(channelId types.ChannelId, inturnRelayer * a.metricService.SetNextSequenceForChannelFromChain(uint8(channelId), seqFromChain) } else { a.mutex.Lock() - a.hasRetrievedSequenceByChannelMap[channelId] = false + a.inturnRelayerSequenceStatusMap[channelId].HasRetrieved = false a.mutex.Unlock() - time.Sleep(time.Duration(a.config.RelayConfig.BSCSequenceUpdateLatency) * time.Second) - startSequence, err = a.greenfieldExecutor.GetNextDeliverySequenceForChannelWithRetry(channelId) + var err error + startSeq, err = a.greenfieldExecutor.GetNextDeliverySequenceForChannelWithRetry(channelId) if err != nil { return err } @@ -137,32 +145,31 @@ func (a *GreenfieldAssembler) process(channelId types.ChannelId, inturnRelayer * if endSequence == -1 { return nil } - nonce, err := a.bscExecutor.GetNonce() - if err != nil { - return err - } + logging.Logger.Debugf("channel %d start seq and end enq are %d and %d", channelId, startSeq, endSequence) - for i := startSequence; i <= uint64(endSequence); i++ { + for i := startSeq; i <= uint64(endSequence); i++ { tx, err := a.daoManager.GreenfieldDao.GetTransactionByChannelIdAndSequence(channelId, i) if err != nil { return err } + if (*tx == model.GreenfieldRelayTransaction{}) { return nil } if tx.Status != db.AllVoted && tx.Status != db.Delivered { return fmt.Errorf("tx with channel id %d and sequence %d does not get enough votes yet", tx.ChannelId, tx.Sequence) } - if !isInturnRelyer && time.Now().Unix() < tx.TxTime+a.config.RelayConfig.GreenfieldToBSCInturnRelayerTimeout { return nil } - if err := a.processTx(tx, nonce, isInturnRelyer); err != nil { + if err := a.processTx(tx, a.relayerNonceStatus.Nonce, isInturnRelyer); err != nil { return err } logging.Logger.Infof("relayed tx with channel id %d and sequence %d ", tx.ChannelId, tx.Sequence) - nonce++ + a.mutex.Lock() + a.relayerNonceStatus.Nonce++ + a.mutex.Unlock() } return nil } @@ -174,6 +181,7 @@ func (a *GreenfieldAssembler) processTx(tx *model.GreenfieldRelayTransaction, no logging.Logger.Errorf("failed to get votes for event with channel id %d and sequence %d", tx.ChannelId, tx.Sequence) return err } + validators, err := a.bscExecutor.QueryCachedLatestValidators() if err != nil { return err @@ -187,6 +195,7 @@ func (a *GreenfieldAssembler) processTx(tx *model.GreenfieldRelayTransaction, no if err != nil { return err } + logging.Logger.Infof("relayed transaction with channel id %d and sequence %d, get txHash %s", tx.ChannelId, tx.Sequence, txHash) a.metricService.SetGnfdProcessedBlockHeight(tx.Height) @@ -202,9 +211,9 @@ func (a *GreenfieldAssembler) processTx(tx *model.GreenfieldRelayTransaction, no if err = a.daoManager.GreenfieldDao.UpdateTransactionStatusAndClaimedTxHash(tx.Id, db.Delivered, txHash.String()); err != nil { return err } - if err = a.daoManager.SequenceDao.Upsert(tx.ChannelId, tx.Sequence+1); err != nil { - return err - } + a.mutex.Lock() + a.inturnRelayerSequenceStatusMap[types.ChannelId(tx.ChannelId)].NextDeliverySeq = tx.Sequence + 1 + a.mutex.Unlock() return nil } diff --git a/common/const.go b/common/const.go index 27e0bc7..b234ac1 100644 --- a/common/const.go +++ b/common/const.go @@ -19,9 +19,7 @@ const ( OracleChannelId types.ChannelId = 0 SleepTimeAfterSyncLightBlock = 15 * time.Second - ListenerPauseTime = 2 * time.Second - ErrorRetryInterval = 1 * time.Second - BroadcastInterval = 500 * time.Millisecond - CollectVoteInterval = 500 * time.Millisecond - AssembleInterval = 500 * time.Millisecond + ListenerPauseTime = 2 * time.Second + ErrorRetryInterval = 1 * time.Second + AssembleInterval = 500 * time.Millisecond ) diff --git a/config/config.go b/config/config.go index d83b8f6..3631c84 100644 --- a/config/config.go +++ b/config/config.go @@ -3,7 +3,6 @@ package config import ( "encoding/json" "fmt" - "math/big" "os" ) @@ -11,6 +10,7 @@ type Config struct { GreenfieldConfig GreenfieldConfig `json:"greenfield_config"` BSCConfig BSCConfig `json:"bsc_config"` RelayConfig RelayConfig `json:"relay_config"` + VotePoolConfig VotePoolConfig `json:"vote_pool_config"` LogConfig LogConfig `json:"log_config"` AdminConfig AdminConfig `json:"admin_config"` AlertConfig AlertConfig `json:"alert_config"` @@ -28,19 +28,43 @@ func (cfg *AdminConfig) Validate() { } type GreenfieldConfig struct { - KeyType string `json:"key_type"` - AWSRegion string `json:"aws_region"` - AWSSecretName string `json:"aws_secret_name"` - AWSBlsSecretName string `json:"aws_bls_secret_name"` - RPCAddrs []string `json:"rpc_addrs"` - GRPCAddrs []string `json:"grpc_addrs"` - PrivateKey string `json:"private_key"` - BlsPrivateKey string `json:"bls_private_key"` - ChainId uint64 `json:"chain_id"` - StartHeight uint64 `json:"start_height"` - MonitorChannelList []uint8 `json:"monitor_channel_list"` - GasLimit uint64 `json:"gas_limit"` - ChainIdString string `json:"chain_id_string"` + KeyType string `json:"key_type"` + AWSRegion string `json:"aws_region"` + AWSSecretName string `json:"aws_secret_name"` + AWSBlsSecretName string `json:"aws_bls_secret_name"` + RPCAddrs []string `json:"rpc_addrs"` + GRPCAddrs []string `json:"grpc_addrs"` + PrivateKey string `json:"private_key"` + BlsPrivateKey string `json:"bls_private_key"` + ChainId uint64 `json:"chain_id"` + StartHeight uint64 `json:"start_height"` + NumberOfBlocksForFinality uint64 `json:"number_of_blocks_for_finality"` + MonitorChannelList []uint8 `json:"monitor_channel_list"` + GasLimit uint64 `json:"gas_limit"` + FeeAmount uint64 `json:"fee_amount"` + ChainIdString string `json:"chain_id_string"` +} + +func (cfg *GreenfieldConfig) Validate() { + if len(cfg.RPCAddrs) == 0 { + panic("provider address of Greenfield should not be empty") + } + + if cfg.KeyType == "" { + panic("key_type Greenfield should not be empty") + } + if cfg.KeyType != KeyTypeLocalPrivateKey && cfg.KeyType != KeyTypeAWSPrivateKey { + panic(fmt.Sprintf("key_type of Greenfield only supports %s and %s", KeyTypeLocalPrivateKey, KeyTypeAWSPrivateKey)) + } + if cfg.KeyType == KeyTypeAWSPrivateKey && cfg.AWSRegion == "" { + panic("aws_region of Greenfield should not be empty") + } + if cfg.KeyType == KeyTypeAWSPrivateKey && cfg.AWSSecretName == "" { + panic("aws_secret_name of Greenfield should not be empty") + } + if cfg.KeyType != KeyTypeAWSPrivateKey && cfg.PrivateKey == "" { + panic("privateKey of Greenfield should not be empty") + } } type BSCConfig struct { @@ -56,18 +80,6 @@ type BSCConfig struct { ChainId uint64 `json:"chain_id"` } -type RelayConfig struct { - BSCToGreenfieldInturnRelayerTimeout int64 `json:"bsc_to_greenfield_inturn_relayer_timeout"` // in second - GreenfieldToBSCInturnRelayerTimeout int64 `json:"greenfield_to_bsc_inturn_relayer_timeout"` // in second - GreenfieldSequenceUpdateLatency int64 `json:"greenfield_sequence_update_latency"` // in second - BSCSequenceUpdateLatency int64 `json:"bsc_sequence_update_latency"` // in second - GreenfieldEventTypeCrossChain string `json:"greenfield_event_type_cross_chain"` - BSCCrossChainPackageEventName string `json:"bsc_cross_chain_package_event_name"` - CrossChainPackageEventHex string `json:"cross_chain_package_event_hex"` - CrossChainContractAddr string `json:"cross_chain_contract_addr"` - GreenfieldLightClientContractAddr string `json:"greenfield_light_client_contract_addr"` -} - func (cfg *BSCConfig) Validate() { if len(cfg.RPCAddrs) == 0 { panic("provider address of Binance Smart Chain should not be empty") @@ -93,6 +105,24 @@ func (cfg *BSCConfig) Validate() { } } +type RelayConfig struct { + BSCToGreenfieldInturnRelayerTimeout int64 `json:"bsc_to_greenfield_inturn_relayer_timeout"` // in second + GreenfieldToBSCInturnRelayerTimeout int64 `json:"greenfield_to_bsc_inturn_relayer_timeout"` // in second + GreenfieldSequenceUpdateLatency int64 `json:"greenfield_sequence_update_latency"` // in second + BSCSequenceUpdateLatency int64 `json:"bsc_sequence_update_latency"` // in second + GreenfieldEventTypeCrossChain string `json:"greenfield_event_type_cross_chain"` + BSCCrossChainPackageEventName string `json:"bsc_cross_chain_package_event_name"` + CrossChainPackageEventHex string `json:"cross_chain_package_event_hex"` + CrossChainContractAddr string `json:"cross_chain_contract_addr"` + GreenfieldLightClientContractAddr string `json:"greenfield_light_client_contract_addr"` +} + +type VotePoolConfig struct { + BroadcastIntervalInMillisecond int64 `json:"broadcast_interval_in_millisecond"` + VotesBatchMaxSizePerInterval int64 `json:"votes_batch_max_size_per_interval"` + QueryIntervalInMillisecond int64 `json:"query_interval_in_millisecond"` +} + type LogConfig struct { Level string `json:"level"` Filename string `json:"filename"` @@ -119,37 +149,9 @@ func (cfg *LogConfig) Validate() { } type AlertConfig struct { - EnableAlert bool `json:"enable_alert"` - EnableHeartBeat bool `json:"enable_heart_beat"` - Interval int64 `json:"interval"` - Identity string `json:"identity"` TelegramBotId string `json:"telegram_bot_id"` TelegramChatId string `json:"telegram_chat_id"` - - BalanceThreshold string `json:"balance_threshold"` - SequenceGapThreshold uint64 `json:"sequence_gap_threshold"` -} - -func (cfg *AlertConfig) Validate() { - if !cfg.EnableAlert { - return - } - if cfg.Interval <= 0 { - panic("alert interval should be positive") - } - balanceThreshold, ok := big.NewInt(1).SetString(cfg.BalanceThreshold, 10) - if !ok { - panic("unrecognized balance_threshold") - } - - if balanceThreshold.Cmp(big.NewInt(0)) <= 0 { - panic("balance_threshold should be positive") - } - - if cfg.SequenceGapThreshold <= 0 { - panic("sequence_gap_threshold should be positive") - } } type DBConfig struct { @@ -160,6 +162,8 @@ type DBConfig struct { Password string `json:"password"` Username string `json:"username"` Url string `json:"url"` + MaxIdleConns int `json:"max_idle_conns"` + MaxOpenConns int `json:"max_open_conns"` } func (cfg *DBConfig) Validate() { @@ -175,7 +179,6 @@ func (cfg *Config) Validate() { cfg.AdminConfig.Validate() cfg.LogConfig.Validate() cfg.BSCConfig.Validate() - cfg.AlertConfig.Validate() cfg.DBConfig.Validate() } diff --git a/config/config.json b/config/config.json index ae4ac82..fb832b5 100644 --- a/config/config.json +++ b/config/config.json @@ -14,8 +14,10 @@ "bls_private_key": "your_private_key", "chain_id": 1, "start_height": 1, + "number_of_blocks_for_finality": 0, "monitor_channel_list": [1,2,3], - "gas_limit": 210000, + "gas_limit": 30000, + "fee_amount": 150000000000000, "chain_id_string": "greenfield_9000-121" }, "bsc_config": { @@ -28,7 +30,7 @@ "private_key": "your_private_key", "gas_limit": 4700000, "gas_price": 20000000000, - "number_of_blocks_for_finality": 10, + "number_of_blocks_for_finality": 2, "start_height": 0, "chain_id": 714 }, @@ -43,6 +45,11 @@ "cross_chain_contract_addr": "0x3a282380958194D1131bC49056abb712Ab98b82B", "greenfield_light_client_contract_addr": "0x60B1E6259944Ea8CEEfFAe2d50Df33EE3CCc593A" }, + "vote_pool_config": { + "broadcast_interval_in_millisecond": 1000, + "votes_batch_max_size_per_interval": 30, + "query_interval_in_millisecond": 1000 + }, "log_config": { "level": "DEBUG", "filename": "", @@ -63,16 +70,13 @@ "aws_secret_name": "", "password": "pass", "username": "root", - "url": "/local-greenfield-relayer0?charset=utf8&parseTime=True&loc=Local" + "url": "/local-greenfield-relayer0?charset=utf8&parseTime=True&loc=Local", + "max_idle_conns": 10, + "max_open_conns": 100 }, "alert_config": { - "enable_alert": true, - "enable_heart_beat": false, - "interval": 300, "identity": "your_service_name", "telegram_bot_id": "your_bot_id", - "telegram_chat_id": "your_chat_id", - "balance_threshold": "1000000000000000000", - "sequence_gap_threshold": 10 + "telegram_chat_id": "your_chat_id" } } \ No newline at end of file diff --git a/config/local/config_local_0.json b/config/local/config_local_0.json index b79e2ad..9189823 100644 --- a/config/local/config_local_0.json +++ b/config/local/config_local_0.json @@ -14,8 +14,10 @@ "bls_private_key": "your_private_key", "chain_id": 18, "start_height": 1, + "number_of_blocks_for_finality": 0, "monitor_channel_list": [1,2,3], - "gas_limit": 210000, + "gas_limit": 1000, + "fee_amount": 5000000000000, "chain_id_string": "greenfield_9000-121" }, "bsc_config": { @@ -28,7 +30,7 @@ "private_key": "your_private_key", "gas_limit": 4700000, "gas_price": 20000000000, - "number_of_blocks_for_finality": 10, + "number_of_blocks_for_finality": 2, "start_height": 0, "chain_id": 714 }, @@ -40,8 +42,13 @@ "greenfield_event_type_cross_chain": "cosmos.crosschain.v1.EventCrossChain", "bsc_cross_chain_package_event_name": "CrossChainPackage", "cross_chain_package_event_hex": "0x64998dc5a229e7324e622192f111c691edccc3534bbea4b2bd90fbaec936845a", - "cross_chain_contract_addr": "0x3a282380958194D1131bC49056abb712Ab98b82B", - "greenfield_light_client_contract_addr": "0x60B1E6259944Ea8CEEfFAe2d50Df33EE3CCc593A" + "cross_chain_contract_addr": "0x1F82F1f3d7a10538920CA1856481f1b5aB782158", + "greenfield_light_client_contract_addr": "0x37aac91D8029DAA9a06AA24178CEd28Fcf378fBf" + }, + "vote_pool_config": { + "broadcast_interval_in_millisecond": 1000, + "votes_batch_max_size_per_interval": 30, + "query_interval_in_millisecond": 1000 }, "log_config": { "level": "DEBUG", @@ -63,16 +70,13 @@ "aws_secret_name": "", "password": "pass", "username": "root", - "url": "/local-greenfield-relayer0?charset=utf8&parseTime=True&loc=Local" + "url": "/local-greenfield-relayer0?charset=utf8&parseTime=True&loc=Local", + "max_idle_conns": 10, + "max_open_conns": 100 }, "alert_config": { - "enable_alert": true, - "enable_heart_beat": false, - "interval": 300, "identity": "your_service_name", "telegram_bot_id": "your_bot_id", - "telegram_chat_id": "your_chat_id", - "balance_threshold": "1000000000000000000", - "sequence_gap_threshold": 10 + "telegram_chat_id": "your_chat_id" } } \ No newline at end of file diff --git a/config/local/config_local_1.json b/config/local/config_local_1.json index 7c4c96e..7153aa5 100644 --- a/config/local/config_local_1.json +++ b/config/local/config_local_1.json @@ -14,8 +14,10 @@ "bls_private_key": "your_private_key", "chain_id": 18, "start_height": 1, + "number_of_blocks_for_finality": 0, "monitor_channel_list": [1,2,3], - "gas_limit": 210000, + "gas_limit": 1000, + "fee_amount": 5000000000000, "chain_id_string": "greenfield_9000-121" }, "bsc_config": { @@ -28,7 +30,7 @@ "private_key": "your_private_key", "gas_limit": 4700000, "gas_price": 20000000000, - "number_of_blocks_for_finality": 10, + "number_of_blocks_for_finality": 2, "start_height": 0, "chain_id": 714 }, @@ -40,8 +42,13 @@ "greenfield_event_type_cross_chain": "cosmos.crosschain.v1.EventCrossChain", "bsc_cross_chain_package_event_name": "CrossChainPackage", "cross_chain_package_event_hex": "0x64998dc5a229e7324e622192f111c691edccc3534bbea4b2bd90fbaec936845a", - "cross_chain_contract_addr": "0x3a282380958194D1131bC49056abb712Ab98b82B", - "greenfield_light_client_contract_addr": "0x60B1E6259944Ea8CEEfFAe2d50Df33EE3CCc593A" + "cross_chain_contract_addr": "0x1F82F1f3d7a10538920CA1856481f1b5aB782158", + "greenfield_light_client_contract_addr": "0x37aac91D8029DAA9a06AA24178CEd28Fcf378fBf" + }, + "vote_pool_config": { + "broadcast_interval_in_millisecond": 1000, + "votes_batch_max_size_per_interval": 30, + "query_interval_in_millisecond": 1000 }, "log_config": { "level": "DEBUG", @@ -63,16 +70,13 @@ "aws_secret_name": "", "password": "pass", "username": "root", - "url": "/local-greenfield-relayer1?charset=utf8&parseTime=True&loc=Local" + "url": "/local-greenfield-relayer1?charset=utf8&parseTime=True&loc=Local", + "max_idle_conns": 10, + "max_open_conns": 100 }, "alert_config": { - "enable_alert": true, - "enable_heart_beat": false, - "interval": 300, "identity": "your_service_name", "telegram_bot_id": "your_bot_id", - "telegram_chat_id": "your_chat_id", - "balance_threshold": "1000000000000000000", - "sequence_gap_threshold": 10 + "telegram_chat_id": "your_chat_id" } } \ No newline at end of file diff --git a/config/local/config_local_2.json b/config/local/config_local_2.json index 07f5b44..b647304 100644 --- a/config/local/config_local_2.json +++ b/config/local/config_local_2.json @@ -14,8 +14,10 @@ "bls_private_key": "your_private_key", "chain_id": 18, "start_height": 1, + "number_of_blocks_for_finality": 0, "monitor_channel_list": [1,2,3], - "gas_limit": 210000, + "gas_limit": 1000, + "fee_amount": 5000000000000, "chain_id_string": "greenfield_9000-121" }, "bsc_config": { @@ -28,7 +30,7 @@ "private_key": "your_private_key", "gas_limit": 4700000, "gas_price": 20000000000, - "number_of_blocks_for_finality": 10, + "number_of_blocks_for_finality": 2, "start_height": 0, "chain_id": 714 }, @@ -40,8 +42,13 @@ "greenfield_event_type_cross_chain": "cosmos.crosschain.v1.EventCrossChain", "bsc_cross_chain_package_event_name": "CrossChainPackage", "cross_chain_package_event_hex": "0x64998dc5a229e7324e622192f111c691edccc3534bbea4b2bd90fbaec936845a", - "cross_chain_contract_addr": "0x3a282380958194D1131bC49056abb712Ab98b82B", - "greenfield_light_client_contract_addr": "0x60B1E6259944Ea8CEEfFAe2d50Df33EE3CCc593A" + "cross_chain_contract_addr": "0x1F82F1f3d7a10538920CA1856481f1b5aB782158", + "greenfield_light_client_contract_addr": "0x37aac91D8029DAA9a06AA24178CEd28Fcf378fBf" + }, + "vote_pool_config": { + "broadcast_interval_in_millisecond": 1000, + "votes_batch_max_size_per_interval": 30, + "query_interval_in_millisecond": 1000 }, "log_config": { "level": "DEBUG", @@ -54,7 +61,7 @@ "compress": false }, "admin_config": { - "port": 8082 + "port": 8080 }, "db_config": { "dialect": "mysql", @@ -63,16 +70,13 @@ "aws_secret_name": "", "password": "pass", "username": "root", - "url": "/local-greenfield-relayer2?charset=utf8&parseTime=True&loc=Local" + "url": "/local-greenfield-relayer2?charset=utf8&parseTime=True&loc=Local", + "max_idle_conns": 10, + "max_open_conns": 100 }, "alert_config": { - "enable_alert": true, - "enable_heart_beat": false, - "interval": 300, "identity": "your_service_name", "telegram_bot_id": "your_bot_id", - "telegram_chat_id": "your_chat_id", - "balance_threshold": "1000000000000000000", - "sequence_gap_threshold": 10 + "telegram_chat_id": "your_chat_id" } } \ No newline at end of file diff --git a/db/dao/bsc_dao.go b/db/dao/bsc_dao.go index b003587..a4c738a 100644 --- a/db/dao/bsc_dao.go +++ b/db/dao/bsc_dao.go @@ -38,9 +38,9 @@ func (d *BSCDao) GetPackagesByStatus(status db.TxStatus) ([]*model.BscRelayPacka return votedTxs, nil } -func (d *BSCDao) GetPackagesByStatusAndHeight(status db.TxStatus, height uint64) ([]*model.BscRelayPackage, error) { +func (d *BSCDao) GetPackagesByHeightAndStatus(status db.TxStatus, height uint64) ([]*model.BscRelayPackage, error) { unVotedTxs := make([]*model.BscRelayPackage, 0) - err := d.DB.Where("status = ? and height = ?", status, height).Find(&unVotedTxs).Order("tx_time asc").Error + err := d.DB.Where("status = ? and height = ?", status, height).Order("height asc").Find(&unVotedTxs).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, err } @@ -86,6 +86,13 @@ func (d *BSCDao) UpdateBatchPackagesStatus(txIds []int64, status db.TxStatus) er }) } +func UpdateBatchPackagesStatus(dbTx *gorm.DB, txIds []int64, status db.TxStatus) error { + return dbTx.Transaction(func(dbTx *gorm.DB) error { + return dbTx.Model(model.BscRelayPackage{}).Where("id IN (?)", txIds).Updates( + model.BscRelayPackage{Status: status, UpdatedTime: time.Now().Unix()}).Error + }) +} + func (d *BSCDao) UpdateBatchPackagesStatusToDelivered(seq uint64) error { return d.DB.Transaction(func(dbTx *gorm.DB) error { return dbTx.Model(model.BscRelayPackage{}).Where("oracle_sequence < ? and status = 2", seq).Updates( diff --git a/db/dao/dao_manager.go b/db/dao/dao_manager.go index 6a5c87a..cee5187 100644 --- a/db/dao/dao_manager.go +++ b/db/dao/dao_manager.go @@ -4,14 +4,12 @@ type DaoManager struct { GreenfieldDao *GreenfieldDao VoteDao *VoteDao BSCDao *BSCDao - SequenceDao *SequenceDao } -func NewDaoManager(greenfieldDao *GreenfieldDao, bscDao *BSCDao, voteDao *VoteDao, seqDao *SequenceDao) *DaoManager { +func NewDaoManager(greenfieldDao *GreenfieldDao, bscDao *BSCDao, voteDao *VoteDao) *DaoManager { return &DaoManager{ GreenfieldDao: greenfieldDao, VoteDao: voteDao, BSCDao: bscDao, - SequenceDao: seqDao, } } diff --git a/db/dao/greenfield_dao.go b/db/dao/greenfield_dao.go index 4b9b103..e4b480e 100644 --- a/db/dao/greenfield_dao.go +++ b/db/dao/greenfield_dao.go @@ -30,18 +30,9 @@ func (d *GreenfieldDao) GetLatestBlock() (*model.GreenfieldBlock, error) { return &block, nil } -func (d *GreenfieldDao) GetTransactionsByStatus(s db.TxStatus) ([]*model.GreenfieldRelayTransaction, error) { +func (d *GreenfieldDao) GetTransactionsByStatusWithLimit(s db.TxStatus, limit int64) ([]*model.GreenfieldRelayTransaction, error) { txs := make([]*model.GreenfieldRelayTransaction, 0) - err := d.DB.Where("status = ? ", s).Find(&txs).Order("tx_time desc").Error - if err != nil && err != gorm.ErrRecordNotFound { - return nil, err - } - return txs, nil -} - -func (d *GreenfieldDao) GetTransactionsByStatusAndHeight(status db.TxStatus, height uint64) ([]*model.GreenfieldRelayTransaction, error) { - txs := make([]*model.GreenfieldRelayTransaction, 0) - err := d.DB.Where("status = ? and height = ?", status, height).Find(&txs).Order("tx_time asc").Error + err := d.DB.Where("status = ? ", s).Order("height asc").Limit(int(limit)).Find(&txs).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, err } @@ -86,6 +77,12 @@ func (d *GreenfieldDao) UpdateTransactionStatus(id int64, status db.TxStatus) er return err } +func UpdateTransactionStatus(dbTx *gorm.DB, id int64, status db.TxStatus) error { + err := dbTx.Model(model.GreenfieldRelayTransaction{}).Where("id = ?", id).Updates( + model.GreenfieldRelayTransaction{Status: status, UpdatedTime: time.Now().Unix()}).Error + return err +} + func (d *GreenfieldDao) UpdateTransactionClaimedTxHash(id int64, claimedTxHash string) error { return d.DB.Transaction(func(dbTx *gorm.DB) error { return dbTx.Model(model.GreenfieldRelayTransaction{}).Where("id = ?", id).Updates( diff --git a/db/dao/sequence_dao.go b/db/dao/sequence_dao.go deleted file mode 100644 index 6691508..0000000 --- a/db/dao/sequence_dao.go +++ /dev/null @@ -1,47 +0,0 @@ -package dao - -import ( - "gorm.io/gorm" - "gorm.io/gorm/clause" - - "github.com/bnb-chain/greenfield-relayer/common" - "github.com/bnb-chain/greenfield-relayer/db/model" -) - -const OFFSET = 100 - -type SequenceDao struct { - DB *gorm.DB -} - -func NewSequenceDao(db *gorm.DB) *SequenceDao { - return &SequenceDao{ - DB: db, - } -} - -func (d *SequenceDao) GetByChannelId(channelId uint8) (*model.Sequence, error) { - if channelId == uint8(common.OracleChannelId) { - channelId = channelId + OFFSET - } - seq := model.Sequence{} - err := d.DB.Where("channel_id = ?", channelId).Find(&seq).Error - if err != nil && err != gorm.ErrRecordNotFound { - return nil, err - } - return &seq, nil -} - -func (d *SequenceDao) Upsert(channelId uint8, sequence uint64) error { - if channelId == uint8(common.OracleChannelId) { - channelId = channelId + OFFSET - } - seq := model.Sequence{ - ChannelId: channelId, - Sequence: int64(sequence), - } - return d.DB.Clauses(clause.OnConflict{ - Columns: []clause.Column{{Name: "channel_id"}}, - DoUpdates: clause.AssignmentColumns([]string{"sequence"}), - }).Create(&seq).Error -} diff --git a/db/dao/vote_dao.go b/db/dao/vote_dao.go index 80968b3..98f93e2 100644 --- a/db/dao/vote_dao.go +++ b/db/dao/vote_dao.go @@ -53,12 +53,28 @@ func (d *VoteDao) IsVoteExist(channelId uint8, sequence uint64, pubKey string) ( return exists, nil } +func IsVoteExist(dbTx *gorm.DB, channelId uint8, sequence uint64, pubKey string) (bool, error) { + exists := false + if err := dbTx.Raw( + "SELECT EXISTS(SELECT id FROM vote WHERE channel_id = ? and sequence = ? and pub_key = ?)", + channelId, sequence, pubKey).Scan(&exists).Error; err != nil { + return false, err + } + return exists, nil +} + func (d *VoteDao) SaveVote(vote *model.Vote) error { return d.DB.Transaction(func(dbTx *gorm.DB) error { return dbTx.Create(vote).Error }) } +func SaveVote(dbTx *gorm.DB, vote *model.Vote) error { + return dbTx.Transaction(func(dbTx *gorm.DB) error { + return dbTx.Create(vote).Error + }) +} + func (d *VoteDao) SaveBatchVotes(votes []*model.Vote) error { return d.DB.Transaction(func(dbTx *gorm.DB) error { return dbTx.Create(votes).Error diff --git a/db/model/bsc_model.go b/db/model/bsc_model.go index f796ab3..9adb635 100644 --- a/db/model/bsc_model.go +++ b/db/model/bsc_model.go @@ -21,7 +21,7 @@ func (*BscBlock) TableName() string { type BscRelayPackage struct { Id int64 ChannelId uint8 `gorm:"NOT NULL"` - OracleSequence uint64 `gorm:"NOT NULL"` + OracleSequence uint64 `gorm:"NOT NULL;index:idx_bsc_relay_package_oracle_sequence"` PackageSequence uint64 `gorm:"NOT NULL"` PayLoad string `gorm:"type:text"` TxIndex uint `gorm:"NOT NULL"` diff --git a/db/model/sequence_model.go b/db/model/sequence_model.go deleted file mode 100644 index dfc84c4..0000000 --- a/db/model/sequence_model.go +++ /dev/null @@ -1,24 +0,0 @@ -package model - -import ( - "gorm.io/gorm" -) - -// Sequence used to store next delivery sequence for channels -type Sequence struct { - ChannelId uint8 `gorm:"primaryKey"` - Sequence int64 `gorm:"NOT NULL"` -} - -func (*Sequence) TableName() string { - return "sequence" -} - -func InitSequenceTable(db *gorm.DB) { - if !db.Migrator().HasTable(&Sequence{}) { - err := db.Migrator().CreateTable(&Sequence{}) - if err != nil { - panic(err) - } - } -} diff --git a/db/model/votepool_model.go b/db/model/votepool_model.go index 01c602d..1982112 100644 --- a/db/model/votepool_model.go +++ b/db/model/votepool_model.go @@ -10,9 +10,9 @@ type Vote struct { EventType uint32 `gorm:"NOT NULL"` ClaimPayload []byte `gorm:"NOT NULL"` EventHash []byte `gorm:"NOT NULL"` - Sequence uint64 `gorm:"NOT NULL;index:idx_vote_channel_id_sequence_pub_key"` - ChannelId uint8 `gorm:"NOT NULL;index:idx_vote_channel_id_sequence_pub_key"` - PubKey string `gorm:"NOT NULL;index:idx_vote_channel_id_sequence_pub_key"` + Sequence uint64 `gorm:"NOT NULL;uniqueIndex:idx_vote_channel_id_sequence_pub_key"` + ChannelId uint8 `gorm:"NOT NULL;uniqueIndex:idx_vote_channel_id_sequence_pub_key"` + PubKey string `gorm:"NOT NULL;uniqueIndex:idx_vote_channel_id_sequence_pub_key;size:96"` CreatedTime int64 `gorm:"NOT NULL"` } diff --git a/executor/bsc_executor.go b/executor/bsc_executor.go index d43924d..6c6680b 100644 --- a/executor/bsc_executor.go +++ b/executor/bsc_executor.go @@ -246,7 +246,7 @@ func (e *BSCExecutor) GetNextReceiveSequenceForChannelWithRetry(channelID rtypes relayercommon.RtyDelay, relayercommon.RtyErr, retry.OnRetry(func(n uint, err error) { - logging.Logger.Infof("failed to query sequence for channel %d, attempt: %d times, max_attempts: %d", channelID, n+1, relayercommon.RtyAttNum) + logging.Logger.Errorf("failed to query sequence for channel %d, attempt: %d times, max_attempts: %d", channelID, n+1, relayercommon.RtyAttNum) })) } diff --git a/executor/greenfield_executor.go b/executor/greenfield_executor.go index 34d6a5a..53c10ae 100644 --- a/executor/greenfield_executor.go +++ b/executor/greenfield_executor.go @@ -6,7 +6,6 @@ import ( "encoding/json" _ "encoding/json" "fmt" - "github.com/prysmaticlabs/prysm/crypto/bls/blst" "time" "github.com/avast/retry-go/v4" @@ -15,6 +14,7 @@ import ( crosschaintypes "github.com/cosmos/cosmos-sdk/x/crosschain/types" oracletypes "github.com/cosmos/cosmos-sdk/x/oracle/types" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/prysmaticlabs/prysm/crypto/bls/blst" "github.com/spf13/viper" "github.com/tendermint/tendermint/rpc/client" ctypes "github.com/tendermint/tendermint/rpc/core/types" @@ -282,10 +282,14 @@ func (e *GreenfieldExecutor) ClaimPackages(payloadBts []byte, aggregatedSig []by voteAddressSet, aggregatedSig, ) + txRes, err := e.getGnfdClient().BroadcastTx( []sdk.Msg{msgClaim}, &sdktypes.TxOption{ - Nonce: nonce, + NoSimulate: true, + GasLimit: e.config.GreenfieldConfig.GasLimit, + FeeAmount: sdk.NewCoins(sdk.NewCoin(sdktypes.Denom, sdk.NewInt(int64(e.config.GreenfieldConfig.FeeAmount)))), + Nonce: nonce, }, ) if err != nil { diff --git a/go.mod b/go.mod index bee1242..599192b 100644 --- a/go.mod +++ b/go.mod @@ -157,8 +157,8 @@ require ( replace ( cosmossdk.io/math => github.com/bnb-chain/greenfield-cosmos-sdk/math v0.0.0-20230228075616-68ac309b432c - github.com/bnb-chain/greenfield => github.com/bnb-chain/greenfield v0.0.11 - github.com/cosmos/cosmos-sdk => github.com/bnb-chain/greenfield-cosmos-sdk v0.0.14 + github.com/bnb-chain/greenfield => github.com/bnb-chain/greenfield v0.1.0 + github.com/cosmos/cosmos-sdk => github.com/bnb-chain/greenfield-cosmos-sdk v0.1.0 github.com/ferranbt/fastssz => github.com/prysmaticlabs/fastssz v0.0.0-20220110145812-fafb696cae88 github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1 github.com/grpc-ecosystem/grpc-gateway/v2 => github.com/prysmaticlabs/grpc-gateway/v2 v2.3.1-0.20210702154020-550e1cd83ec1 diff --git a/go.sum b/go.sum index 6dae64e..17a40c5 100644 --- a/go.sum +++ b/go.sum @@ -154,10 +154,10 @@ github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQ github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84= github.com/bmizerany/pat v0.0.0-20170815010413-6226ea591a40/go.mod h1:8rLXio+WjiTceGBHIoTvn60HIbs7Hm7bcHjyrSqYB9c= -github.com/bnb-chain/greenfield v0.0.11 h1:uH++LV0oenWsSCpVC1OBiohhBEBHC+ZWe+vrcF7j4JM= -github.com/bnb-chain/greenfield v0.0.11/go.mod h1:v5/zA5+Sd/BNlgkM08YPdDV73ZXikmy9UQfCURTX+rU= -github.com/bnb-chain/greenfield-cosmos-sdk v0.0.14 h1:57q0qusqgA3bhzVGo4hXHHXYpWlXRFYfg/dP3Y7BUfs= -github.com/bnb-chain/greenfield-cosmos-sdk v0.0.14/go.mod h1:rvAY7ga/AakZWyYkA1zAsNtvKpdoyRFZTqF4MhFYzZ8= +github.com/bnb-chain/greenfield v0.1.0 h1:H2Xe45HcZ7ts6OBKKE9wiTUmiQg2yCSf/X8XPt1P6V4= +github.com/bnb-chain/greenfield v0.1.0/go.mod h1:7344f+97RhnkZPOIE/uHdF5u6Awwyhfb/TgIA6nQhXA= +github.com/bnb-chain/greenfield-cosmos-sdk v0.1.0 h1:uKTjLxB4+EKry79hbCM32QmRcUSRMVbDCwOfV7xrvOo= +github.com/bnb-chain/greenfield-cosmos-sdk v0.1.0/go.mod h1:rvAY7ga/AakZWyYkA1zAsNtvKpdoyRFZTqF4MhFYzZ8= github.com/bnb-chain/greenfield-cosmos-sdk/math v0.0.0-20230228075616-68ac309b432c h1:BLmdYaj7Dx0YOhfk77+KPPJSMCwpQl6f4Y30+801bf0= github.com/bnb-chain/greenfield-cosmos-sdk/math v0.0.0-20230228075616-68ac309b432c/go.mod h1:u/MXvf8wbUbCsAEyQSSYXXMsczAsFX48e2D6JI86T4o= github.com/bnb-chain/greenfield-go-sdk v0.0.8 h1:eBhhdek0o9NnRVAeDOVJVyP3y3a/ym5ZuZWEbV5Nrco= diff --git a/integrationtest/config/config_test.json b/integrationtest/config/config_test.json index ed50ead..c171b64 100644 --- a/integrationtest/config/config_test.json +++ b/integrationtest/config/config_test.json @@ -14,8 +14,10 @@ "bls_private_key": "your_private_key", "chain_id": 18, "start_height": 1, + "number_of_blocks_for_finality": 0, "monitor_channel_list": [1,2,3], - "gas_limit": 210000, + "gas_limit": 30000, + "fee_amount": 150000000000000, "chain_id_string": "greenfield_9000-121" }, "bsc_config": { @@ -28,7 +30,7 @@ "private_key": "your_private_key", "gas_limit": 4700000, "gas_price": 20000000000, - "number_of_blocks_for_finality": 10, + "number_of_blocks_for_finality": 2, "start_height": 0, "chain_id": 714 }, @@ -40,8 +42,13 @@ "greenfield_event_type_cross_chain": "cosmos.crosschain.v1.EventCrossChain", "bsc_cross_chain_package_event_name": "CrossChainPackage", "cross_chain_package_event_hex": "0x64998dc5a229e7324e622192f111c691edccc3534bbea4b2bd90fbaec936845a", - "cross_chain_contract_addr": "0xd2253A26e6d5b729dDBf4bCce5A78F93C725b455", - "greenfield_light_client_contract_addr": "0x349a42f907c7562B3aaD4431780E4596bC2a053f" + "cross_chain_contract_addr": "0x1F82F1f3d7a10538920CA1856481f1b5aB782158", + "greenfield_light_client_contract_addr": "0x37aac91D8029DAA9a06AA24178CEd28Fcf378fBf" + }, + "vote_pool_config": { + "broadcast_interval_in_millisecond": 1000, + "votes_batch_max_size_per_interval": 30, + "query_interval_in_millisecond": 1000 }, "log_config": { "level": "DEBUG", @@ -63,16 +70,13 @@ "aws_secret_name": "", "password": "pass", "username": "root", - "url": "/local-greenfield-relayer0?charset=utf8&parseTime=True&loc=Local" + "url": "/local-greenfield-relayer0?charset=utf8&parseTime=True&loc=Local", + "max_idle_conns": 10, + "max_open_conns": 100 }, "alert_config": { - "enable_alert": true, - "enable_heart_beat": false, - "interval": 300, "identity": "your_service_name", "telegram_bot_id": "your_bot_id", - "telegram_chat_id": "your_chat_id", - "balance_threshold": "1000000000000000000", - "sequence_gap_threshold": 10 + "telegram_chat_id": "your_chat_id" } } \ No newline at end of file diff --git a/listener/greenfield_listener.go b/listener/greenfield_listener.go index d2eb897..d4cdd15 100644 --- a/listener/greenfield_listener.go +++ b/listener/greenfield_listener.go @@ -19,27 +19,23 @@ import ( "github.com/bnb-chain/greenfield-relayer/executor" "github.com/bnb-chain/greenfield-relayer/logging" "github.com/bnb-chain/greenfield-relayer/metric" - "github.com/bnb-chain/greenfield-relayer/types" "github.com/bnb-chain/greenfield-relayer/util" - "github.com/bnb-chain/greenfield-relayer/vote" ) type GreenfieldListener struct { config *config.Config greenfieldExecutor *executor.GreenfieldExecutor bscExecutor *executor.BSCExecutor - voteProcessor *vote.GreenfieldVoteProcessor DaoManager *dao.DaoManager metricService *metric.MetricService } func NewGreenfieldListener(cfg *config.Config, gnfdExecutor *executor.GreenfieldExecutor, bscExecutor *executor.BSCExecutor, - voteProcessor *vote.GreenfieldVoteProcessor, dao *dao.DaoManager, ms *metric.MetricService) *GreenfieldListener { + dao *dao.DaoManager, ms *metric.MetricService) *GreenfieldListener { return &GreenfieldListener{ config: cfg, greenfieldExecutor: gnfdExecutor, bscExecutor: bscExecutor, - voteProcessor: voteProcessor, DaoManager: dao, metricService: ms, } @@ -120,7 +116,7 @@ func (l *GreenfieldListener) monitorTxEvents(height uint64, txRes []*abci.Respon for _, tx := range txRes { for _, event := range tx.Events { if event.Type == l.config.RelayConfig.GreenfieldEventTypeCrossChain { - relayTx, err := l.constructRelayTxAndBroadcast(event, height) + relayTx, err := constructRelayTx(event, height) if err != nil { errChan <- err return @@ -135,7 +131,7 @@ func (l *GreenfieldListener) monitorEndBlockEvents(height uint64, endBlockEvents defer wg.Done() for _, e := range endBlockEvents { if e.Type == l.config.RelayConfig.GreenfieldEventTypeCrossChain { - relayTx, err := l.constructRelayTxAndBroadcast(e, height) + relayTx, err := constructRelayTx(e, height) if err != nil { errChan <- err return @@ -253,30 +249,6 @@ func (l *GreenfieldListener) sync(nextHeight uint64, validatorsHash string) erro return nil } -func (l *GreenfieldListener) broadCastTx(tx *model.GreenfieldRelayTransaction) error { - return l.voteProcessor.SignAndBroadcast(tx) -} - -func (l *GreenfieldListener) constructRelayTxAndBroadcast(event abci.Event, height uint64) (*model.GreenfieldRelayTransaction, error) { - relayTx, err := constructRelayTx(event, height) - if err != nil { - return nil, err - } - filled, err := l.isTxSequenceFilled(relayTx) - if err != nil { - return nil, err - } - if filled { - relayTx.Status = db.Delivered - return relayTx, nil - } - if err = l.broadCastTx(relayTx); err != nil { - return nil, err - } - relayTx.Status = db.SelfVoted - return relayTx, nil -} - func constructRelayTx(event abci.Event, height uint64) (*model.GreenfieldRelayTransaction, error) { relayTx := model.GreenfieldRelayTransaction{} for _, attr := range event.Attributes { @@ -344,11 +316,3 @@ func constructRelayTx(event abci.Event, height uint64) (*model.GreenfieldRelayTr relayTx.UpdatedTime = time.Now().Unix() return &relayTx, nil } - -func (l *GreenfieldListener) isTxSequenceFilled(tx *model.GreenfieldRelayTransaction) (bool, error) { - nextDeliverySequence, err := l.greenfieldExecutor.GetNextDeliverySequenceForChannelWithRetry(types.ChannelId(tx.ChannelId)) - if err != nil { - return false, err - } - return tx.Sequence < nextDeliverySequence, nil -} diff --git a/relayer/greenfield_relayer.go b/relayer/greenfield_relayer.go index 97e60f9..27c1ef4 100644 --- a/relayer/greenfield_relayer.go +++ b/relayer/greenfield_relayer.go @@ -28,6 +28,7 @@ func NewGreenfieldRelayer(listener *listener.GreenfieldListener, greenfieldExecu func (r *GreenfieldRelayer) Start() { go r.MonitorEventsLoop() + go r.SignAndBroadcastLoop() go r.CollectVotesLoop() go r.AssembleTransactionsLoop() go r.UpdateCachedLatestValidatorsLoop() @@ -38,6 +39,10 @@ func (r *GreenfieldRelayer) MonitorEventsLoop() { r.Listener.StartLoop() } +func (r *GreenfieldRelayer) SignAndBroadcastLoop() { + r.voteProcessor.SignAndBroadcastLoop() +} + func (r *GreenfieldRelayer) CollectVotesLoop() { r.voteProcessor.CollectVotesLoop() } diff --git a/types/types.go b/types/types.go index 13f03b3..e2d8440 100644 --- a/types/types.go +++ b/types/types.go @@ -30,3 +30,13 @@ type CrossChainPackageEvent struct { ChannelId uint8 Payload []byte } + +type SequenceStatus struct { + HasRetrieved bool + NextDeliverySeq uint64 +} + +type NonceStatus struct { + HasRetrieved bool + Nonce uint64 +} diff --git a/vote/bsc_vote_processor.go b/vote/bsc_vote_processor.go index 9af2d38..e287914 100644 --- a/vote/bsc_vote_processor.go +++ b/vote/bsc_vote_processor.go @@ -47,7 +47,7 @@ func NewBSCVoteProcessor(cfg *config.Config, dao *dao.DaoManager, signer *VoteSi } func (p *BSCVoteProcessor) SignAndBroadcastVoteLoop() { - ticker := time.NewTicker(common.BroadcastInterval) + ticker := time.NewTicker(time.Duration(p.config.VotePoolConfig.BroadcastIntervalInMillisecond) * time.Millisecond) for range ticker.C { if err := p.signAndBroadcast(); err != nil { logging.Logger.Errorf("encounter error, err: %s", err.Error()) @@ -55,7 +55,7 @@ func (p *BSCVoteProcessor) SignAndBroadcastVoteLoop() { } } -// SignAndBroadcastVoteLoop Will sign using the bls private key, and broadcast the vote to votepool +// SignAndBroadcastVoteLoop signs using the bls private key, and broadcast the vote to votepool func (p *BSCVoteProcessor) signAndBroadcast() error { latestHeight, err := p.bscExecutor.GetLatestBlockHeightWithRetry() if err != nil { @@ -72,7 +72,7 @@ func (p *BSCVoteProcessor) signAndBroadcast() error { if leastSavedPkgHeight+p.config.BSCConfig.NumberOfBlocksForFinality > latestHeight { return nil } - pkgs, err := p.daoManager.BSCDao.GetPackagesByStatusAndHeight(db.Saved, leastSavedPkgHeight) + pkgs, err := p.daoManager.BSCDao.GetPackagesByHeightAndStatus(db.Saved, leastSavedPkgHeight) if err != nil { logging.Logger.Errorf("failed to get packages at height %d from db, error: %s", leastSavedPkgHeight, err.Error()) return err @@ -151,18 +151,18 @@ func (p *BSCVoteProcessor) signAndBroadcast() error { } err = p.daoManager.BSCDao.DB.Transaction(func(dbTx *gorm.DB) error { - err := p.daoManager.BSCDao.UpdateBatchPackagesStatus(pkgIds, db.SelfVoted) - if err != nil { - return err + e := dao.UpdateBatchPackagesStatus(dbTx, pkgIds, db.SelfVoted) + if e != nil { + return e } - exist, err := p.daoManager.VoteDao.IsVoteExist(uint8(channelId), seq, hex.EncodeToString(v.PubKey[:])) - if err != nil { - return err + exist, e := dao.IsVoteExist(dbTx, uint8(channelId), seq, hex.EncodeToString(v.PubKey[:])) + if e != nil { + return e } if !exist { - err = p.daoManager.VoteDao.SaveVote(EntityToDto(v, uint8(channelId), seq, encodedPayload)) - if err != nil { - return err + e = dao.SaveVote(dbTx, EntityToDto(v, uint8(channelId), seq, encodedPayload)) + if e != nil { + return e } } return nil @@ -175,7 +175,7 @@ func (p *BSCVoteProcessor) signAndBroadcast() error { } func (p *BSCVoteProcessor) CollectVotesLoop() { - ticker := time.NewTicker(common.CollectVoteInterval) + ticker := time.NewTicker(time.Duration(p.config.VotePoolConfig.QueryIntervalInMillisecond) * time.Millisecond) for range ticker.C { if err := p.collectVotes(); err != nil { logging.Logger.Errorf("encounter error, err: %s", err.Error()) diff --git a/vote/greenfield_vote_processor.go b/vote/greenfield_vote_processor.go index 80a46bc..9ece7e9 100644 --- a/vote/greenfield_vote_processor.go +++ b/vote/greenfield_vote_processor.go @@ -38,7 +38,6 @@ type GreenfieldVoteProcessor struct { func NewGreenfieldVoteProcessor(cfg *config.Config, dao *dao.DaoManager, signer *VoteSigner, greenfieldExecutor *executor.GreenfieldExecutor) *GreenfieldVoteProcessor { - return &GreenfieldVoteProcessor{ config: cfg, daoManager: dao, @@ -48,59 +47,100 @@ func NewGreenfieldVoteProcessor(cfg *config.Config, dao *dao.DaoManager, signer } } -func (p *GreenfieldVoteProcessor) SignAndBroadcast(tx *model.GreenfieldRelayTransaction) error { - isFilled, err := p.isTxSequenceFilled(tx) - if err != nil { - return err - } - if isFilled { - if err = p.daoManager.GreenfieldDao.UpdateTransactionStatus(tx.Id, db.Delivered); err != nil { - return err +// SignAndBroadcastLoop signs tx using the relayer's bls private key, then broadcasts the vote to Greenfield votepool +func (p *GreenfieldVoteProcessor) SignAndBroadcastLoop() { + ticker := time.NewTicker(time.Duration(p.config.VotePoolConfig.BroadcastIntervalInMillisecond) * time.Millisecond) + for range ticker.C { + if err := p.signAndBroadcast(); err != nil { + logging.Logger.Errorf("encounter error, err: %s", err.Error()) } - logging.Logger.Infof("sequence %d for channel %d has already been filled ", tx.Sequence, tx.ChannelId) - return nil } +} - aggregatedPayload, err := p.aggregatePayloadForTx(tx) +func (p *GreenfieldVoteProcessor) signAndBroadcast() error { + latestHeight, err := p.greenfieldExecutor.GetLatestBlockHeight() if err != nil { + logging.Logger.Errorf("failed to get latest block height, error: %s", err.Error()) return err } - v := p.constructVoteAndSign(aggregatedPayload) - // broadcast v - if err = retry.Do(func() error { - err = p.greenfieldExecutor.BroadcastVote(v) - if err != nil { - return fmt.Errorf("failed to submit vote for event with channel id %d and sequence %d", tx.ChannelId, tx.Sequence) - } + leastSavedTxHeight, err := p.daoManager.GreenfieldDao.GetLeastSavedTransactionHeight() + if err != nil { + logging.Logger.Errorf("failed to get least saved tx height, error: %s", err.Error()) + return err + } + if leastSavedTxHeight+p.config.GreenfieldConfig.NumberOfBlocksForFinality > latestHeight { return nil - }, retry.Context(context.Background()), rcommon.RtyAttem, rcommon.RtyDelay, rcommon.RtyErr); err != nil { + } + txs, err := p.daoManager.GreenfieldDao.GetTransactionsByStatusWithLimit(db.Saved, p.config.VotePoolConfig.VotesBatchMaxSizePerInterval) + if err != nil { + logging.Logger.Errorf("failed to get transactions from db, error: %s", err.Error()) return err } + if len(txs) == 0 { + return nil + } + // for every tx, we are going to sign it and broadcast vote of it. + for _, tx := range txs { - // After vote submitted to vote pool, persist vote Data and update the status of tx to 'SELF_VOTED'. - err = p.daoManager.GreenfieldDao.DB.Transaction(func(dbTx *gorm.DB) error { - err = p.daoManager.GreenfieldDao.UpdateTransactionStatus(tx.Id, db.SelfVoted) + // in case there is chance that reprocessing same transactions(caused by DB data loss) or processing outdated + // transactions from block( when relayer need to catch up others), this ensures relayer will skip to next transaction directly + isFilled, err := p.isTxSequenceFilled(tx) if err != nil { return err } - exist, err := p.daoManager.VoteDao.IsVoteExist(tx.ChannelId, tx.Sequence, hex.EncodeToString(v.PubKey[:])) + if isFilled { + if err = p.daoManager.GreenfieldDao.UpdateTransactionStatus(tx.Id, db.Delivered); err != nil { + return err + } + logging.Logger.Infof("sequence %d for channel %d has already been filled ", tx.Sequence, tx.ChannelId) + continue + } + + aggregatedPayload, err := p.aggregatePayloadForTx(tx) if err != nil { return err } - if !exist { - err = p.daoManager.VoteDao.SaveVote(EntityToDto(v, tx.ChannelId, tx.Sequence, aggregatedPayload)) + v := p.constructVoteAndSign(aggregatedPayload) + + // broadcast v + if err = retry.Do(func() error { + logging.Logger.Debugf("broadcasting vote with c %d and seq %d", tx.ChannelId, tx.Sequence) + + err = p.greenfieldExecutor.BroadcastVote(v) if err != nil { - return err + return fmt.Errorf("failed to submit vote for event with channel id %d and sequence %d", tx.ChannelId, tx.Sequence) } + return nil + }, retry.Context(context.Background()), rcommon.RtyAttem, rcommon.RtyDelay, rcommon.RtyErr); err != nil { + return err } - return nil - }) - return err + + // After vote submitted to vote pool, persist vote Data and update the status of tx to 'SELF_VOTED'. + err = p.daoManager.GreenfieldDao.DB.Transaction(func(dbTx *gorm.DB) error { + if e := dao.UpdateTransactionStatus(dbTx, tx.Id, db.SelfVoted); e != nil { + return e + } + exist, e := dao.IsVoteExist(dbTx, tx.ChannelId, tx.Sequence, hex.EncodeToString(v.PubKey[:])) + if e != nil { + return e + } + if !exist { + if e = dao.SaveVote(dbTx, EntityToDto(v, tx.ChannelId, tx.Sequence, aggregatedPayload)); e != nil { + return e + } + } + return nil + }) + if err != nil { + return err + } + } + return nil } func (p *GreenfieldVoteProcessor) CollectVotesLoop() { - ticker := time.NewTicker(rcommon.CollectVoteInterval) + ticker := time.NewTicker(time.Duration(p.config.VotePoolConfig.QueryIntervalInMillisecond) * time.Millisecond) for range ticker.C { if err := p.collectVotes(); err != nil { logging.Logger.Errorf("encounter error, err: %s", err.Error()) @@ -109,7 +149,7 @@ func (p *GreenfieldVoteProcessor) CollectVotesLoop() { } func (p *GreenfieldVoteProcessor) collectVotes() error { - txs, err := p.daoManager.GreenfieldDao.GetTransactionsByStatus(db.SelfVoted) + txs, err := p.daoManager.GreenfieldDao.GetTransactionsByStatusWithLimit(db.SelfVoted, p.config.VotePoolConfig.VotesBatchMaxSizePerInterval) if err != nil { logging.Logger.Errorf("failed to get voted transactions from db, error: %s", err.Error()) return err @@ -207,6 +247,7 @@ func (p *GreenfieldVoteProcessor) queryMoreThanTwoThirdVotesForTx(localVote *mod return errors.New("exceed max retry") } + logging.Logger.Debugf("query vote for c %d and s %d", channelId, seq) queriedVotes, err := p.greenfieldExecutor.QueryVotesByEventHashAndType(localVote.EventHash, votepool.ToBscCrossChainEvent) if err != nil { return err @@ -342,6 +383,8 @@ func (p *GreenfieldVoteProcessor) isTxSequenceFilled(tx *model.GreenfieldRelayTr } func (p *GreenfieldVoteProcessor) reBroadcastVote(localVote *model.Vote) error { + logging.Logger.Debugf("broadcasting vote with c %d and seq %d", localVote.ChannelId, localVote.Sequence) + v, err := DtoToEntity(localVote) if err != nil { return err